graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: preserve project layout breadth and suggest nearby directories
Rach Pradhan07356fe61315
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c30f93ed..3123de4f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,9 @@ current is part of cutting a release.## Unreleased+- Project layout selection favors breadth across directories, with explicit+ truncation notices. Missing `codedb list_dir` paths suggest close siblings+ without relaxing confinement or changing constraint policy (ADR 0093).- Bare `codedb context <task>` defaults to on-device retrieval. Remotereranking remains an explicit opt-in and is refused under local-onlypolicy (ADR 0084, ADR 0092).diff --git a/docs/adr/0084-codedb-context-honors-local-only.md b/docs/adr/0084-codedb-context-honors-local-only.mdindex b9f2f5e0..225114b4 100644--- a/docs/adr/0084-codedb-context-honors-local-only.md+++ b/docs/adr/0084-codedb-context-honors-local-only.md@@ -27,6 +27,6 @@ ordinary reads to codedb-pro (ADR 0040).- Callers can enforce the boundary with `local_only` even when policy filesare silent.- Hybrid is opt-in (`--hybrid` / `--semantic`); bare `context` is `--local`- (ADR 0086). Policy still refuses those remote flags before spawn.+ (ADR 0092). Policy still refuses those remote flags before spawn.- Revisit only if codedb grows a stronger in-process local composer thatgraff should prefer over `--local`.diff --git a/docs/adr/0093-project-layout-breadth-and-directory-hints.md b/docs/adr/0093-project-layout-breadth-and-directory-hints.mdnew file mode 100644index 00000000..ff7fa4a8--- /dev/null+++ b/docs/adr/0093-project-layout-breadth-and-directory-hints.md@@ -0,0 +1,32 @@+# 0093. Project layout favors breadth and missing paths offer siblings++Status: accepted 2026-09-09++## Context++Depth-first selection can exhaust the project-layout budget inside one+subtree and hide other top-level entries. A misspelled directory then+produces an unhelpful not-found response.++## Decision++Select layout entries breadth-first and round-robin across directories,+while retaining the readable depth-first output order and existing caps.+Report truncation and the top-level directories not fully expanded.+A capped layout is not proof that an omitted path is absent.++For a missing `codedb list_dir` path, offer close sibling names and a+bounded parent listing, subject to the existing confinement and ignore+rules. Keep the response an error; a suggestion is not a successful read.++## Constraints++This integrates the navigation portion of #767 only. Its older constraint+policy is superseded by ADR 0090 and is not adopted. Durable constraints+still require explicit project scope and exact current-user text.++## Verification++The layout and near-miss module tests cover bounded selection and sibling+matching. The `list-dir-near-miss-hint` tier-2 case checks that the tool+result exposes the suggested directory to the next model request.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex c171d046..a85e9ed5 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -102,6 +102,7 @@ record only when you need the evidence or the edge cases.| [0089](0089-canonical-compaction-windows-survive-recovery.md) | Preserve standalone compaction windows across pruning and resume; opaque recovery uses the server or reports failure without discarding history. || [0090](0090-project-constraints-require-explicit-scope.md) | Local steering stays local; durable project constraints require explicit scope and exact current-user text, while legacy unscoped records are reviewable. || [0092](0092-codedb-context-is-local-first.md) | Bare `codedb context` is `--local`; `--hybrid` / `--semantic` are opt-in remote rerank (and still refused under ADR 0084 policy). |+| [0093](0093-project-layout-breadth-and-directory-hints.md) | Project layout favors breadth under its caps; missing directories offer bounded sibling hints without changing confinement or ADR 0090 constraint policy. |## When to write onediff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonlindex 12aff391..09121b07 100644--- a/evals/harness_behavior.jsonl+++ b/evals/harness_behavior.jsonl@@ -72,5 +72,6 @@{"id": "model-loop-fenced-data", "prompt": "Return the requested literal data block.", "args": ["--no-lean"], "script": [{"text": "```text\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\n```"}], "assert": [{"final_text_contains": "```text\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\n```"}], "why": "#743: Legitimate fenced repetition remains intact"}{"id": "native-read-image-same-turn", "why": "Native image reads must deliver pixels on the next model request without waiting for a second user prompt.", "prompt": "Read image.png with read_file and confirm that the image arrived.", "script": [{"tool": "bash", "arguments": {"command": "python3 -c \"import base64; open('image.png','wb').write(base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1sAAAAASUVORK5CYII='))\""}}, {"tool": "read_file", "arguments": {"path": "image.png"}}, {"text": "Image received."}], "assert": [{"event": {"type": "tool_result", "name": "read_file", "is_error": false}}, {"request_contains": {"index": -1, "text": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1sAAAAASUVORK5CYII="}}, {"final_text_contains": "Image received."}], "controls_before_prompt": [{"type": "set_model", "provider": "lmstudio", "model": "mock-vision"}]}{"id": "meta-tool-completion-status", "why": "A metadata tool must finish its announced GUI row even when its result body uses a separate presentation path.", "prompt": "Create one pending todo, then finish your response.", "script": [{"tool": "todo_write", "arguments": {"todos": [{"content": "Review fixture", "status": "pending"}]}}, {"text": "The pending item is ready."}], "assert": [{"event": {"type": "tool_call", "name": "todo_write", "id": "call_1"}}, {"event": {"type": "tool_call_finished", "name": "todo_write", "id": "call_1", "is_error": false}}]}+{"id": "list-dir-near-miss-hint", "why": "ADR 0093: a misspelled list_dir path should name the closest sibling while retaining error status.", "prompt": "what is in the demo-server folder", "workspace_seed": {"demos-servers/README.md": "# runbook\n"}, "script": [{"tool": "codedb", "arguments": {"command": "list_dir demo-server"}}, {"text": "the folder is demos-servers"}], "assert": [{"event": {"type": "tool_result", "name": "codedb", "is_error": true}}, {"request_contains": {"index": 1, "text": "was not found. Closest match: demos-servers/."}}, {"final_text_contains": "demos-servers"}]}{"id": "subagent-activity-isolated-sink", "why": "Frontendless workers must publish their streamed progress, tool identity and final report to a separate bounded activity feed without emitting child prose as parent text.", "workspace_seed": {"example.txt": "fixture content\n", "check_activity.py": "import json, pathlib\nsnapshots = [json.loads(p.read_text()) for p in pathlib.Path('.graff/live').glob('activity-*/*.json')]\nassert len(snapshots) == 1, len(snapshots)\ns = snapshots[0]\nassert s['agent']['status'] == 'completed', s['agent']\nassert s['response'] == 'Child review complete.', s['response']\nassert any(e['type'] == 'text' and 'Child is inspecting.' in e['text'] for e in s['events']), s['events']\nassert any(e['type'] == 'tool_call' and e['name'] == 'read_file' and e['text'] == 'example.txt' and e['input_key'] == 'path' for e in s['events']), s['events']\nassert any(e['type'] == 'tool_result' and 'fixture content' in e['text'] for e in s['events']), s['events']\nassert not any('Parent has finished.' in e['text'] for e in s['events'])\nprint('child-activity-verified')\n"}, "prompt": "Use one subagent to inspect example.txt, then verify its activity feed with check_activity.py.", "script": [{"tool": "subagent", "arguments": {"description": "Inspect example", "prompt": "Read example.txt and report your findings."}}, {"text": "Child is inspecting.", "tool": "read_file", "arguments": {"path": "example.txt"}}, {"text": "Child review complete."}, {"tool": "bash", "arguments": {"command": "python3 check_activity.py"}}, {"text": "Parent has finished."}], "assert": [{"event": {"type": "tool_result", "name": "bash", "text": "child-activity-verified\n"}}, {"events_at_most": {"match": {"type": "text", "text": "Child is inspecting."}, "count": 0}}, {"final_text_contains": "Parent has finished."}]}{"id":"opaque-compaction-is-not-success-804","why":"An unsupported local fallback must report that opaque history needs server compaction, not emit successful zero-work compaction or discard the preserved context.","args":["--resume","compact-fixture"],"workspace_seed":{".graff/sessions/compact-fixture.session.json":"{\"provider\":\"lmstudio\",\"model\":\"mock\",\"messages\":[{\"type\":\"compaction\",\"encrypted_content\":\"opaque-fixture-804\"},{\"role\":\"user\",\"content\":\"retained-context-804\"}]}"},"controls_before_prompt":[{"type":"compact"}],"prompt":"Continue using the retained context.","script":[{"text":"Retained context is available."}],"assert":[{"event":{"type":"error","message":"compaction failed: ServerCompactionRequired"}},{"events_at_most":{"match":{"type":"compact","ok":true},"count":0}},{"request_contains":{"index":0,"text":"retained-context-804"}},{"request_contains":{"index":0,"text":"opaque-fixture-804"}},{"final_text_contains":"Retained context is available."}]}diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex 7c8d2f91..fdb86c1f 100644--- a/scripts/eval/tier1-manifest.json+++ b/scripts/eval/tier1-manifest.json@@ -15,7 +15,7 @@"src/repl.zig","TUI/root.zig"],- "test_count_baseline": 2072,+ "test_count_baseline": 2105,"test_count_slack": 25,"required_invariants": [{diff --git a/src/codedb_local.zig b/src/codedb_local.zigindex 0f476965..6014f62c 100644--- a/src/codedb_local.zig+++ b/src/codedb_local.zig@@ -133,7 +133,7 @@ pub fn restHasFlag(rest: []const u8, check: *const fn ([]const u8) bool) bool {}/// Explicit `--hybrid` / `--semantic` opt into remote advisory rerank.-/// Bare `context <task>` is on-device (ADR 0086).+/// Bare `context <task>` is on-device (ADR 0092).pub fn restAsksRemoteRerank(rest: []const u8) bool {return restHasFlag(rest, tokenIsRemoteFlag);}diff --git a/src/list_dir.zig b/src/list_dir.zigindex 6d513c9d..039be87e 100644--- a/src/list_dir.zig+++ b/src/list_dir.zig@@ -12,6 +12,8 @@//! unexpanded dirs collapse to `[N files in subtree: K *.ext, …]`.//! `.git` is never listed. Other dotfiles stay visible (`.github` is load-//! bearing here; grok-build hides every dot).+//! A path that does not exist answers with its closest siblings and the+//! parent's entries (list_dir_nearmiss.zig) instead of a bare not-found.const std = @import("std");const Io = std.Io;@@ -20,6 +22,7 @@ const Allocator = std.mem.Allocator;const tools = @import("tools.zig");const approvals = @import("approvals.zig");const gitignore = @import("gitignore.zig");+const nearmiss = @import("list_dir_nearmiss.zig");pub const max_output_chars: usize = 10_000;pub const max_walk_items: usize = 20_000;@@ -346,7 +349,7 @@ pub fn run(io: Io, gpa: Allocator, rest: []const u8, agent_cwd: ?[]const u8) !toconst st = Io.Dir.cwd().statFile(io, resolved, .{}) catch |err| switch (err) {error.FileNotFound => return .{- .text = try std.fmt.allocPrint(gpa, "Error: {s} was not found.", .{path}),+ .text = try std.fmt.allocPrint(gpa, "Error: {s} was not found.{s}", .{ path, nearmiss.suggest(io, arena, resolved, path, agent_cwd) orelse "" }),.is_error = true,},error.AccessDenied => return .{@@ -475,6 +478,20 @@ test "run refuses a file and an escaped path" {try std.testing.expect(std.mem.indexOf(u8, listing.text, "only.txt") != null);}+test "not found names the closest sibling instead of a dead end" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ tmp.dir.createDirPath(io, "demos-servers") catch unreachable;+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const abs = try tmpAbs(io, &tmp, &buf);++ const out = try run(io, std.testing.allocator, "demo-server", abs);+ defer std.testing.allocator.free(out.text);+ try std.testing.expect(out.is_error);+ try std.testing.expectEqualStrings("Error: demo-server was not found. Closest match: demos-servers/. Entries in . (1): demos-servers/.", out.text);+}+test "empty directory is a header only" {const io = std.testing.io;var tmp = std.testing.tmpDir(.{ .iterate = true });diff --git a/src/list_dir_nearmiss.zig b/src/list_dir_nearmiss.zignew file mode 100644index 00000000..6c2cda75--- /dev/null+++ b/src/list_dir_nearmiss.zig@@ -0,0 +1,163 @@+//! Near-miss help for `codedb list_dir <path>` when the path does not exist.+//!+//! A bare not-found error gives no way to recover from a mistyped path.+//! Naming the closest visible siblings and listing the parent helps the next+//! call use the right path. Distance is edit distance over a normalized form+//! (case and the separators '-', '_', '.', ' ' ignored); containment either+//! way is close.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const gitignore = @import("gitignore.zig");++const max_scanned = 4000;+const max_close = 3;+const max_listed_bytes = 1200;+const max_compare = 64;++const Entry = struct { shown: []const u8, is_dir: bool, dist: usize };++fn normalize(s: []const u8, buf: *[max_compare]u8) []const u8 {+ var n: usize = 0;+ for (s) |c| {+ if (n == max_compare) break;+ if (c == '-' or c == '_' or c == '.' or c == ' ') continue;+ buf[n] = std.ascii.toLower(c);+ n += 1;+ }+ return buf[0..n];+}++fn levenshtein(a: []const u8, b: []const u8) usize {+ var prev: [max_compare + 1]usize = undefined;+ var cur: [max_compare + 1]usize = undefined;+ for (0..b.len + 1) |j| prev[j] = j;+ for (a, 0..) |ca, i| {+ cur[0] = i + 1;+ for (b, 0..) |cb, j| {+ const sub = prev[j] + @as(usize, if (ca == cb) 0 else 1);+ cur[j + 1] = @min(sub, @min(prev[j + 1] + 1, cur[j] + 1));+ }+ @memcpy(prev[0 .. b.len + 1], cur[0 .. b.len + 1]);+ }+ return prev[b.len];+}++/// 0 = same name up to case and separators; 1 = one contains the other.+pub fn distance(want: []const u8, have: []const u8) usize {+ var wb: [max_compare]u8 = undefined;+ var hb: [max_compare]u8 = undefined;+ const w = normalize(want, &wb);+ const h = normalize(have, &hb);+ if (w.len == 0 or h.len == 0) return max_compare;+ if (std.mem.eql(u8, w, h)) return 0;+ if (w.len >= 3 and (std.mem.indexOf(u8, h, w) != null or std.mem.indexOf(u8, w, h) != null)) return 1;+ return levenshtein(w, h);+}++fn threshold(want: []const u8) usize {+ return @max(2, want.len / 3);+}++fn byDist(_: void, a: Entry, b: Entry) bool {+ if (a.dist != b.dist) return a.dist < b.dist;+ return std.mem.lessThan(u8, a.shown, b.shown);+}++fn byName(_: void, a: Entry, b: Entry) bool {+ if (a.is_dir != b.is_dir) return a.is_dir;+ return std.mem.lessThan(u8, a.shown, b.shown);+}++/// Text to append to the not-found error, or null when the parent cannot be+/// read. `resolved` is the path that failed; `display` is what the model+/// typed (its parent is echoed back so the next command can be copied).+pub fn suggest(io: Io, arena: Allocator, resolved: []const u8, display: []const u8, agent_cwd: ?[]const u8) ?[]const u8 {+ const target = std.mem.trimEnd(u8, resolved, "/");+ const leaf = std.fs.path.basename(target);+ if (leaf.len == 0) return null;+ const parent_abs = std.fs.path.dirname(target) orelse (agent_cwd orelse ".");+ const parent_display = std.fs.path.dirname(std.mem.trimEnd(u8, display, "/")) orelse ".";++ var dir = Io.Dir.cwd().openDir(io, parent_abs, .{ .iterate = true }) catch return null;+ defer dir.close(io);+ var parent_buf: [std.fs.max_path_bytes]u8 = undefined;+ const parent_len = dir.realPath(io, &parent_buf) catch return null;+ const root_abs = parent_buf[0..parent_len];+ const rules = gitignore.loadClimb(io, arena, root_abs) catch return null;+ var entries: std.ArrayList(Entry) = .empty;+ var it = dir.iterate();+ while (it.next(io) catch null) |entry| {+ if (entry.kind == .sym_link or std.mem.eql(u8, entry.name, ".git")) continue;+ if (entries.items.len == max_scanned) break;+ const is_dir = entry.kind == .directory;+ const child_abs = std.fmt.allocPrint(arena, "{s}/{s}", .{ root_abs, entry.name }) catch return null;+ if (gitignore.ignored(arena, rules, root_abs, child_abs, is_dir) catch return null) continue;+ const shown = std.fmt.allocPrint(arena, "{s}{s}", .{ entry.name, if (is_dir) "/" else "" }) catch return null;+ entries.append(arena, .{ .shown = shown, .is_dir = is_dir, .dist = distance(leaf, entry.name) }) catch return null;+ }+ if (entries.items.len == 0) return null;++ var aw: Io.Writer.Allocating = .init(arena);+ const w = &aw.writer;+ std.mem.sort(Entry, entries.items, {}, byDist);+ var close: usize = 0;+ for (entries.items) |e| {+ if (e.dist > threshold(leaf) or close == max_close) break;+ w.print("{s}{s}", .{ if (close == 0) " Closest match: " else ", ", e.shown }) catch return null;+ close += 1;+ }+ if (close > 0) w.writeAll(".") catch return null;++ std.mem.sort(Entry, entries.items, {}, byName);+ w.print(" Entries in {s} ({d}): ", .{ parent_display, entries.items.len }) catch return null;+ var bytes: usize = 0;+ var listed: usize = 0;+ for (entries.items) |e| {+ if (bytes + e.shown.len + 2 > max_listed_bytes) break;+ w.print("{s}{s}", .{ if (listed == 0) "" else ", ", e.shown }) catch return null;+ bytes += e.shown.len + 2;+ listed += 1;+ }+ if (listed < entries.items.len) w.print(", … {d} more", .{entries.items.len - listed}) catch return null;+ w.writeAll(".") catch return null;+ return aw.writer.buffered();+}++test "distance: separators and case are free, containment is close, unrelated is far" {+ try std.testing.expectEqual(@as(usize, 0), distance("Demos_Servers", "demos-servers"));+ try std.testing.expect(distance("demo-server", "demos-servers") <= 2);+ try std.testing.expectEqual(@as(usize, 1), distance("server", "demos-servers"));+ try std.testing.expect(distance("demo-server", "frontend") > threshold("demo-server"));+}++test "not found: names the closest sibling and lists the parent" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ tmp.dir.createDirPath(io, "demos-servers") catch unreachable;+ tmp.dir.createDirPath(io, "frontend") catch unreachable;+ tmp.dir.createDirPath(io, ".git") catch unreachable;+ tmp.dir.writeFile(io, .{ .sub_path = ".gitignore", .data = "demo-server.log\ndemo-servers/\n" }) catch unreachable;+ tmp.dir.writeFile(io, .{ .sub_path = "demo-server.log", .data = "x" }) catch unreachable;+ tmp.dir.createDirPath(io, "demo-servers") catch unreachable;+ tmp.dir.writeFile(io, .{ .sub_path = "README.md", .data = "x" }) catch unreachable;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const arena = arena_state.allocator();+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const n = try tmp.dir.realPath(io, &buf);+ const missing = try std.fmt.allocPrint(arena, "{s}/demo-server", .{buf[0..n]});++ const hint = suggest(io, arena, missing, "demo-server", null) orelse return error.TestUnexpectedResult;+ try std.testing.expectEqualStrings(" Closest match: demos-servers/. Entries in . (4): demos-servers/, frontend/, .gitignore, README.md.", hint);++ try std.testing.expect(std.mem.indexOf(u8, hint, "demo-server.log") == null);+ try std.testing.expect(std.mem.indexOf(u8, hint, "demo-servers/") == null);++ const unrelated = try std.fmt.allocPrint(arena, "{s}/zzz", .{buf[0..n]});+ const none = suggest(io, arena, unrelated, "sub/zzz", null) orelse return error.TestUnexpectedResult;+ try std.testing.expect(std.mem.indexOf(u8, none, "Closest match") == null);+ try std.testing.expect(std.mem.startsWith(u8, none, " Entries in sub (4): "));+}diff --git a/src/main.zig b/src/main.zigindex 85b18902..c209c1d1 100644--- a/src/main.zig+++ b/src/main.zig@@ -564,8 +564,6 @@ const agentJobsReap = subagent.agentJobsReap; // #276 P0-3: background subagentsconst workflow = @import("workflow_test.zig"); // the engine's tests live here (workflow.zig hit the 600-line cap)const exec = @import("exec.zig");test { // ── Unit tests (`zig build test`): pull in tests from imported modules (mcp.zig)- _ = @import("mcp.zig");- _ = @import("mcp_rpc.zig");_ = @import("main_test.zig");_ = @import("http_client.zig");_ = @import("http_client_tests.zig");@@ -575,6 +573,8 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = @import("publication_policy_tests.zig");_ = @import("jobs_completion_tests.zig");_ = @import("test_hooks.zig"); // unreached modules; their tests were silently skipped+ _ = @import("list_dir_nearmiss.zig");+ _ = @import("repo_map.zig");_ = @import("agent_overflow_tests.zig"); // #414: and, through it, agent_overflow.zig's table tests_ = @import("agent_server_compact.zig"); // server-side autocompact (codex Responses)_ = @import("compact_status.zig");diff --git a/src/repo_map.zig b/src/repo_map.zigindex 00f3461d..e08486bf 100644--- a/src/repo_map.zig+++ b/src/repo_map.zig@@ -5,6 +5,13 @@//! Deterministic (sorted) so prompt rebuilds produce byte-identical text —//! the segment lives inside the cache-stable prefix. Built once per process://! mid-session file changes are NOT reflected, which the header says.+//!+//! Selection is breadth-first and round-robin: top-level entries are considered+//! before any child, then each directory's first child, second child, and so+//! on, under the entry and byte caps. Emission stays depth-first (a path list+//! in tree order). The trailer names incompletely expanded top-level dirs and+//! counts omitted top-level entries. An unlisted name may still exist: caps,+//! skipped names, unreadable directories, and later changes limit this map.const std = @import("std");const Io = std.Io;@@ -13,16 +20,31 @@ const Allocator = std.mem.Allocator;const max_depth = 3;const max_entries = 300;const max_bytes = 6 * 1024;+/// How many not-fully-expanded top-level directories the trailer names.+const max_named = 12;/// Directories that are never informative to the model at this granularity.const skip_dirs = [_][]const u8{ ".git", "node_modules", "zig-cache", "zig-out", ".zig-cache", "target", "dist", "build", "__pycache__", ".venv", "venv", ".hg", ".svn" };-const Ent = struct { name: []const u8, dir: bool };+const Node = struct {+ /// Relative path; directories carry a trailing '/'.+ rel: []const u8,+ is_dir: bool,+ depth: usize,+ /// The depth-1 ancestor (self at depth 1) — where omissions are charged.+ top: ?*Node,+ kids: std.ArrayList(*Node) = .empty,+ selected: bool = false,+ /// Enumerated entries beneath this top-level directory the caps left out.+ omitted_below: usize = 0,+};-fn entLt(_: void, a: Ent, b: Ent) bool {- if (a.dir != b.dir) return a.dir;- return std.mem.lessThan(u8, a.name, b.name);-}+const Budget = struct {+ entries: usize = 0,+ bytes: usize = 0,+ omitted: usize = 0,+ root_omitted: usize = 0,+};var cached: ?[]const u8 = null; // built once per process (see module doc)@@ -32,53 +54,215 @@ fn skipped(name: []const u8) bool {return false;}-fn walk(io: Io, arena: Allocator, out: *std.ArrayList([]const u8), dir_path: []const u8, depth: usize, omitted: *usize) void {- if (out.items.len >= max_entries) return;+fn nodeLt(_: void, a: *Node, b: *Node) bool {+ if (a.is_dir != b.is_dir) return a.is_dir;+ return std.mem.lessThan(u8, a.rel, b.rel);+}++/// Read `parent`'s children, sorted directories first then by name.+fn readChildren(io: Io, arena: Allocator, root: []const u8, parent: *Node) void {+ const dir_path: []const u8 = if (parent.depth == 0)+ root+ else if (std.mem.eql(u8, root, "."))+ parent.rel[0 .. parent.rel.len - 1]+ else+ std.fmt.allocPrint(arena, "{s}/{s}", .{ root, parent.rel[0 .. parent.rel.len - 1] }) catch return;var dir = Io.Dir.cwd().openDir(io, dir_path, .{ .iterate = true }) catch return;defer dir.close(io);- var names: std.ArrayList(Ent) = .empty;var it = dir.iterate();while (it.next(io) catch null) |entry| {if (skipped(entry.name)) continue;- const recursed = entry.kind == .directory and depth < max_depth and out.items.len < max_entries;- names.append(arena, .{ .name = std.fmt.allocPrint(arena, "{s}{s}", .{ entry.name, if (entry.kind == .directory) "/" else "" }) catch continue, .dir = recursed }) catch continue;+ const is_dir = entry.kind == .directory;+ const rel = std.fmt.allocPrint(arena, "{s}{s}{s}", .{ parent.rel, entry.name, if (is_dir) "/" else "" }) catch continue;+ const n = arena.create(Node) catch continue;+ n.* = .{ .rel = rel, .is_dir = is_dir, .depth = parent.depth + 1, .top = null };+ n.top = if (parent.depth == 0) n else parent.top;+ parent.kids.append(arena, n) catch continue;+ }+ std.mem.sort(*Node, parent.kids.items, {}, nodeLt);+}++fn take(b: *Budget, n: *Node) void {+ const cost = n.rel.len + 1;+ if (b.entries < max_entries and b.bytes + cost <= max_bytes) {+ n.selected = true;+ b.entries += 1;+ b.bytes += cost;+ return;+ }+ b.omitted += 1;+ if (n.depth == 1) {+ b.root_omitted += 1;+ } else if (n.top) |t| {+ t.omitted_below += 1;+ }+}++fn emit(w: *Io.Writer, n: *Node) !void {+ for (n.kids.items) |k| {+ if (!k.selected) continue;+ try w.print("{s}\n", .{k.rel});+ if (k.is_dir) try emit(w, k);}- // Directories first, then files, alphabetical within each — stable output.- std.mem.sort(Ent, names.items, {}, entLt);- for (names.items) |item| {- if (out.items.len >= max_entries) {- omitted.* += 1;+}++fn trailer(w: *Io.Writer, root_node: *Node, b: *const Budget) !void {+ try w.print("... ({d} more entries not shown", .{b.omitted});+ if (b.root_omitted > 0) try w.print("; {d} of them top-level", .{b.root_omitted});+ var named: usize = 0;+ var extra: usize = 0;+ for (root_node.kids.items) |k| {+ if (!k.is_dir or k.omitted_below == 0) continue;+ if (named == max_named) {+ extra += 1;continue;}- const rel = if (std.mem.eql(u8, dir_path, ".")) item.name else std.fmt.allocPrint(arena, "{s}/{s}", .{ dir_path, item.name }) catch continue;- out.append(arena, rel) catch return;- if (item.dir) walk(io, arena, out, rel[0 .. rel.len - 1], depth + 1, omitted);+ try w.print("{s}{s}", .{ if (named == 0) "; not fully expanded: " else ", ", k.rel });+ named += 1;}+ if (extra > 0) try w.print(" and {d} more", .{extra});+ try w.writeAll(" — list a directory on demand)\n");+}++/// Build the segment for `root` ("." in production; tests pass a temp dir).+/// Null when the tree is empty or unreadable.+pub fn build(io: Io, arena: Allocator, root: []const u8) ?[]const u8 {+ const root_node = arena.create(Node) catch return null;+ root_node.* = .{ .rel = "", .is_dir = true, .depth = 0, .top = null };+ var budget: Budget = .{};+ var level: std.ArrayList(*Node) = .empty;+ level.append(arena, root_node) catch return null;+ var depth: usize = 1;+ while (depth <= max_depth and level.items.len > 0) : (depth += 1) {+ for (level.items) |p| readChildren(io, arena, root, p);+ // Round-robin across this level's directories: each gets its first+ // child before any gets its second, so a fat sibling cannot starve+ // the others.+ var i: usize = 0;+ var any = true;+ while (any) : (i += 1) {+ any = false;+ for (level.items) |p| {+ if (i < p.kids.items.len) {+ any = true;+ take(&budget, p.kids.items[i]);+ }+ }+ }+ var next: std.ArrayList(*Node) = .empty;+ for (level.items) |p| {+ for (p.kids.items) |k| {+ if (k.selected and k.is_dir) next.append(arena, k) catch {};+ }+ }+ level = next;+ }+ if (root_node.kids.items.len == 0) return null;++ var aw: Io.Writer.Allocating = .init(arena);+ aw.writer.print("\n\n# Project layout (working tree at session start, depth {d}; may omit later changes)\n", .{max_depth}) catch return null;+ emit(&aw.writer, root_node) catch return null;+ if (budget.omitted > 0) trailer(&aw.writer, root_node, &budget) catch return null;+ return aw.writer.buffered();}/// The prompt segment, or null when the tree is empty/unreadable. Cached for/// the process so every prompt rebuild reuses the same bytes.pub fn segment(io: Io, arena: Allocator) ?[]const u8 {if (cached) |c| return if (c.len == 0) null else c;- var entries: std.ArrayList([]const u8) = .empty;- var omitted: usize = 0;- walk(io, arena, &entries, ".", 1, &omitted);- if (entries.items.len == 0) {- cached = "";- return null;- }- var aw: Io.Writer.Allocating = .init(arena);- aw.writer.print("\n\n# Project layout (working tree at session start, depth {d}; may omit later changes)\n", .{max_depth}) catch return null;- var bytes: usize = 0;- for (entries.items) |e| {- if (bytes + e.len > max_bytes) {- omitted += 1;- continue;+ const built = build(io, arena, ".") orelse "";+ cached = built;+ return if (built.len == 0) null else built;+}++fn tmpAbs(io: Io, tmp: *std.testing.TmpDir, buf: *[std.fs.max_path_bytes]u8) ![]const u8 {+ const n = try tmp.dir.realPath(io, buf);+ return buf[0..n];+}++test "small tree emits in tree order, hides dot and build dirs, no trailer" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ tmp.dir.createDirPath(io, "b") catch unreachable;+ tmp.dir.writeFile(io, .{ .sub_path = "b/y.txt", .data = "x" }) catch unreachable;+ tmp.dir.createDirPath(io, "a/deep") catch unreachable;+ tmp.dir.writeFile(io, .{ .sub_path = "a/x.txt", .data = "x" }) catch unreachable;+ tmp.dir.writeFile(io, .{ .sub_path = "c.txt", .data = "x" }) catch unreachable;+ tmp.dir.createDirPath(io, ".git/objects") catch unreachable;+ tmp.dir.createDirPath(io, "node_modules/pkg") catch unreachable;++ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const abs = try tmpAbs(io, &tmp, &buf);+ const out = build(io, arena_state.allocator(), abs) orelse return error.TestUnexpectedResult;+ try std.testing.expectEqualStrings(+ "\n\n# Project layout (working tree at session start, depth 3; may omit later changes)\n" +++ "a/\na/deep/\na/x.txt\nb/\nb/y.txt\nc.txt\n",+ out,+ );+}++test "breadth-first: a late top-level directory survives fat early siblings" {+ // The failure this guards: fat directories ahead of it in the alphabet+ // spent the whole budget, so the model never saw the folder the user named.+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ var d: usize = 0;+ while (d < 10) : (d += 1) {+ var dn: [8]u8 = undefined;+ tmp.dir.createDirPath(io, std.fmt.bufPrint(&dn, "fat{d}", .{d}) catch unreachable) catch unreachable;+ var i: usize = 0;+ while (i < 60) : (i += 1) {+ var name: [64]u8 = undefined;+ const n = std.fmt.bufPrint(&name, "fat{d}/file_with_a_longer_name_{d:0>3}.zig", .{ d, i }) catch unreachable;+ tmp.dir.writeFile(io, .{ .sub_path = n, .data = "x" }) catch unreachable;}- bytes += e.len + 1;- aw.writer.print("{s}\n", .{e}) catch return null;}- if (omitted > 0) aw.writer.print("... ({d} more entries not shown — list directories on demand)\n", .{omitted}) catch return null;- cached = aw.writer.buffered();- return cached;+ tmp.dir.createDirPath(io, "rachs-servers/egress-relay") catch unreachable;+ tmp.dir.writeFile(io, .{ .sub_path = "rachs-servers/README.md", .data = "x" }) catch unreachable;+ tmp.dir.writeFile(io, .{ .sub_path = "zz-top.txt", .data = "x" }) catch unreachable;++ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const abs = try tmpAbs(io, &tmp, &buf);+ const out = build(io, arena_state.allocator(), abs) orelse return error.TestUnexpectedResult;+ // Every top-level entry is present …+ try std.testing.expect(std.mem.indexOf(u8, out, "\nrachs-servers/\n") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "\nzz-top.txt\n") != null);+ // … each directory got its first children (round-robin) …+ try std.testing.expect(std.mem.indexOf(u8, out, "\nrachs-servers/egress-relay/\n") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "\nrachs-servers/README.md\n") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "\nfat9/file_with_a_longer_name_000.zig\n") != null);+ // … the caps still hold, and the trailer names what was cut, not what was not.+ try std.testing.expect(out.len <= max_bytes + 512);+ const trailer_at = std.mem.indexOf(u8, out, "\n... (") orelse return error.TestUnexpectedResult;+ const tail = out[trailer_at..];+ try std.testing.expect(std.mem.indexOf(u8, tail, "more entries not shown; not fully expanded: fat0/, fat1/") != null);+ try std.testing.expect(std.mem.indexOf(u8, tail, "fat9/ — list a directory on demand)\n") != null);+ try std.testing.expect(std.mem.indexOf(u8, tail, "rachs-servers/") == null);+ try std.testing.expect(std.mem.indexOf(u8, tail, "top-level") == null);+}++test "top-level overflow is reported as such" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ var i: usize = 0;+ while (i < 310) : (i += 1) {+ var name: [16]u8 = undefined;+ const n = std.fmt.bufPrint(&name, "f{d:0>3}.txt", .{i}) catch unreachable;+ tmp.dir.writeFile(io, .{ .sub_path = n, .data = "x" }) catch unreachable;+ }+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const abs = try tmpAbs(io, &tmp, &buf);+ const out = build(io, arena_state.allocator(), abs) orelse return error.TestUnexpectedResult;+ try std.testing.expect(std.mem.indexOf(u8, out, "\nf299.txt\n") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "\nf300.txt\n") == null);+ try std.testing.expect(std.mem.endsWith(u8, out, "... (10 more entries not shown; 10 of them top-level — list a directory on demand)\n"));}diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 1b0015df..2744f23c 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -371,4 +371,6 @@ test {_ = @import("mcp_elicitation.zig"); // #768: Computer Use form elicitation_ = @import("skill_runtime_adapter.zig"); // #768: read-only get_app_state adapter_ = @import("edit_worktree_tests.zig"); // #747: edit lands on the selected worktree+ _ = @import("mcp.zig");+ _ = @import("mcp_rpc.zig");}