Skip to content

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

Python

Answer mistyped slash commands locally over ACP (#1275)

Rach Pradhan101bf011e355
diff --git a/TUI/catalog.zig b/TUI/catalog.zig
index 559ca491..c0443c1b 100644
--- a/TUI/catalog.zig
+++ b/TUI/catalog.zig
@@ -86,6 +86,29 @@ pub fn filter(needle: []const u8, out: []usize) usize {
return n;
}
+/// Every spelling lookup() accepts, names first, for suggest().
+const spellings = blk: {
+ var n: usize = 0;
+ for (items) |it| n += 1 + it.aliases.len;
+ var arr: [n][]const u8 = undefined;
+ var i: usize = 0;
+ for (items) |it| {
+ arr[i] = it.name;
+ i += 1;
+ }
+ for (items) |it| for (it.aliases) |a| {
+ arr[i] = a;
+ i += 1;
+ };
+ break :blk arr;
+};
+
+/// The command a mistyped `token` most likely meant (#1275), from the same
+/// speller the REPL/ACP catalog uses, so `/resuem` gets one answer everywhere.
+pub fn suggest(token: []const u8) ?[]const u8 {
+ return @import("slash_suggest").nearest(token, &spellings);
+}
+
fn eqlIgnoreCase(a: []const u8, b: []const u8) bool {
return std.ascii.eqlIgnoreCase(a, b);
}
@@ -119,3 +142,11 @@ test "filter: slash prefix and alias" {
test "catalog names start with slash" {
for (items) |it| try std.testing.expect(it.name.len > 1 and it.name[0] == '/');
}
+
+test "suggest (#1275): a typo names the command; paths and noise do not" {
+ try std.testing.expectEqualStrings("/resume", suggest("/resuem").?);
+ try std.testing.expectEqualStrings("/help", suggest("/hlep").?);
+ try std.testing.expectEqualStrings("/settings", suggest("/setings").?);
+ try std.testing.expect(suggest("/banana") == null);
+ try std.testing.expect(suggest("/usr/bin/foo") == null);
+}
diff --git a/TUI/dispatch.zig b/TUI/dispatch.zig
index 750dca63..5153fbdc 100644
--- a/TUI/dispatch.zig
+++ b/TUI/dispatch.zig
@@ -277,6 +277,8 @@ pub fn runCommand(self: *Model, line: []const u8) Effect {
} else {
return applyLine(self, arg);
}
+ } else if (catalog.suggest(cmd)) |near| {
+ self.pushFmt(.err, "unknown command: {s} — did you mean {s}?", .{ cmd, near }) catch {};
} else {
self.pushFmt(.err, "unknown command: {s} — try /help", .{cmd}) catch {};
}
diff --git a/TUI/dispatch_command_tests.zig b/TUI/dispatch_command_tests.zig
index a89334d0..cd836f42 100644
--- a/TUI/dispatch_command_tests.zig
+++ b/TUI/dispatch_command_tests.zig
@@ -264,6 +264,17 @@ test "every slash name printed in /help dispatches" {
try std.testing.expect(seen >= 9);
}
+test "a mistyped command is refused locally with the nearest spelling (#1275)" {
+ var m: Model = undefined;
+ m.setup(std.testing.allocator);
+ defer m.deinit();
+ try std.testing.expectEqual(Effect.stay, applyLine(&m, "/resuem"));
+ try std.testing.expect(m.pending == null); // no model turn
+ try std.testing.expectEqualStrings("unknown command: /resuem — did you mean /resume?", m.history.items[m.history.items.len - 1].text);
+ _ = applyLine(&m, "/xyzzy");
+ try std.testing.expectEqualStrings("unknown command: /xyzzy — try /help", m.history.items[m.history.items.len - 1].text);
+}
+
test "/image attaches a path the next send carries as @[path]" {
var m: Model = undefined;
m.setup(std.testing.allocator);
diff --git a/build.zig b/build.zig
index b0235cb2..7031ed2d 100644
--- a/build.zig
+++ b/build.zig
@@ -67,12 +67,21 @@ pub fn build(b: *std.Build) void {
.optimize = optimize,
});
exe.root_module.addImport("models_rank", models_rank_mod);
+ // Same reason: one nearest-command speller for the REPL/ACP catalog and
+ // the TUI catalog (#1275).
+ const slash_suggest_mod = b.createModule(.{
+ .root_source_file = b.path("src/slash_suggest.zig"),
+ .target = target,
+ .optimize = optimize,
+ });
+ exe.root_module.addImport("slash_suggest", slash_suggest_mod);
const tui_mod = b.createModule(.{
.root_source_file = b.path("TUI/root.zig"),
.target = target,
.optimize = optimize,
});
tui_mod.addImport("models_rank", models_rank_mod);
+ tui_mod.addImport("slash_suggest", slash_suggest_mod);
exe.root_module.addImport("tui", tui_mod);
const install_graff = b.addInstallArtifact(exe, .{});
b.getInstallStep().dependOn(&install_graff.step);
@@ -107,6 +116,7 @@ pub fn build(b: *std.Build) void {
unit_tests.root_module.addImport("accord", accord_mod);
unit_tests.root_module.addImport("http_zig", http_zig_mod);
unit_tests.root_module.addImport("models_rank", models_rank_mod);
+ unit_tests.root_module.addImport("slash_suggest", slash_suggest_mod);
unit_tests.root_module.addImport("tui", tui_mod);
// spec/ fixtures live outside src/; importing them here makes @embedFile
// legal and rebuilds the suite when the exported semantics change.
@@ -161,6 +171,9 @@ pub fn build(b: *std.Build) void {
const acp_images_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-images.py" });
acp_images_test.addArtifactArg(exe);
test_step.dependOn(&acp_images_test.step);
+ const acp_slash_typo_test = b.addSystemCommand(&.{ "python3", "scripts/test-acp-slash-typo.py" });
+ acp_slash_typo_test.addArtifactArg(exe);
+ test_step.dependOn(&acp_slash_typo_test.step);
const run_tool_budget_test = b.addSystemCommand(&.{ "python3", "scripts/test-run-tool-budget.py" });
run_tool_budget_test.addArtifactArg(exe);
test_step.dependOn(&run_tool_budget_test.step);
@@ -215,6 +228,7 @@ pub fn build(b: *std.Build) void {
}),
});
tui_exe.root_module.addImport("models_rank", models_rank_mod);
+ tui_exe.root_module.addImport("slash_suggest", slash_suggest_mod);
b.installArtifact(tui_exe);
const tui_tests = b.addTest(.{
@@ -232,6 +246,7 @@ pub fn build(b: *std.Build) void {
.filters = test_filters,
});
tui_tests.root_module.addImport("models_rank", models_rank_mod);
+ tui_tests.root_module.addImport("slash_suggest", slash_suggest_mod);
tui_tests.root_module.addAnonymousImport("spec_terminal_modes", .{ .root_source_file = b.path("spec/kernels/terminal_modes.json") });
const tui_test_step = b.step("tui-test", "Run fullscreen TUI unit tests");
diff --git a/scripts/test-acp-slash-typo.py b/scripts/test-acp-slash-typo.py
new file mode 100755
index 00000000..50d6739c
--- /dev/null
+++ b/scripts/test-acp-slash-typo.py
@@ -0,0 +1,67 @@
+#!/usr/bin/env python3
+"""Offline ACP slash parity (#1275): a mistyped `/command` is answered locally
+with the terminal's refusal and nearest spelling, exactly like the TUI refuses
+it, and never costs a model turn. Paths and prose still reach the model."""
+import importlib.util
+import json
+import sys
+import tempfile
+from pathlib import Path
+
+REPO = Path(__file__).resolve().parents[1]
+sys.path.insert(0, str(REPO / "scripts/eval"))
+from mock_model import ScriptedModel
+
+_spec = importlib.util.spec_from_file_location("acp_session_load_fixture", REPO / "scripts/test-acp-session-load.py")
+_fixture = importlib.util.module_from_spec(_spec)
+_spec.loader.exec_module(_fixture)
+Acp = _fixture.Acp
+
+
+def reply_text(a, start):
+ """Concatenated agent_message_chunk text among events recorded since `start`."""
+ out = []
+ for e in a.events[start:]:
+ update = e.get("params", {}).get("update", {})
+ if update.get("sessionUpdate") == "agent_message_chunk":
+ out.append(update.get("content", {}).get("text", ""))
+ return "".join(out)
+
+
+def run(binary):
+ with tempfile.TemporaryDirectory(prefix="graff-acp-slash-typo-") as temporary:
+ base = Path(temporary).resolve()
+ cwd, home = base / "work", base / "home"
+ cwd.mkdir()
+ home.mkdir()
+ model = ScriptedModel([{"text": "path prompt answered"}])
+ port = model.start(0)
+ a = Acp(binary, cwd, home, port)
+ try:
+ a.request("initialize", {"protocolVersion": 1})
+ sid = a.request("session/new", {"cwd": str(cwd), "mcpServers": []})["result"]["sessionId"]
+
+ def prompt(text):
+ start = len(a.events)
+ turn = a.request("session/prompt", {"sessionId": sid, "prompt": [{"type": "text", "text": text}]}, 35)
+ assert turn["result"]["stopReason"] == "end_turn", turn
+ return reply_text(a, start)
+
+ typo = prompt("/resuem")
+ assert "unknown command '/resuem'" in typo and "did you mean /resume?" in typo, typo
+ far = prompt("/xyzzy now")
+ assert "unknown command '/xyzzy'" in far and "/help for the list" in far, far
+ assert model.requests == [], "a mistyped command must never reach the model"
+
+ passed = prompt("/tmp/x.png what is in this file?")
+ assert "path prompt answered" in passed, passed
+ assert len(model.requests) == 1, len(model.requests)
+ assert "/tmp/x.png what is in this file?" in json.dumps(model.requests[0]["messages"][-1])
+ finally:
+ a.close()
+ model.stop()
+ print("ACP slash typo: answered locally with a suggestion, no model call; paths still reach the model: ok")
+
+
+if __name__ == "__main__":
+ run(Path(sys.argv[1] if len(sys.argv) > 1 else REPO / "zig-out/bin/graff").resolve())
diff --git a/src/acp.zig b/src/acp.zig
index e88793a7..a00d5881 100644
--- a/src/acp.zig
+++ b/src/acp.zig
@@ -65,9 +65,10 @@ fn liveCancelled() bool {
/// A slash command typed in a client runs the same handler the REPL runs,
/// so the menu the agent advertises is not a menu of things that then get
-/// sent to the model as prose. Anything outside the catalog returns null
-/// and stays an ordinary prompt. Pickers here find no TTY and fall back to
-/// printing their list, so nothing waits on a keypress that cannot come.
+/// sent to the model as prose. A command-shaped `/word` outside the catalog
+/// gets the terminal's own refusal + nearest spelling (#1275), not a model
+/// turn; paths and prose return null and stay ordinary prompts. Pickers here
+/// find no TTY and fall back to printing their list.
fn liveSlash(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror!?[]const u8 {
if (@import("review.zig").promptFromLine(text) != null) return null;
if (@import("issue_cmd.zig").promptFromLine(text) != null) return null;
@@ -78,8 +79,8 @@ fn liveSlash(ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror!?[]co
_ = try playbook_glue.command(live.root, arena, text, &aw.writer);
return try engine.stripSgr(arena, aw.writer.buffered());
}
- if (command_catalog.match(text) == null) return null;
- try main_mod.handleCommand(live.root, live.keys, arena, text, &aw.writer);
+ if (command_catalog.match(text) == null and command_catalog.commandWord(text) == null) return null;
+ try main_mod.handleCommand(live.root, live.keys, arena, std.mem.trim(u8, text, " \t\r\n"), &aw.writer);
return try engine.stripSgr(arena, aw.writer.buffered());
}
diff --git a/src/command_catalog.zig b/src/command_catalog.zig
index 246693fe..604bf834 100644
--- a/src/command_catalog.zig
+++ b/src/command_catalog.zig
@@ -9,6 +9,7 @@
//! /help dump (it falls back to `name` when empty). `desc` is the one-liner.
const std = @import("std");
+const slash_suggest = @import("slash_suggest");
/// One catalog entry. `name`/`desc` are the same two fields the generic
/// listPicker items carry (pickers.PickItem = this type), so both are always
@@ -30,6 +31,34 @@ pub fn match(line: []const u8) ?Item {
return null;
}
+/// Spellings the handlers accept that are not catalog entries (each runs the
+/// entry named in its comment). suggest() offers them like any name.
+pub const aliases = [_][]const u8{
+ "/constraint", // /never
+ "/ws", // /workspace
+ "/adopt", // /import-claude
+};
+
+/// The first word of `line` when it is command-shaped: `/` then letters,
+/// digits, `-` or `_`, ended by whitespace or the end of the line. A path
+/// (`/usr/bin/foo`, `/tmp/x.png`), `/**`, or text that merely contains a
+/// `/word` later on is not a command and stays an ordinary prompt.
+pub fn commandWord(line: []const u8) ?[]const u8 {
+ const t = std.mem.trim(u8, line, " \t\r\n");
+ if (t.len < 2 or t[0] != '/') return null;
+ const word = t[0 .. std.mem.indexOfAny(u8, t, " \t\r\n") orelse t.len];
+ for (word[1..]) |c| if (!(std.ascii.isAlphanumeric(c) or c == '-' or c == '_')) return null;
+ return word;
+}
+
+/// The command `word` most likely misspells (#1275): the nearest catalog
+/// name or alias by edit distance, or null when nothing is close. Shared by
+/// the terminal refusal (commands_misc.handleRest) and, through it, ACP.
+pub fn suggest(word: []const u8) ?[]const u8 {
+ const candidates = comptime names ++ aliases;
+ return slash_suggest.nearest(word, &candidates);
+}
+
pub const commands = [_]Item{
.{ .name = "/model", .usage = "/model [<provider>] <name>", .desc = "switch model/provider, fuzzy match (e.g. \"sonnet\", \"opus\"); name a provider to pin the seat" },
.{ .name = "/models", .usage = "/models [health]", .desc = "list known models: context window, compaction point, provider and what that seat costs (plan/credits/api/local); health shows live state" },
@@ -121,3 +150,37 @@ test "catalog is well-formed and names track commands" {
try std.testing.expectEqualStrings(command.name, name);
}
}
+
+test "suggest (#1275): typos find the command, unrelated words do not" {
+ try std.testing.expectEqualStrings("/resume", suggest("/resuem").?); // transposition
+ try std.testing.expectEqualStrings("/help", suggest("/hlep").?);
+ try std.testing.expectEqualStrings("/model", suggest("/modle").?);
+ try std.testing.expectEqualStrings("/compact", suggest("/compcat").?);
+ try std.testing.expectEqualStrings("/sessions", suggest("/sesions").?); // deletion
+ try std.testing.expectEqualStrings("/resume", suggest("/Resume").?); // case only
+ try std.testing.expectEqualStrings("/constraint", suggest("/constrant").?); // aliases count
+ // Too far from every name, or too short to guess at.
+ try std.testing.expect(suggest("/banana") == null);
+ try std.testing.expect(suggest("/xyzzy") == null);
+ try std.testing.expect(suggest("/zz") == null);
+ try std.testing.expect(suggest("/") == null);
+ var long: [81]u8 = undefined;
+ @memset(&long, 'a');
+ long[0] = '/';
+ try std.testing.expect(suggest(&long) == null); // past the speller's length cap
+}
+
+test "commandWord (#1275): paths and prose are not commands" {
+ try std.testing.expectEqualStrings("/resuem", commandWord("/resuem").?);
+ try std.testing.expectEqualStrings("/resuem", commandWord(" /resuem last ").?);
+ try std.testing.expectEqualStrings("/pr-acceptance", commandWord("/pr-acceptance draft").?);
+ try std.testing.expectEqualStrings("/foo", commandWord("/foo\nsecond line").?);
+ try std.testing.expect(commandWord("/usr/bin/foo") == null);
+ try std.testing.expect(commandWord("/usr/bin/foo explain this") == null);
+ try std.testing.expect(commandWord("/tmp/x.png") == null);
+ try std.testing.expect(commandWord("/x.png what is this") == null);
+ try std.testing.expect(commandWord("/**\n * doc comment\n */") == null);
+ try std.testing.expect(commandWord("please /resuem") == null);
+ try std.testing.expect(commandWord("/") == null);
+ try std.testing.expect(commandWord("") == null);
+}
diff --git a/src/commands_misc.zig b/src/commands_misc.zig
index cb14d169..f8ea0d49 100644
--- a/src/commands_misc.zig
+++ b/src/commands_misc.zig
@@ -470,9 +470,14 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
/// /help dumps the full command list. Always handles `line` — never returns
/// "unhandled" — so callers just `try` it after every tryHandle() misses.
pub fn handleRest(line: []const u8, out: *Io.Writer) !void {
- // Unknown slash command → a short error + pointer (only /help dumps the list).
+ // Unknown slash command → a short error + the nearest spelling (#1275), or
+ // a pointer to /help (only /help dumps the list). ACP answers with this too.
if (!std.mem.eql(u8, line, "/help")) {
- try out.print("unknown command '{s}' — /help for the list\n", .{line});
+ const word = line[0 .. std.mem.indexOfAny(u8, line, " \t\r\n") orelse line.len];
+ if (command_catalog.suggest(word)) |near|
+ try out.print("unknown command '{s}' — did you mean {s}?\n", .{ word, near })
+ else
+ try out.print("unknown command '{s}' — /help for the list\n", .{word});
try out.flush();
return;
}
diff --git a/src/slash_suggest.zig b/src/slash_suggest.zig
new file mode 100644
index 00000000..11d367e0
--- /dev/null
+++ b/src/slash_suggest.zig
@@ -0,0 +1,62 @@
+//! Nearest-spelling lookup for a mistyped slash command (#1275).
+//!
+//! Its own module so the line REPL / ACP catalog (src/command_catalog.zig) and
+//! the fullscreen TUI catalog (TUI/catalog.zig) share one implementation: a
+//! file import from both modules is illegal in Zig 0.17 (see models_rank).
+//! Tests live with the callers, which the test roots reach.
+
+const std = @import("std");
+
+/// No command is this long, so nothing longer is a typo of one.
+pub const max_len = 64;
+
+/// Optimal-string-alignment distance: Levenshtein plus one adjacent
+/// transposition (`resuem` -> `resume` is 1), ASCII case-insensitive.
+/// null when either side is longer than max_len.
+pub fn distance(a: []const u8, b: []const u8) ?usize {
+ if (a.len > max_len or b.len > max_len) return null;
+ var prev2: [max_len + 1]usize = undefined;
+ var prev: [max_len + 1]usize = undefined;
+ var cur: [max_len + 1]usize = undefined;
+ for (0..b.len + 1) |j| prev[j] = j;
+ for (a, 1..) |ca, i| {
+ cur[0] = i;
+ for (b, 1..) |cb, j| {
+ const cost: usize = if (eq(ca, cb)) 0 else 1;
+ var d = @min(@min(prev[j] + 1, cur[j - 1] + 1), prev[j - 1] + cost);
+ if (i > 1 and j > 1 and eq(ca, b[j - 2]) and eq(a[i - 2], cb)) d = @min(d, prev2[j - 2] + 1);
+ cur[j] = d;
+ }
+ prev2 = prev;
+ prev = cur;
+ }
+ return prev[b.len];
+}
+
+fn eq(x: u8, y: u8) bool {
+ return std.ascii.toLower(x) == std.ascii.toLower(y);
+}
+
+/// Edits tolerated for a word of `len` letters: none under 3 (too many
+/// two-letter commands to guess between), 1 up to 5, then 2.
+pub fn threshold(len: usize) usize {
+ return @min(2, len / 3);
+}
+
+/// The candidate `word` most likely misspells, or null when none is within
+/// threshold. Both sides may carry the leading `/`; ties keep list order.
+pub fn nearest(word: []const u8, candidates: []const []const u8) ?[]const u8 {
+ const w = std.mem.trimStart(u8, word, "/");
+ if (w.len == 0) return null;
+ const limit = threshold(w.len);
+ var best: ?[]const u8 = null;
+ var best_d: usize = limit + 1;
+ for (candidates) |c| {
+ const d = distance(w, std.mem.trimStart(u8, c, "/")) orelse continue;
+ if (d < best_d) {
+ best = c;
+ best_d = d;
+ }
+ }
+ return best;
+}