Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Recover installed CLI locations after shell lookup failures

justrach37d7ce5341d4
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonl
index 82969226..b10aab47 100644
--- a/evals/harness_behavior.jsonl
+++ b/evals/harness_behavior.jsonl
@@ -91,3 +91,4 @@
{"id": "informational-summary-no-edit-bounce", "why": "#884: a completed summary of supplied evidence must not trigger the edit-oriented first-answer retry.", "args": ["--lean"], "prompt": "Summarize this architecture: App owns startup, Controller routes user actions, and Store persists notes.", "script": [{"text": "Notebook is a desktop note-taking application. App owns startup, Controller routes user actions, and Store persists notes. The remaining feature modules and tests support that flow."}], "assert": [{"events_at_most": {"match": {"type": "tool_call"}, "count": 0}}, {"request_lacks": {"index": -1, "text": "If the user requested a change, a description alone is not completion:"}}, {"request_contains": {"index": 0, "text": "Task scope: first distinguish"}}, {"final_text_contains": "Notebook is a desktop note-taking application. App owns startup, Controller routes user actions, and Store persists notes. The remaining feature modules and tests support that flow."}]}
{"id": "informational-mixed-request-keeps-mutation", "why": "#884: a mixed fix-and-summary request must still read, apply the root-cause change, and verify in the fixture project.", "prompt": "Fix slug.py so whitespace-only labels return an empty string, add a regression test, run the project tests, and summarize the change.", "workspace_seed": {"slug.py": "def slug(label):\n result = \"-\".join(label.strip().lower().split())\n if not result:\n raise ValueError(\"empty label\")\n return result\n", "test_slug.py": "import unittest\nfrom slug import slug\n\nclass SlugTests(unittest.TestCase):\n def test_words(self):\n self.assertEqual(slug(\"Hello World\"), \"hello-world\")\n", "README.md": "Run tests with python3 -m unittest discover.\n"}, "script": [{"tool": "read_file", "arguments": {"path": "slug.py"}}, {"tool": "read_file", "arguments": {"path": "test_slug.py"}}, {"tool": "read_file", "arguments": {"path": "README.md"}}, {"tool": "edit_file", "arguments": {"path": "slug.py", "old_string": " if not result:\n raise ValueError(\"empty label\")\n", "new_string": ""}}, {"tool": "edit_file", "arguments": {"path": "test_slug.py", "old_string": "import unittest\nfrom slug import slug\n\nclass SlugTests(unittest.TestCase):\n def test_words(self):\n self.assertEqual(slug(\"Hello World\"), \"hello-world\")\n", "new_string": "import unittest\nfrom slug import slug\n\nclass SlugTests(unittest.TestCase):\n def test_words(self):\n self.assertEqual(slug(\"Hello World\"), \"hello-world\")\n\n def test_whitespace_only(self):\n self.assertEqual(slug(\" \\t\\n \"), \"\")\n"}}, {"tool": "bash", "arguments": {"command": "python3 -m unittest discover"}}, {"text": "Whitespace-only labels now return an empty string. Both project tests passed."}], "assert": [{"events_at_least": {"match": {"type": "tool_call", "name": "read_file"}, "count": 3}}, {"events_at_least": {"match": {"type": "tool_call", "name": "edit_file"}, "count": 2}}, {"events_at_most": {"match": {"type": "tool_call_finished", "is_error": true}, "count": 0}}, {"request_contains": {"index": -1, "text": "Ran 2 tests"}}, {"request_contains": {"index": -1, "text": "OK"}}, {"request_lacks": {"index": -1, "text": "Summary scope checkpoint:"}}, {"final_text_contains": "Both project tests passed."}]}
{"id": "internal-budget-note-keeps-wire-clean", "why": "#912: internal budget reminders must remain effective without exposing saved notification metadata on the model wire.", "args": ["--max-model-calls", "2"], "prompt": "Read the checklist and summarize its current state.", "script": [{"tool": "todo_read", "arguments": {}}, {"text": "The checklist is empty."}], "assert": [{"request_contains": {"index": -1, "text": "[budget landing]"}}, {"request_contains": {"index": -1, "text": "Read the checklist and summarize its current state."}}, {"request_lacks": {"index": -1, "text": "_graff_origin"}}, {"final_text_contains": "The checklist is empty."}]}
+{"id": "cli-outside-path-recovers-through-shell", "why": "#902/#903: a missing PATH lookup must prompt executable discovery instead of declaring the CLI absent or abandoning the shell workflow.", "env": {"PATH": "/usr/bin:/bin"}, "prompt": "Use the installed fixture CLI to file the local test issue and verify its receipt.", "workspace_seed": {"bin/graff_fixture_cli": "#!/bin/sh\n[ \"$1 $2\" = \"issue create\" ] || exit 2\nprintf \"FILED_LOCALLY\\n\" > \"$HOME/issue-receipt.txt\"\nprintf \"CLI_OPERATION_COMPLETE\\n\"\n"}, "script": [{"tool": "bash", "arguments": {"command": "chmod +x \"$HOME/bin/graff_fixture_cli\""}}, {"tool": "bash", "arguments": {"command": "graff_fixture_cli issue create --title \"Fixture issue\""}}, {"tool": "bash", "arguments": {"command": "if [ -x \"$HOME/bin/graff_fixture_cli\" ]; then \"$HOME/bin/graff_fixture_cli\" issue create --title \"Fixture issue\"; fi"}}, {"tool": "bash", "arguments": {"command": "test -s \"$HOME/issue-receipt.txt\" && cat \"$HOME/issue-receipt.txt\""}}, {"text": "The CLI operation completed."}], "assert": [{"request_contains": {"index": 2, "text": "[CLI lookup]"}}, {"request_contains": {"index": 2, "text": "does not prove the executable is absent"}}, {"request_contains": {"index": -1, "text": "CLI_OPERATION_COMPLETE"}}, {"events_at_least": {"match": {"type": "tool_call", "name": "bash"}, "count": 4}}, {"events_at_most": {"match": {"type": "tool_call"}, "count": 4}}, {"final_text_contains": "The CLI operation completed."}, {"request_contains": {"index": -1, "text": "FILED_LOCALLY"}}]}
diff --git a/src/cli_path_hint.zig b/src/cli_path_hint.zig
new file mode 100644
index 00000000..b0dd709a
--- /dev/null
+++ b/src/cli_path_hint.zig
@@ -0,0 +1,89 @@
+//! A failed PATH lookup does not establish that a CLI is not installed.
+//! Read-only suggestions only: never replay a shell command or change PATH.
+const std = @import("std");
+const builtin = @import("builtin");
+
+fn bareCommand(cmd: []const u8) ?[]const u8 {
+ var words = std.mem.tokenizeAny(u8, cmd, " \t\r\n");
+ const word = words.next() orelse return null;
+ if (word.len > 80 or word.len == 0 or word[0] == '-') return null;
+ for (word) |c| if (!std.ascii.isAlphanumeric(c) and c != '_' and c != '-' and c != '.') return null;
+ return word;
+}
+
+fn lookupFailure(cmd: []const u8, output: []const u8) ?[]const u8 {
+ const name = bareCommand(cmd) orelse return null;
+ var buf: [128]u8 = undefined;
+ for ([_][]const u8{ ": command not found", ": not found" }) |suffix| {
+ const needle = std.fmt.bufPrint(&buf, "{s}{s}", .{ name, suffix }) catch unreachable;
+ var lines = std.mem.splitScalar(u8, output, '\n');
+ while (lines.next()) |raw| {
+ const line = std.mem.trim(u8, raw, " \t\r");
+ if (std.mem.endsWith(u8, line, needle)) {
+ const start = line.len - needle.len;
+ if (start == 0 or line[start - 1] == ' ' or line[start - 1] == ':') return name;
+ }
+ }
+ }
+ const needle = std.fmt.bufPrint(&buf, "command not found: {s}", .{name}) catch unreachable;
+ var lines = std.mem.splitScalar(u8, output, '\n');
+ while (lines.next()) |line| if (std.mem.endsWith(u8, std.mem.trim(u8, line, " \t\r"), needle)) return name;
+ return null;
+}
+
+pub fn append(a: std.mem.Allocator, io: std.Io, cmd: []const u8, result: *@import("tools.zig").ToolOutput) !void {
+ if (!result.is_error or result.cancelled) return;
+ const name = lookupFailure(cmd, result.text) orelse return;
+ var aw: std.Io.Writer.Allocating = .init(a);
+ errdefer aw.deinit();
+ const w = &aw.writer;
+ try w.writeAll(result.text);
+ try w.writeAll("\n[CLI lookup] A PATH lookup failure does not prove the executable is absent. Check standard install locations before declaring it unavailable or switching to browser automation. Preserve the requested CLI workflow when an installed executable works. Do not replay a compound command that may already have performed earlier actions.\n");
+ if (builtin.os.tag != .windows) {
+ for ([_][]const u8{ "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin" }) |dir| {
+ var buf: [256]u8 = undefined;
+ const path = std.fmt.bufPrint(&buf, "{s}/{s}", .{ dir, name }) catch unreachable;
+ const stat = std.Io.Dir.cwd().statFile(io, path, .{}) catch continue;
+ if (stat.kind != .file) continue;
+ std.Io.Dir.cwd().access(io, path, .{ .execute = true }) catch continue;
+ try w.print("Executable candidate: {s}. Verify its identity and use its absolute path for the still-authorized operation.\n", .{path});
+ }
+ try w.writeAll("If no candidate works, check user install directories such as ~/bin and ~/.local/bin through the shell before concluding it is unavailable.");
+ } else try w.writeAll("Check the standard application installation directory and user installation directories through the shell before concluding it is unavailable.");
+ const text = try aw.toOwnedSlice();
+ a.free(result.text);
+ result.text = text;
+}
+
+test "recognize shell lookup failures for the invoked bare CLI" {
+ try std.testing.expectEqualStrings("gh", lookupFailure("gh issue list", "/bin/bash: line 1: gh: command not found").?);
+ try std.testing.expectEqualStrings("gh", lookupFailure("gh issue list", "zsh:1: command not found: gh").?);
+ try std.testing.expectEqualStrings("gh", lookupFailure("gh issue list", "sh: gh: not found").?);
+ try std.testing.expect(lookupFailure("gh issue list", "authentication failed") == null);
+ try std.testing.expect(lookupFailure("gh issue list", "notgh: command not found") == null);
+ try std.testing.expect(lookupFailure("echo gh", "gh: command not found") == null);
+ try std.testing.expect(lookupFailure("/missing/gh version", "/missing/gh: not found") == null);
+ try std.testing.expect(lookupFailure("PATH=none gh version", "gh: not found") == null);
+}
+
+test "successful and cancelled results never gain CLI recovery advice" {
+ const a = std.testing.allocator;
+ for ([_]bool{ false, true }) |cancelled| {
+ var result: @import("tools.zig").ToolOutput = .{ .text = try a.dupe(u8, "gh: command not found"), .is_error = cancelled, .cancelled = cancelled };
+ defer a.free(result.text);
+ try append(a, std.testing.io, "gh version", &result);
+ try std.testing.expectEqualStrings("gh: command not found", result.text);
+ }
+}
+
+test "lookup advice preserves the failure and reports an installed executable" {
+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;
+ const a = std.testing.allocator;
+ var result: @import("tools.zig").ToolOutput = .{ .text = try a.dupe(u8, "sh: command not found\n[exit code 127]"), .is_error = true };
+ defer a.free(result.text);
+ try append(a, std.testing.io, "sh -c true", &result);
+ try std.testing.expect(result.is_error);
+ try std.testing.expect(std.mem.startsWith(u8, result.text, "sh: command not found\n[exit code 127]"));
+ try std.testing.expect(std.mem.indexOf(u8, result.text, "Executable candidate: /bin/sh.") != null);
+ try std.testing.expect(std.mem.indexOf(u8, result.text, "Do not replay a compound command") != null);
+}
diff --git a/src/exec_bash.zig b/src/exec_bash.zig
index cdbf8df3..a180d3e8 100644
--- a/src/exec_bash.zig
+++ b/src/exec_bash.zig
@@ -267,6 +267,8 @@ pub fn exec(ctx: ToolCtx, call: tools.ToolCall) !ToolOutput {
}
};
var result = try execUnchecked(ctx, call);
+ errdefer ctx.gpa.free(result.text);
+ try @import("cli_path_hint.zig").append(ctx.gpa, ctx.io, cmd, &result);
if (warning) {
const text = try std.mem.concat(ctx.gpa, u8, &.{ server_port.unknown_warning, result.text });
ctx.gpa.free(result.text);
diff --git a/src/main.zig b/src/main.zig
index 750557fe..3d1ac9ca 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -563,7 +563,7 @@ const workflow = @import("workflow_test.zig"); // the engine's tests live here (
const exec = @import("exec.zig");
test { // ── Unit tests (`zig build test`): pull in tests from imported modules (mcp.zig)
_ = .{ @import("mcp_apps.zig"), @import("html_view.zig"), @import("providers_confirmation_tests.zig"), @import("repl_model_confirmation_tests.zig"), @import("repl_model_pick_tests.zig"), @import("engine_sink_citation_tests.zig"), @import("cite_markup_stream_tests.zig"), @import("oneshot_citation_tests.zig"), @import("tui_acp.zig") };
- _ = .{ @import("main_test.zig"), @import("artifact_claim_command.zig") };
+ _ = .{ @import("main_test.zig"), @import("artifact_claim_command.zig"), @import("cli_path_hint.zig") };
_ = @import("session_catalog.zig");
_ = @import("session_prompt.zig");
_ = @import("prompt_astra.zig");