graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(codedb): grok-build list_dir inside codedb (#579)
Rach332c00188754
diff --git a/.gitignore b/.gitignoreindex 05962e72..f2aa082c 100644--- a/.gitignore+++ b/.gitignore@@ -35,6 +35,8 @@ dist/# surfer lives in its own repo (~/surfer, github.com/justrach/surfer) — never track it heresurfer/+# codedb lives in its own repo (github.com/justrach/codedb) — local checkout only+codedb/graff-evals/results/graff-evals/.sandboxes/diff --git a/docs/adr/0013-list-dir-lives-in-codedb.md b/docs/adr/0013-list-dir-lives-in-codedb.mdnew file mode 100644index 00000000..887770e4--- /dev/null+++ b/docs/adr/0013-list-dir-lives-in-codedb.md@@ -0,0 +1,32 @@+# 0013. Directory listing is a codedb subcommand, not a catalog tool++Status: accepted 2026-08-20++## Context++grok-build's `list_dir` is a first-class tool: BFS, `.gitignore`, any folder,+10k-character cap, collapsed subtree summaries. graff already has `codedb`+for structural nav and tells the model to prefer it over bash `ls`. A new+always-on catalog entry would tax every turn — that is how the first #574+A/B lost.++`codedb ls` / `tree` are the **index**. They do not list an extra `--add-dir`+root or an unindexed tree.++## Decision++`codedb list_dir <path>` is implemented in-process in graff (PathConfine,+including extra roots) **and** as a real codedb CLI/MCP command+(`github.com/justrach/codedb`, issue #696 / PR #697). Same algorithm: BFS, gitignore,+10k-character cap. Graff keeps the in-process path so `--add-dir` and a+missing binary still work. `codedb ls` / `tree` stay index queries.++Do not add a sibling graff `list_dir` catalog tool unless an A/B shows the+extra schema bytes beat this subcommand.++## Consequences++- Folder listing no longer needs `bash ls` / `find` for confined trees.+- `codedb ls` / `tree` stay index queries.+- The model has to read the codedb description (or the prompt sentence) to+ find `list_dir`; that is the cost of not growing the catalog.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex ed63b993..d4c8e11b 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -23,6 +23,7 @@ record only when you need the evidence or the edge cases.| [0010](0010-background-jobs-wait-for-exit.md) | `bash_output`/`agent_output` `wait_ms>0` blocks until exit (10h cap); do not poll every 30s. || [0011](0011-prompt-cache-max-is-visible.md) | Prompt-cache max is `/cache` posture, not a new default; `/btw` rides the parent prefix. || [0012](0012-overflow-handles-named-limits-extra-roots.md) | Fat tool results become `tr_N` handles; named `--context-limit` caps prefix bytes; `--add-dir` extra roots are PathConfine allow-lists, not cwd/skill/session sources. |+| [0013](0013-list-dir-lives-in-codedb.md) | Directory listing is `codedb list_dir` (in-process BFS, gitignore, 10k cap), not a new always-on catalog tool. |## When to write onediff --git a/scripts/list-dir-showcase.py b/scripts/list-dir-showcase.pynew file mode 100755index 00000000..baae076a--- /dev/null+++ b/scripts/list-dir-showcase.py@@ -0,0 +1,246 @@+#!/usr/bin/env python3+"""Offline showcase: graff now + new codedb list_dir vs the old index path.++No provider, no network. Builds a fixture, times the walks, and prints a+scorecard. Fail the invariants with --self-test.++ python3 scripts/list-dir-showcase.py+ python3 scripts/list-dir-showcase.py --self-test+ python3 scripts/list-dir-showcase.py --codedb /workspace/codedb/zig-out/bin/codedb+"""++from __future__ import annotations++import argparse+import os+import re+import shutil+import subprocess+import sys+import tempfile+import time+from pathlib import Path++ROOT = Path(__file__).resolve().parents[1]+FAT = 400+MAX_LIST = 10_000+++def timed(argv: list[str], cwd: Path | None, env: dict[str, str]) -> tuple[float, str, int]:+ t0 = time.perf_counter()+ proc = subprocess.run(+ argv,+ cwd=cwd,+ env=env,+ text=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ timeout=120,+ )+ elapsed = time.perf_counter() - t0+ out = (proc.stdout or "") + (("\n" + proc.stderr) if proc.stderr else "")+ return elapsed, out, proc.returncode+++def materialize(root: Path) -> None:+ (root / ".git" / "objects").mkdir(parents=True)+ (root / ".git" / "HEAD").write_text("ref: refs/heads/main\n", encoding="utf-8")+ (root / ".github").mkdir()+ (root / ".github" / "ci.yml").write_text("on: push\n", encoding="utf-8")+ (root / ".gitignore").write_text("skip.log\nbuild/\n", encoding="utf-8")+ (root / "keep.zig").write_text("pub fn main() void {}\n", encoding="utf-8")+ (root / "skip.log").write_text("noise\n", encoding="utf-8")+ (root / "src").mkdir()+ (root / "src" / "main.zig").write_text("pub fn main() void {}\n", encoding="utf-8")+ (root / "build").mkdir()+ (root / "build" / "a.o").write_text("x", encoding="utf-8")+ (root / "aaa").mkdir()+ for i in range(FAT):+ (root / "aaa" / f"file_with_a_longer_name_{i:03d}.zig").write_text("x", encoding="utf-8")+ (root / "zzz").mkdir()+ (root / "zzz" / "tail.md").write_text("end\n", encoding="utf-8")+++def find_codedb(explicit: str | None) -> Path | None:+ if explicit:+ p = Path(explicit)+ return p if p.is_file() else None+ for cand in (+ ROOT / "codedb" / "zig-out" / "bin" / "codedb",+ Path("/workspace/codedb/zig-out/bin/codedb"),+ ):+ if cand.is_file():+ return cand+ return None+++def ensure_codedb(explicit: str | None) -> Path:+ got = find_codedb(explicit)+ if got:+ return got+ src = Path("/workspace/codedb")+ zig = Path("/tmp/zig-install/zig/zig")+ if not src.is_dir() or not zig.is_file():+ raise SystemExit("codedb binary not found (pass --codedb)")+ subprocess.run([str(zig), "build"], cwd=src, check=True)+ got = find_codedb(explicit)+ if not got:+ raise SystemExit("codedb built but zig-out/bin/codedb missing")+ return got+++def catalog_bits() -> dict[str, object]:+ schema = (ROOT / "src" / "schema.zig").read_text(encoding="utf-8")+ prompt = (ROOT / "src" / "prompt_text.zig").read_text(encoding="utf-8")+ names = re.findall(r'\.name = "([a-z_]+)"', schema)+ # first block is the always-on root specs; stop at meta+ root_names: list[str] = []+ for name in names:+ if name == "todo_write":+ break+ root_names.append(name)+ codedb_desc = ""+ m = re.search(r'\.name = "codedb",\s*\n\s*\.desc = "([^"]+)"', schema)+ if m:+ codedb_desc = m.group(1)+ return {+ "root_tools": root_names,+ "codedb_is_one_tool": root_names.count("codedb") == 1 and "list_dir" not in root_names,+ "codedb_desc_bytes": len(codedb_desc),+ "prompt_has_list_dir": "codedb list_dir" in prompt,+ "list_dir_in_desc": "list_dir" in codedb_desc,+ }+++def checks(listing: str) -> dict[str, bool]:+ return {+ "keep.zig": "keep.zig" in listing,+ ".github": ".github" in listing,+ "skip.log hidden": "skip.log" not in listing,+ "build/ hidden": not re.search(r"^- build/$", listing, re.M)+ and "build/a.o" not in listing,+ ".git omitted": ".git/" not in listing and "\n - .git\n" not in listing,+ "fat sibling collapsed": "files in subtree" in listing and "aaa/" in listing,+ "later sibling visible": "zzz/" in listing and "tail.md" in listing,+ "under 10k": len(listing) < MAX_LIST + 256,+ }+++def section(title: str) -> None:+ print()+ print(title)+ print("=" * len(title))+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--codedb", help="path to codedb binary")+ parser.add_argument("--self-test", action="store_true")+ parser.add_argument("--keep", action="store_true")+ args = parser.parse_args()++ cat = catalog_bits()+ codedb = ensure_codedb(args.codedb)+ env = os.environ.copy()+ env["CODEDB_NO_CLI_DAEMON"] = "1"+ env["CODEDB_QUIET"] = "1"+ env["CODEDB_NO_TELEMETRY"] = "1"++ tmp = Path(tempfile.mkdtemp(prefix="graff-list-dir-showcase-"))+ try:+ materialize(tmp)+ find_out = subprocess.check_output(["find", str(tmp), "-print"], text=True)+ ls_out = subprocess.check_output(["ls", "-la", str(tmp)], text=True)+ t_list, list_out, list_rc = timed([str(codedb), str(tmp), "list_dir", "."], None, env)+ t_ls, codedb_ls_out, ls_rc = timed([str(codedb), str(tmp), "ls"], None, env)+ t_list2, list_out2, _ = timed([str(codedb), str(tmp), "list_dir", "."], None, env)+ finally:+ if not args.keep:+ shutil.rmtree(tmp, ignore_errors=True)++ got = checks(list_out)+ failed = [k for k, ok in got.items() if not ok]++ if args.self_test:+ if list_rc != 0:+ raise SystemExit(f"self-test: list_dir exited {list_rc}\n{list_out}")+ if failed:+ raise SystemExit("self-test failed: " + ", ".join(failed))+ if not cat["codedb_is_one_tool"] or not cat["prompt_has_list_dir"]:+ raise SystemExit("self-test: catalog/prompt drifted")+ if len(list_out) * 10 > len(find_out):+ raise SystemExit(+ f"self-test: list_dir {len(list_out)} chars was not much smaller than find {len(find_out)}"+ )+ print("self-test ok: live walk, gitignore, 10k cap, one codedb tool, no index")+ return 0++ section("graff now")+ print("one codedb tool (not a sibling list_dir catalog entry) — ADR 0013")+ print(f" root tools: {', '.join(cat['root_tools'])}")+ print(f" codedb description: {cat['codedb_desc_bytes']} bytes")+ print(f" prompt steers list_dir instead of bash ls: {cat['prompt_has_list_dir']}")+ print(" codedb stays on the every-turn surface (native_fold does not hide it)")+ print()+ print("prompt-cache max (kernels, offline):")+ show = subprocess.run(+ [sys.executable, str(ROOT / "spec" / "conformance.py"), "--showcase", "prompt"],+ cwd=ROOT,+ text=True,+ stdout=subprocess.PIPE,+ stderr=subprocess.PIPE,+ check=False,+ )+ if show.returncode != 0:+ print(" (spec showcase unavailable)")+ else:+ for line in show.stdout.splitlines()[:24]:+ print(" " + line)++ section("new codedb list_dir vs the old index path")+ print(f"fixture: {FAT} fat-sibling files + .gitignore + .git + .github")+ print(f"codedb: {codedb}")+ print()+ print(f" find -print {len(find_out):5d} chars (no gitignore, no cap)")+ print(f" ls -la {len(ls_out):5d} chars (dotfiles, no collapse)")+ print(+ f" codedb list_dir {len(list_out):5d} chars {t_list*1000:6.1f} ms exit {list_rc} (no index)"+ )+ print(+ f" codedb list_dir ×2 {len(list_out2):5d} chars {t_list2*1000:6.1f} ms (repeat, still no snapshot)"+ )+ print(+ f" codedb ls {len(codedb_ls_out):5d} chars {t_ls*1000:6.1f} ms exit {ls_rc} (index / snapshot)"+ )+ if len(list_out) > 0:+ print(f" list_dir is {len(find_out) / len(list_out):0.0f}× smaller than find on the same tree")+ if t_list > 0:+ print(f" list_dir is {t_ls / t_list:0.1f}× faster than codedb ls (ls still pays the scan)")+ print()+ print("invariants (live walk):")+ for name, ok in got.items():+ print(f" [{'PASS' if ok else 'FAIL'}] {name}")++ section("old codedb ls (index children of one directory)")+ print(codedb_ls_out.rstrip()[:800] or "(empty)")++ section("new codedb list_dir (live walk the model would see)")+ print(list_out.rstrip()[:2000])+ if len(list_out) > 2000:+ print(f" … ({len(list_out) - 2000} more chars, still under the 10k cap)")++ section("what got better")+ print(" old codedb ls/tree: index children. Cold tree pays a scan. Extra --add-dir roots miss.")+ print(" new codedb list_dir: BFS + gitignore + 10k cap. Early-exit, no snapshot, any folder.")+ print(" graff: same walk in-process (PathConfine, --add-dir) so a missing binary still lists.")+ print(" catalog tax: still one `codedb` tool. grok-build pays a first-class list_dir every turn.")+ if failed:+ print("\nshowcase failed: " + ", ".join(failed))+ return 1+ print()+ print("verdict: better (live walk, no catalog growth, no index on list)")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/src/exec.zig b/src/exec.zigindex f7a1e7ef..7cb2a92c 100644--- a/src/exec.zig+++ b/src/exec.zig@@ -57,6 +57,7 @@ const skill_docs = @import("skill_docs.zig");const mcp_schema_gate = @import("mcp_schema_gate.zig"); // #416: refuse an MCP tool whose schema was never loadedconst read_file = @import("read_file.zig");const result_read = @import("result_read.zig");+const list_dir = @import("list_dir.zig"); // codedb list_dir: in-process BFS listing// #337: edit_file's verified write path, plus the file-tool helpers that moved// out with it (this file is at the 600-line ceiling).const edit_verify = @import("edit_verify.zig");@@ -458,6 +459,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {const cmd = strField(input, "command") orelse return missingArg(gpa, "command");var it = std.mem.tokenizeAny(u8, cmd, " \t");const sub = it.next() orelse return .{ .text = try gpa.dupe(u8, "usage: codedb <subcommand> [args] — e.g. search <q>, symbol <name>, callers <name>, outline <path>"), .is_error = true };+ if (std.mem.eql(u8, sub, "list_dir")) return list_dir.exec(ctx, it.rest());// Allowlist read-only subcommands: never run the long-lived daemons// (serve/mcp) — they'd block this tool forever — or the destructive// ones (update/nuke).@@ -466,7 +468,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {for (ok_subs) |s| if (std.mem.eql(u8, s, sub)) {allowed = true;};- if (!allowed) return .{ .text = try std.fmt.allocPrint(gpa, "codedb subcommand '{s}' is not allowed here — use one of: search, symbol, callers, find, outline, read, tree, context, word, deps, glob, ls, file, hot", .{sub}), .is_error = true };+ if (!allowed) return .{ .text = try std.fmt.allocPrint(gpa, "codedb subcommand '{s}' is not allowed here — use one of: search, symbol, callers, find, outline, read, tree, list_dir, context, word, deps, glob, ls, file, hot", .{sub}), .is_error = true };var argv: std.ArrayList([]const u8) = .empty;defer argv.deinit(gpa);argv.append(gpa, "codedb") catch {};diff --git a/src/gitignore.zig b/src/gitignore.zignew file mode 100644index 00000000..6c73feae--- /dev/null+++ b/src/gitignore.zig@@ -0,0 +1,288 @@+//! gitignore matching for `codedb list_dir`.+//!+//! Subset of git's rules: comments, `!` negation, trailing-`/` directories,+//! leading-`/` (or mid-slash) anchored to the ignore file's directory, `*` / `?`+//! in a path segment, and `**` across segments. A parent directory that wins+//! as ignored hides its children (a `!` on a child does not pierce it).+//! `.git` itself is the walker's job, not this file.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++pub const Rule = struct {+ negated: bool,+ dir_only: bool,+ /// Leading `/` or a `/` in the middle — match from this ignore file's dir.+ anchored: bool,+ pattern: []const u8,+ /// Absolute directory that contained the ignore file (no trailing slash).+ base: []const u8,+};++pub const Verdict = enum { none, ignore, include };++pub fn parse(arena: Allocator, text: []const u8, base: []const u8) ![]Rule {+ var list: std.ArrayList(Rule) = .empty;+ var it = std.mem.splitScalar(u8, text, '\n');+ while (it.next()) |raw| {+ const line = trim(raw);+ if (line.len == 0 or line[0] == '#') continue;+ try list.append(arena, parseLine(line, base));+ }+ return list.items;+}++fn trim(s: []const u8) []const u8 {+ return std.mem.trim(u8, s, " \t\r");+}++fn parseLine(line: []const u8, base: []const u8) Rule {+ var s = line;+ var negated = false;+ if (s[0] == '!') {+ negated = true;+ s = s[1..];+ }+ var dir_only = false;+ if (s.len > 0 and s[s.len - 1] == '/') {+ dir_only = true;+ s = s[0 .. s.len - 1];+ }+ var anchored = false;+ if (s.len > 0 and s[0] == '/') {+ anchored = true;+ s = s[1..];+ }+ if (std.mem.indexOfScalar(u8, s, '/') != null) anchored = true;+ return .{+ .negated = negated,+ .dir_only = dir_only,+ .anchored = anchored,+ .pattern = s,+ .base = base,+ };+}++fn under(path: []const u8, root: []const u8) bool {+ if (!std.mem.startsWith(u8, path, root)) return false;+ if (path.len == root.len) return true;+ return path[root.len] == '/';+}++/// Path of `abs` relative to `base`, or null when `abs` is not under `base`.+/// The base directory itself yields empty string.+pub fn relTo(abs: []const u8, base: []const u8) ?[]const u8 {+ if (!under(abs, base)) return null;+ if (abs.len == base.len) return "";+ return abs[base.len + 1 ..];+}++fn globSeg(pat: []const u8, s: []const u8) bool {+ if (pat.len == 0) return s.len == 0;+ if (pat[0] == '*') {+ var i: usize = 0;+ while (i <= s.len) : (i += 1) {+ if (globSeg(pat[1..], s[i..])) return true;+ }+ return false;+ }+ if (s.len == 0) return false;+ if (pat[0] == '?' or pat[0] == s[0]) return globSeg(pat[1..], s[1..]);+ return false;+}++fn matchSegs(pat: []const []const u8, path: []const []const u8) bool {+ if (pat.len == 0) return path.len == 0;+ if (std.mem.eql(u8, pat[0], "**")) {+ if (pat.len == 1) return true;+ var i: usize = 0;+ while (i <= path.len) : (i += 1) {+ if (matchSegs(pat[1..], path[i..])) return true;+ }+ return false;+ }+ if (path.len == 0) return false;+ if (!globSeg(pat[0], path[0])) return false;+ return matchSegs(pat[1..], path[1..]);+}++fn split(arena: Allocator, s: []const u8) ![]const []const u8 {+ var list: std.ArrayList([]const u8) = .empty;+ var it = std.mem.splitScalar(u8, s, '/');+ while (it.next()) |p| {+ if (p.len == 0) continue;+ try list.append(arena, p);+ }+ return list.items;+}++fn matchPattern(arena: Allocator, pattern: []const u8, local: []const u8, anchored: bool) !bool {+ if (pattern.len == 0) return false;+ const p = try split(arena, pattern);+ const segs = try split(arena, local);+ if (anchored) return matchSegs(p, segs);+ var i: usize = 0;+ while (i <= segs.len) : (i += 1) {+ if (matchSegs(p, segs[i..])) return true;+ }+ return false;+}++fn ruleHits(arena: Allocator, rule: Rule, abs: []const u8, is_dir: bool) !bool {+ if (rule.dir_only and !is_dir) return false;+ const local = relTo(abs, rule.base) orelse return false;+ if (local.len == 0) return false; // the ignore file's own directory+ return matchPattern(arena, rule.pattern, local, rule.anchored);+}++/// Last matching rule wins.+pub fn verdict(arena: Allocator, rules: []const Rule, abs: []const u8, is_dir: bool) !Verdict {+ var v: Verdict = .none;+ for (rules) |r| {+ if (try ruleHits(arena, r, abs, is_dir)) {+ v = if (r.negated) .include else .ignore;+ }+ }+ return v;+}++/// True when `abs` or a parent under the walk is ignored. `walk_root` stops+/// the parent walk so we do not apply a rule to a path above the listing.+pub fn ignored(arena: Allocator, rules: []const Rule, walk_root: []const u8, abs: []const u8, is_dir: bool) !bool {+ if (!under(abs, walk_root)) return false;+ var start: usize = if (abs.len > walk_root.len) walk_root.len + 1 else abs.len;+ while (start <= abs.len) {+ const slash = if (start >= abs.len) abs.len else (std.mem.indexOfScalarPos(u8, abs, start, '/') orelse abs.len);+ const prefix = abs[0..slash];+ const prefix_dir = slash < abs.len or is_dir;+ const last = slash == abs.len;+ switch (try verdict(arena, rules, prefix, prefix_dir)) {+ .ignore => return true,+ .include => if (last) return false,+ .none => {},+ }+ if (slash == abs.len) break;+ start = slash + 1;+ }+ return false;+}++fn hasGit(io: Io, dir: []const u8) bool {+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const p = std.fmt.bufPrint(&buf, "{s}/.git", .{dir}) catch return false;+ _ = Io.Dir.cwd().statFile(io, p, .{}) catch return false;+ return true;+}++fn parentOf(path: []const u8) ?[]const u8 {+ if (path.len <= 1) return null;+ const slash = std.mem.lastIndexOfScalar(u8, path, '/') orelse return null;+ if (slash == 0) return path[0..1];+ return path[0..slash];+}++fn loadFile(io: Io, arena: Allocator, path: []const u8, base: []const u8, out: *std.ArrayList(Rule)) void {+ const text = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(64 * 1024)) catch return;+ const extra = parse(arena, text, base) catch return;+ out.appendSlice(arena, extra) catch {};+}++/// Climb from `abs_root` to the git root (or 32 parents) and load each+/// `.gitignore`, then `.git/info/exclude`. Parent files first so a nested+/// file's later rules win.+pub fn loadClimb(io: Io, arena: Allocator, abs_root: []const u8) ![]Rule {+ var dirs: std.ArrayList([]const u8) = .empty;+ var cur = abs_root;+ var git_root: ?[]const u8 = null;+ var n: usize = 0;+ while (n < 32) : (n += 1) {+ try dirs.append(arena, cur);+ if (hasGit(io, cur)) {+ git_root = cur;+ break;+ }+ cur = parentOf(cur) orelse break;+ }+ // With a git root: parent files first (nested wins). Without one: only+ // the walk root — climbing into /tmp/.gitignore would make listings+ // depend on the host.+ var out: std.ArrayList(Rule) = .empty;+ if (git_root != null) {+ var i: usize = dirs.items.len;+ while (i > 0) {+ i -= 1;+ const d = dirs.items[i];+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const gi = std.fmt.bufPrint(&buf, "{s}/.gitignore", .{d}) catch continue;+ loadFile(io, arena, gi, d, &out);+ }+ if (git_root) |g| {+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const ex = std.fmt.bufPrint(&buf, "{s}/.git/info/exclude", .{g}) catch return out.items;+ loadFile(io, arena, ex, g, &out);+ }+ } else {+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const gi = std.fmt.bufPrint(&buf, "{s}/.gitignore", .{abs_root}) catch return out.items;+ loadFile(io, arena, gi, abs_root, &out);+ }+ return out.items;+}++test "star and dir-only and negation" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const rules = try parse(a, "*.log\nbuild/\n!keep.log\n", "/work");+ try std.testing.expect(try ignored(a, rules, "/work", "/work/a.log", false));+ try std.testing.expect(!try ignored(a, rules, "/work", "/work/a.zig", false));+ try std.testing.expect(try ignored(a, rules, "/work", "/work/build", true));+ try std.testing.expect(try ignored(a, rules, "/work", "/work/build/x.o", false));+ try std.testing.expect(!try ignored(a, rules, "/work", "/work/keep.log", false));+}++test "rooted pattern does not match nested names" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const rules = try parse(a, "/secret\n", "/work");+ try std.testing.expect(try ignored(a, rules, "/work", "/work/secret", false));+ try std.testing.expect(!try ignored(a, rules, "/work", "/work/sub/secret", false));+}++test "nested ignore file only covers its subtree" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const rules = try parse(a, "*.tmp\n", "/work/src");+ try std.testing.expect(try ignored(a, rules, "/work", "/work/src/x.tmp", false));+ try std.testing.expect(!try ignored(a, rules, "/work", "/work/x.tmp", false));+}++test "without a git root only the walk dir gitignore applies" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ tmp.dir.writeFile(io, .{ .sub_path = ".gitignore", .data = "local.skip\n" }) catch unreachable;+ tmp.dir.writeFile(io, .{ .sub_path = "local.skip", .data = "x" }) catch unreachable;+ tmp.dir.writeFile(io, .{ .sub_path = "keep.txt", .data = "x" }) catch unreachable;+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const n = try tmp.dir.realPath(io, &buf);+ const rules = try loadClimb(io, a, buf[0..n]);+ try std.testing.expect(try ignored(a, rules, buf[0..n], try std.fmt.allocPrint(a, "{s}/local.skip", .{buf[0..n]}), false));+ try std.testing.expect(!try ignored(a, rules, buf[0..n], try std.fmt.allocPrint(a, "{s}/keep.txt", .{buf[0..n]}), false));+}++test "double-star and comments" {+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ const a = arena_state.allocator();+ const rules = try parse(a, "# hi\n\n**/skip.dat\n", "/work");+ try std.testing.expect(try ignored(a, rules, "/work", "/work/skip.dat", false));+ try std.testing.expect(try ignored(a, rules, "/work", "/work/a/b/skip.dat", false));+ try std.testing.expect(!try ignored(a, rules, "/work", "/work/keep.dat", false));+}diff --git a/src/list_dir.zig b/src/list_dir.zignew file mode 100644index 00000000..6d513c9d--- /dev/null+++ b/src/list_dir.zig@@ -0,0 +1,488 @@+//! grok-build-style directory listing, served as `codedb list_dir`.+//!+//! Not a new catalog tool (that tax is how #574 lost its first A/B). The+//! model already has `codedb` and is told to prefer it over bash ls. This+//! subcommand is in-process — PathConfine, extra `--add-dir` roots, works+//! without a codedb binary. The same command lives in the codedb repo+//! (`src/list_dir.zig` there, issue #696) for CLI/MCP; keep the output+//! aligned. `codedb ls` / `tree` remain index queries.+//!+//! BFS seed of depth-1 first, then a budgeted deep walk. `.gitignore` (and+//! `.git/info/exclude`) hide noise. Output is capped at 10k characters;+//! 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).++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const tools = @import("tools.zig");+const approvals = @import("approvals.zig");+const gitignore = @import("gitignore.zig");++pub const max_output_chars: usize = 10_000;+pub const max_walk_items: usize = 20_000;+pub const top_k_exts: usize = 3;++const root_truncation_notice =+ \\ ...+ \\+ \\Note: this directory is too large to list fully. Try codedb list_dir on a narrower path, or use codedb search / bash.+;++const walk_truncation_notice =+ \\+ \\Note: there are more than 20000 items in the directory, so not all files may be shown.+;++const Node = struct {+ name: []const u8,+ is_dir: bool,+ depth: usize,+ parent: ?*Node,+ kids: std.ArrayList(*Node),+ file_count: usize,+ ext: std.StringHashMap(usize),+ expanded: bool,+};++fn newNode(arena: Allocator, name: []const u8, is_dir: bool, depth: usize, parent: ?*Node) !*Node {+ const n = try arena.create(Node);+ n.* = .{+ .name = name,+ .is_dir = is_dir,+ .depth = depth,+ .parent = parent,+ .kids = .empty,+ .file_count = 0,+ .ext = std.StringHashMap(usize).init(arena),+ .expanded = false,+ };+ return n;+}++fn extKey(arena: Allocator, name: []const u8) ![]const u8 {+ const dot = std.mem.lastIndexOfScalar(u8, name, '.') orelse return "no-ext";+ if (dot == 0 or dot + 1 == name.len) return "no-ext";+ const raw = name[dot + 1 ..];+ const out = try arena.alloc(u8, raw.len);+ for (raw, out) |c, *d| d.* = std.ascii.toLower(c);+ return out;+}++fn addFile(arena: Allocator, node: *Node, name: []const u8) !void {+ const key = try extKey(arena, name);+ var p: ?*Node = node;+ while (p) |n| {+ n.file_count += 1;+ const gop = try n.ext.getOrPut(key);+ if (!gop.found_existing) gop.value_ptr.* = 0;+ gop.value_ptr.* += 1;+ p = n.parent;+ }+}++fn join(arena: Allocator, a: []const u8, b: []const u8) ![]const u8 {+ if (a.len == 0) return b;+ return std.fmt.allocPrint(arena, "{s}/{s}", .{ a, b });+}++fn isGitComponent(name: []const u8) bool {+ return std.mem.eql(u8, name, ".git");+}++const Walk = struct {+ io: Io,+ arena: Allocator,+ root_abs: []const u8,+ rules: std.ArrayList(gitignore.Rule),+ items: usize = 0,+ truncated: bool = false,+};++fn skip(w: *Walk, abs: []const u8, is_dir: bool) !bool {+ if (isGitComponent(std.fs.path.basename(abs))) return true;+ return gitignore.ignored(w.arena, w.rules.items, w.root_abs, abs, is_dir);+}++fn fill(w: *Walk, node: *Node, rel: []const u8) !void {+ const abs = if (rel.len == 0) w.root_abs else try join(w.arena, w.root_abs, rel);+ var dir = Io.Dir.cwd().openDir(w.io, abs, .{ .iterate = true, .follow_symlinks = false }) catch return;+ defer dir.close(w.io);++ var names: std.ArrayList(struct { name: []const u8, is_dir: bool }) = .empty;+ var it = dir.iterate();+ var saw_ignore = false;+ while (it.next(w.io) catch null) |ent| {+ if (ent.kind == .sym_link) continue;+ const name = try w.arena.dupe(u8, ent.name);+ if (std.mem.eql(u8, name, ".gitignore") and rel.len > 0) saw_ignore = true;+ const is_dir = ent.kind == .directory;+ try names.append(w.arena, .{ .name = name, .is_dir = is_dir });+ }+ if (saw_ignore) {+ const gi = try join(w.arena, abs, ".gitignore");+ const text = Io.Dir.cwd().readFileAlloc(w.io, gi, w.arena, .limited(64 * 1024)) catch null;+ if (text) |t| {+ const extra = gitignore.parse(w.arena, t, abs) catch &.{};+ w.rules.appendSlice(w.arena, extra) catch {};+ }+ }++ for (names.items) |e| {+ if (isGitComponent(e.name)) continue;+ const child_rel = if (rel.len == 0) e.name else try join(w.arena, rel, e.name);+ const child_abs = try join(w.arena, w.root_abs, child_rel);+ if (try skip(w, child_abs, e.is_dir)) continue;+ const child = try newNode(w.arena, e.name, e.is_dir, node.depth + 1, node);+ try node.kids.append(w.arena, child);+ if (!e.is_dir) try addFile(w.arena, node, e.name);+ w.items += 1;+ if (w.items >= max_walk_items) {+ w.truncated = true;+ return;+ }+ }+}++fn nameLess(_: void, a: *Node, b: *Node) bool {+ const an = a.name;+ const bn = b.name;+ const n = @min(an.len, bn.len);+ var i: usize = 0;+ while (i < n) : (i += 1) {+ const ca = std.ascii.toLower(an[i]);+ const cb = std.ascii.toLower(bn[i]);+ if (ca < cb) return true;+ if (ca > cb) return false;+ }+ return an.len < bn.len;+}++fn sortTree(n: *Node) void {+ std.mem.sort(*Node, n.kids.items, {}, nameLess);+ for (n.kids.items) |k| sortTree(k);+}++const ExtPair = struct { k: []const u8, n: usize };++fn extLess(_: void, a: ExtPair, b: ExtPair) bool {+ if (a.n != b.n) return a.n > b.n;+ return std.mem.lessThan(u8, a.k, b.k);+}++fn summary(arena: Allocator, n: *Node) ![]const u8 {+ if (n.file_count == 0) return "";+ var pairs: std.ArrayList(ExtPair) = .empty;+ var it = n.ext.iterator();+ while (it.next()) |e| try pairs.append(arena, .{ .k = e.key_ptr.*, .n = e.value_ptr.* });+ std.mem.sort(ExtPair, pairs.items, {}, extLess);+ const take = @min(pairs.items.len, top_k_exts);+ var aw: Io.Writer.Allocating = .init(arena);+ const word: []const u8 = if (n.file_count == 1) "file" else "files";+ try aw.writer.print("[{d} {s} in subtree: ", .{ n.file_count, word });+ var shown: usize = 0;+ for (pairs.items[0..take], 0..) |p, i| {+ if (i > 0) try aw.writer.writeAll(", ");+ if (std.mem.eql(u8, p.k, "no-ext")) {+ try aw.writer.print("{d} *no-ext", .{p.n});+ } else {+ try aw.writer.print("{d} *.{s}", .{ p.n, p.k });+ }+ shown += p.n;+ }+ if (shown < n.file_count) try aw.writer.writeAll(", ...");+ try aw.writer.writeByte(']');+ return aw.writer.buffered();+}++fn writeKidLine(w: *Io.Writer, n: *Node, child: *Node) !void {+ var i: usize = 0;+ while (i < n.depth + 1) : (i += 1) try w.writeAll(" ");+ try w.writeAll("- ");+ try w.writeAll(child.name);+ if (child.is_dir) try w.writeByte('/');+ try w.writeByte('\n');+}++fn renderKids(arena: Allocator, n: *Node) ![]const u8 {+ var aw: Io.Writer.Allocating = .init(arena);+ for (n.kids.items) |child| {+ try writeKidLine(&aw.writer, n, child);+ if (!child.is_dir) continue;+ if (child.expanded) {+ try aw.writer.writeAll(try renderKids(arena, child));+ } else {+ const sum = try summary(arena, child);+ if (sum.len == 0) continue;+ var i: usize = 0;+ while (i < n.depth + 2) : (i += 1) try aw.writer.writeAll(" ");+ try aw.writer.writeAll(sum);+ try aw.writer.writeByte('\n');+ }+ }+ return aw.writer.buffered();+}++fn truncateRoot(arena: Allocator, root: *Node, budget: usize) ![]const u8 {+ var aw: Io.Writer.Allocating = .init(arena);+ var used: usize = 0;+ for (root.kids.items) |child| {+ var chunk: Io.Writer.Allocating = .init(arena);+ try writeKidLine(&chunk.writer, root, child);+ if (child.is_dir) {+ const sum = try summary(arena, child);+ if (sum.len > 0) {+ try chunk.writer.writeAll(" ");+ try chunk.writer.writeAll(sum);+ try chunk.writer.writeByte('\n');+ }+ }+ const bytes = chunk.writer.buffered();+ if (used + bytes.len > budget) break;+ try aw.writer.writeAll(bytes);+ used += bytes.len;+ }+ try aw.writer.writeAll(root_truncation_notice);+ return aw.writer.buffered();+}++fn budgetExpand(arena: Allocator, root: *Node, max_chars: usize, walk_cut: bool) ![]const u8 {+ const cutoff: []const u8 = if (walk_cut) walk_truncation_notice else "";+ if (root.kids.items.len == 0) return cutoff;+ root.expanded = true;+ const first = try renderKids(arena, root);+ if (first.len > max_chars) {+ return std.fmt.allocPrint(arena, "{s}{s}", .{ try truncateRoot(arena, root, max_chars), cutoff });+ }+ var remaining = max_chars - first.len;+ var q: std.ArrayList(*Node) = .empty;+ for (root.kids.items) |k| {+ if (k.is_dir) try q.append(arena, k);+ }+ var qi: usize = 0;+ while (qi < q.items.len) : (qi += 1) {+ const node = q.items[qi];+ node.expanded = true;+ const expanded = try renderKids(arena, node);+ const sum = try summary(arena, node);+ const sum_cost: usize = if (sum.len == 0) 0 else (node.depth + 1) * 2 + sum.len + 1;+ if (expanded.len > remaining + sum_cost) {+ node.expanded = false;+ continue;+ }+ remaining += sum_cost;+ remaining -= expanded.len;+ for (node.kids.items) |k| {+ if (k.is_dir) try q.append(arena, k);+ }+ }+ return std.fmt.allocPrint(arena, "{s}{s}", .{ try renderKids(arena, root), cutoff });+}++fn walkTree(io: Io, arena: Allocator, abs: []const u8) !struct { root: *Node, truncated: bool } {+ const climbed = try gitignore.loadClimb(io, arena, abs);+ var w: Walk = .{+ .io = io,+ .arena = arena,+ .root_abs = abs,+ .rules = .empty,+ };+ try w.rules.appendSlice(arena, climbed);+ const root = try newNode(arena, "", true, 0, null);+ try fill(&w, root, "");+ var q: std.ArrayList(struct { n: *Node, rel: []const u8 }) = .empty;+ for (root.kids.items) |k| {+ if (k.is_dir) try q.append(arena, .{ .n = k, .rel = k.name });+ }+ var qi: usize = 0;+ while (qi < q.items.len and !w.truncated) : (qi += 1) {+ const item = q.items[qi];+ try fill(&w, item.n, item.rel);+ for (item.n.kids.items) |k| {+ if (k.is_dir) try q.append(arena, .{ .n = k, .rel = try join(arena, item.rel, k.name) });+ }+ }+ sortTree(root);+ return .{ .root = root, .truncated = w.truncated };+}++fn stripDot(path: []const u8) []const u8 {+ const t = std.mem.trim(u8, path, " \t");+ if (t.len == 0) return ".";+ if (std.mem.eql(u8, t, ".") or std.mem.eql(u8, t, "./")) return ".";+ if (std.mem.startsWith(u8, t, "./")) return t[2..];+ return t;+}++/// Render a listing for an already-resolved absolute directory.+pub fn listAbs(io: Io, arena: Allocator, abs: []const u8, display: []const u8) ![]const u8 {+ const walked = try walkTree(io, arena, abs);+ const body = try budgetExpand(arena, walked.root, max_output_chars, walked.truncated);+ const trimmed = std.mem.trimEnd(u8, body, "\n");+ if (trimmed.len == 0) return std.fmt.allocPrint(arena, "- {s}/", .{display});+ return std.fmt.allocPrint(arena, "- {s}/\n{s}", .{ display, trimmed });+}++fn resolveAbs(gpa: Allocator, path: []const u8, agent_cwd: ?[]const u8) ![]const u8 {+ if (std.fs.path.isAbsolute(path)) return path;+ if (agent_cwd) |base| return std.fmt.allocPrint(gpa, "{s}/{s}", .{ base, path });+ return path;+}++/// PathConfine + list. `rest` is everything after `list_dir` in the codedb command.+pub fn run(io: Io, gpa: Allocator, rest: []const u8, agent_cwd: ?[]const u8) !tools.ToolOutput {+ const path = stripDot(rest);+ if (!approvals.confinedPath(path) or !approvals.noSymlinkEscape(io, path, agent_cwd))+ return tools.outsideCwd(gpa, path);++ var scratch = std.heap.ArenaAllocator.init(gpa);+ defer scratch.deinit();+ const arena = scratch.allocator();++ const resolved = try resolveAbs(gpa, path, agent_cwd);+ defer if (resolved.ptr != path.ptr) gpa.free(resolved);++ const 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}),+ .is_error = true,+ },+ error.AccessDenied => return .{+ .text = try std.fmt.allocPrint(gpa, "Permission denied: {s}", .{path}),+ .is_error = true,+ },+ else => return .{+ .text = try std.fmt.allocPrint(gpa, "Error: {s} is not a valid directory.", .{path}),+ .is_error = true,+ },+ };+ if (st.kind == .file) return .{+ .text = try std.fmt.allocPrint(gpa, "Error: {s} is a file, not a directory.", .{path}),+ .is_error = true,+ };+ if (st.kind != .directory) return .{+ .text = try std.fmt.allocPrint(gpa, "Error: {s} is not a valid directory.", .{path}),+ .is_error = true,+ };++ var buf: [std.fs.max_path_bytes]u8 = undefined;+ var opened = Io.Dir.cwd().openDir(io, resolved, .{}) catch return .{+ .text = try std.fmt.allocPrint(gpa, "Error: {s} is not a valid directory.", .{path}),+ .is_error = true,+ };+ defer opened.close(io);+ const n = opened.realPath(io, &buf) catch return .{+ .text = try std.fmt.allocPrint(gpa, "Error: {s} is not a valid directory.", .{path}),+ .is_error = true,+ };+ const abs = buf[0..n];+ const text = try listAbs(io, arena, abs, path);+ return .{ .text = try gpa.dupe(u8, text) };+}++pub fn exec(ctx: tools.ToolCtx, rest: []const u8) !tools.ToolOutput {+ return run(ctx.io, ctx.gpa, rest, ctx.agent_cwd);+}++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 "lists files and dirs, hides gitignore and .git" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ tmp.dir.writeFile(io, .{ .sub_path = ".gitignore", .data = "skip.log\nbuild/\n" }) catch unreachable;+ tmp.dir.writeFile(io, .{ .sub_path = "keep.zig", .data = "x" }) catch unreachable;+ tmp.dir.writeFile(io, .{ .sub_path = "skip.log", .data = "x" }) catch unreachable;+ tmp.dir.createDirPath(io, "build") catch unreachable;+ tmp.dir.writeFile(io, .{ .sub_path = "build/a.o", .data = "x" }) catch unreachable;+ tmp.dir.createDirPath(io, ".git/objects") catch unreachable;+ tmp.dir.writeFile(io, .{ .sub_path = ".git/HEAD", .data = "ref\n" }) catch unreachable;+ tmp.dir.createDirPath(io, ".github") catch unreachable;+ tmp.dir.writeFile(io, .{ .sub_path = ".github/ci.yml", .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 = try listAbs(io, arena_state.allocator(), abs, ".");+ try std.testing.expect(std.mem.indexOf(u8, out, "keep.zig") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, ".github") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "skip.log") == null);+ try std.testing.expect(std.mem.indexOf(u8, out, "build") == null);+ try std.testing.expect(std.mem.indexOf(u8, out, ".git/") == null);+}++test "fat sibling collapses; later sibling still listed" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ tmp.dir.createDirPath(io, "aaa") catch unreachable;+ var i: usize = 0;+ while (i < 800) : (i += 1) {+ var name: [48]u8 = undefined;+ const n = std.fmt.bufPrint(&name, "aaa/file_with_a_longer_name_{d:0>3}.zig", .{i}) catch unreachable;+ tmp.dir.writeFile(io, .{ .sub_path = n, .data = "x" }) catch unreachable;+ }+ tmp.dir.createDirPath(io, "zzz") catch unreachable;+ tmp.dir.writeFile(io, .{ .sub_path = "zzz/tail.md", .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 = try listAbs(io, arena_state.allocator(), abs, "root");+ try std.testing.expect(std.mem.indexOf(u8, out, "- aaa/") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "- zzz/") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "files in subtree") != null);+ try std.testing.expect(std.mem.indexOf(u8, out, "*.zig") != null);+ try std.testing.expect(out.len < max_output_chars + root_truncation_notice.len + 64);+}++test "run refuses a file and an escaped path" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ tmp.dir.writeFile(io, .{ .sub_path = "only.txt", .data = "x" }) catch unreachable;+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const abs = try tmpAbs(io, &tmp, &buf);+ const file_abs = try std.fmt.allocPrint(std.testing.allocator, "{s}/only.txt", .{abs});+ defer std.testing.allocator.free(file_abs);++ const workspace_roots = @import("workspace_roots.zig");+ workspace_roots.resetForTest();+ defer workspace_roots.resetForTest();+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena_state.deinit();+ try workspace_roots.add(io, arena_state.allocator(), abs);++ const as_file = try run(io, std.testing.allocator, file_abs, null);+ defer std.testing.allocator.free(as_file.text);+ try std.testing.expect(as_file.is_error);+ try std.testing.expect(std.mem.indexOf(u8, as_file.text, "is a file") != null);++ const escaped = try run(io, std.testing.allocator, "../outside", null);+ defer std.testing.allocator.free(escaped.text);+ try std.testing.expect(escaped.is_error);++ const listing = try run(io, std.testing.allocator, abs, null);+ defer std.testing.allocator.free(listing.text);+ try std.testing.expect(!listing.is_error);+ try std.testing.expect(std.mem.indexOf(u8, listing.text, "only.txt") != null);+}++test "empty directory is a header only" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{ .iterate = true });+ defer tmp.cleanup();+ 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 = try listAbs(io, arena_state.allocator(), abs, "empty");+ try std.testing.expectEqualStrings("- empty/", out);+}diff --git a/src/prompt_snapshot_tests.zig b/src/prompt_snapshot_tests.zigindex 6faa242d..8fe68050 100644--- a/src/prompt_snapshot_tests.zig+++ b/src/prompt_snapshot_tests.zig@@ -41,7 +41,7 @@ const golden_full_prompt =\\call read_file once with contains set to the exact key and answer from its\\output; do not request the whole file first. To navigate code — finding symbols,\\definitions, or where logic lives — prefer the codedb tool (it's indexed- \\and structural) over bash grep/find/ls. Before an exact edit, read one current uncompressed target span, apply the smallest edit that preserves terminal-newline state, do not verify after success, and reread/retry only on stale source, ambiguity, or failure. Some bash commands need user approval — if one+ \\and structural) over bash grep/find/ls. For a folder, codedb list_dir <path> is a bounded BFS listing that honors .gitignore — use it instead of bash ls. Before an exact edit, read one current uncompressed target span, apply the smallest edit that preserves terminal-newline state, do not verify after success, and reread/retry only on stale source, ambiguity, or failure. Some bash commands need user approval — if one\\is declined, try another approach or ask. Native file tools deliberately\\stay inside the current working directory. If the user explicitly names\\a repository or path outside it, the root agent may inspect and modifydiff --git a/src/prompt_text.zig b/src/prompt_text.zigindex ec6fb1d8..f1fd6e37 100644--- a/src/prompt_text.zig+++ b/src/prompt_text.zig@@ -38,7 +38,7 @@ pub const local_tools_note =\\call read_file once with contains set to the exact key and answer from its\\output; do not request the whole file first. To navigate code — finding symbols,\\definitions, or where logic lives — prefer the codedb tool (it's indexed- \\and structural) over bash grep/find/ls. Before an exact edit, read one current uncompressed target span, apply the smallest edit that preserves terminal-newline state, do not verify after success, and reread/retry only on stale source, ambiguity, or failure. Some bash commands need user approval — if one+ \\and structural) over bash grep/find/ls. For a folder, codedb list_dir <path> is a bounded BFS listing that honors .gitignore — use it instead of bash ls. Before an exact edit, read one current uncompressed target span, apply the smallest edit that preserves terminal-newline state, do not verify after success, and reread/retry only on stale source, ambiguity, or failure. Some bash commands need user approval — if one\\is declined, try another approach or ask. Native file tools deliberately\\stay inside the current working directory. If the user explicitly names\\a repository or path outside it, the root agent may inspect and modifydiff --git a/src/schema.zig b/src/schema.zigindex 047c2272..bbc7a2b8 100644--- a/src/schema.zig+++ b/src/schema.zig@@ -104,9 +104,9 @@ const base_specs = [_]ToolSpec{.{ .name = skill_docs.tool_name, .desc = skill_docs.tool_desc, .schema = skill_docs.tool_schema },.{.name = "codedb",- .desc = "Query codedb (github.com/justrach/codedb) — the code-intelligence index for this repo (fast & structural; prefer over grep/bash for navigating code). `command` is a codedb subcommand line: search <query> | symbol <name> [--body] | callers <name> | outline <path> | find <name> | deps <path> | tree | context <task...> | read <path>.",+ .desc = "Query codedb (github.com/justrach/codedb) — the code-intelligence index for this repo (fast & structural; prefer over grep/bash for navigating code). `command` is a codedb subcommand line: search <query> | symbol <name> [--body] | callers <name> | outline <path> | find <name> | deps <path> | tree | list_dir <path> | context <task...> | read <path>. list_dir is a live BFS listing (gitignore, 10k-char cap): in-process here so PathConfine and --add-dir work without a codedb binary; the same command exists on the codedb CLI.",.schema =- \\{"type": "object", "properties": {"command": {"type": "string", "description": "codedb subcommand + args, e.g. \"search parseHeader\", \"symbol buildBody --body\", \"callers switchProvider\""}}, "required": ["command"]}+ \\{"type": "object", "properties": {"command": {"type": "string", "description": "codedb subcommand + args, e.g. \"search parseHeader\", \"list_dir src\", \"symbol buildBody --body\""}}, "required": ["command"]},},.{ .name = result_read.tool_name, .desc = result_read.tool_desc, .schema = result_read.tool_schema },diff --git a/src/test_hooks.zig b/src/test_hooks.zigindex 6a2bcd4e..456486f7 100644--- a/src/test_hooks.zig+++ b/src/test_hooks.zig@@ -131,6 +131,8 @@ const result_read = @import("result_read.zig"); // overflow handle pagerconst handle_preview = @import("handle_preview.zig"); // notable lines on first spillconst context_limits = @import("context_limits.zig"); // named prefix capsconst workspace_roots = @import("workspace_roots.zig"); // --add-dir extra roots+const list_dir = @import("list_dir.zig"); // codedb list_dir (BFS + gitignore)+const gitignore = @import("gitignore.zig"); // ignore matcher for list_dirconst mcp_select = @import("mcp_select.zig"); // search-then-select MCPconst plugins = @import("plugins.zig"); // ADR 0007 in-place plugin / foreign MCP discoveryconst plugin_layout = @import("plugin_layout.zig"); // Claude commands/ + inline MCP + ${CLAUDE_PLUGIN_ROOT}@@ -272,6 +274,8 @@ test {_ = result_read;_ = context_limits;_ = workspace_roots;+ _ = list_dir;+ _ = gitignore;_ = mcp_select;_ = plugins;_ = plugin_layout;