graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(codedb): advertise five one-shots on the v0.0.269 line
Rache2f52b1abfde
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2ab6b323..5b540d17 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -12,6 +12,9 @@ current is part of cutting a release.## v0.0.269 (2026-08-20)+- codedb pairing (ADR 0019): advertise five one-shots — `context <task>`,+ `around <name>` (def+callers), `callpath A B`, `list_dir <path>`,+ `status`. Hop verbs stay callable, not on the catalog menu.- Vercel AI Gateway is a built-in OpenAI-chat seat (`AI_GATEWAY_API_KEY`,`graff key set vercel …`, default `alibaba/qwen3.8-27b`). Chat goes to`ai-gateway.vercel.sh/coding-agent/v1` (docs: marks harness traffic;diff --git a/docs/adr/0019-codedb-one-shot-over-hop-chains.md b/docs/adr/0019-codedb-one-shot-over-hop-chains.mdnew file mode 100644index 00000000..1c7c176d--- /dev/null+++ b/docs/adr/0019-codedb-one-shot-over-hop-chains.md@@ -0,0 +1,35 @@+# 0019. codedb one-shots beat hop chains++Status: accepted 2026-08-21++## Context++[graphify](https://github.com/safishamsi/graphify) spends fewer agent+calls because the verbs are neighborhoods, not lookups: `query` (task+subgraph), `explain` (ego graph), `path A B` (shortest chain). codedb+already has the same primitives — `context <task>` (task-shaped+composer), `callpath A B` (resolved call graph BFS), PageRank god-nodes+inside the index — and it is deterministic AST, not an LLM extractor.+The harness advertised `search` / `symbol` / `callers` / `outline` as+siblings, so models paid 3–5 round-trips for one question. `callpath`+was implemented in codedb and blocked here.++## Decision++The catalog advertises five commands only: `context <task>`,+`around <name>` (def body + callers in one harness call), `callpath A B`+(`path` is an alias), `list_dir <path>`, `status`. Hop verbs+(`search` / `symbol` / `callers` / `outline` / `read` / …) stay+callable so a follow-up is not a dead end; they are not named in the+tool description or the system prompt. Do not add a graphify-style LLM+extract / wiki / GRAPH_REPORT inside graff — that is a different+product. Do not add a sibling catalog tool for "ask the graph."++## Consequences++- First-touch orientation is one model hop when the model follows the+ description.+- `around` is two codedb CLI spawns, one tool result. A codedb release+ with a native `explain` can replace the composer later.+- graphify still wins on multimodal docs/images and a written wiki;+ codedb still wins on local, labeled, sub-millisecond structural edges.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex e6c685ec..e884973c 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -29,6 +29,7 @@ record only when you need the evidence or the edge cases.| [0016](0016-line-repl-is-a-working-block.md) | Line REPL chrome is a `WORKING` block plus a bare `›`; tool fan-out is a tree, never `✓ bash`. || [0017](0017-model-election-ranks-signed-in-plans-first.md) | `/model` and `/models` on both frontends rank signed-in plan seats above credits and metered keys (`src/models_rank.zig`). || [0018](0018-standing-chrome-shows-last-turn-cache-hit.md) | Last-turn cache hit % rides with `ctx` on the line-REPL meter and the TUI footer; `/cache` stays the posture HUD. |+| [0019](0019-codedb-one-shot-over-hop-chains.md) | Advertise only `context` / `around` / `callpath` / `list_dir` / `status`; hop verbs stay callable, not on the menu. |## When to write onediff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex 64322d70..44d3d472 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": 1531,+ "test_count_baseline": 1557,"test_count_slack": 25,"required_invariants": [{diff --git a/src/codedb_around.zig b/src/codedb_around.zignew file mode 100644index 00000000..f5feb00d--- /dev/null+++ b/src/codedb_around.zig@@ -0,0 +1,110 @@+//! One-shot codedb composers. Graphify's hop win is `explain` / `path` /+//! `query` — one call, a neighborhood. codedb already has the graph+//! (`callpath`) and a task composer (`context`); this module collapses the+//! remaining "symbol then callers" dance the model otherwise pays two+//! round-trips for.++const std = @import("std");+const Allocator = std.mem.Allocator;++const tools = @import("tools.zig");+const ToolCtx = tools.ToolCtx;+const ToolOutput = tools.ToolOutput;+const jobs = @import("jobs.zig");++const deadline_ms: u64 = 60 * 1000;+const section_cap = 24 * 1024;++pub fn firstIdent(rest: []const u8) ?[]const u8 {+ var it = std.mem.tokenizeAny(u8, rest, " \t");+ while (it.next()) |tok| {+ if (tok.len == 0 or tok[0] == '-') continue;+ return tok;+ }+ return null;+}++pub fn pathEnds(rest: []const u8) ?struct { from: []const u8, to: []const u8 } {+ var it = std.mem.tokenizeAny(u8, rest, " \t");+ const from = it.next() orelse return null;+ const to = it.next() orelse return null;+ if (from[0] == '-' or to[0] == '-') return null;+ return .{ .from = from, .to = to };+}++fn spawn(ctx: ToolCtx, argv_tail: []const []const u8) !ToolOutput {+ const gpa = ctx.gpa;+ var argv: std.ArrayList([]const u8) = .empty;+ defer argv.deinit(gpa);+ try argv.append(gpa, "codedb");+ try argv.appendSlice(gpa, argv_tail);+ const run = jobs.runCappedWithOptions(gpa, ctx.io, argv.items, 512 * 1024, 4096, deadline_ms, jobs.toolRunOptions(ctx.agent_cwd)) catch |e| switch (e) {+ error.FileNotFound => return .{+ .text = try gpa.dupe(u8, "codedb isn't installed — it's open source at github.com/justrach/codedb; install it, then run `codedb` once in the repo to index it. Folder listing still works: codedb list_dir ."),+ .is_error = true,+ },+ else => return tools.failure(gpa, e),+ };+ gpa.free(run.stderr);+ const text = run.stdout;+ if (run.timed_out) {+ defer gpa.free(text);+ return .{+ .text = try std.fmt.allocPrint(gpa, "codedb {s} timed out after {d}s and was killed — narrow the query", .{ argv_tail[0], deadline_ms / 1000 }),+ .is_error = true,+ };+ }+ return .{ .text = text };+}++fn take(gpa: Allocator, out: ToolOutput, cap: usize) ![]u8 {+ defer gpa.free(out.text);+ const src = if (out.text.len > cap) out.text[0..cap] else out.text;+ return gpa.dupe(u8, src);+}++pub fn execAround(ctx: ToolCtx, rest: []const u8) !ToolOutput {+ const gpa = ctx.gpa;+ const name = firstIdent(rest) orelse return .{+ .text = try gpa.dupe(u8, "usage: codedb around <name> — definition body + callers in one call (graphify explain). Alias: explain <name>."),+ .is_error = true,+ };++ const def = try spawn(ctx, &.{ "symbol", name, "--body" });+ if (def.is_error) return def;+ const def_text = try take(gpa, def, section_cap);+ defer gpa.free(def_text);++ const callers = try spawn(ctx, &.{ "callers", name });+ if (callers.is_error) {+ defer gpa.free(callers.text);+ return .{ .text = try std.fmt.allocPrint(gpa, "## definition\n{s}\n\n## callers\n{s}", .{ def_text, callers.text }), .is_error = true };+ }+ const callers_text = try take(gpa, callers, section_cap);+ defer gpa.free(callers_text);++ return .{ .text = try std.fmt.allocPrint(gpa, "## definition\n{s}\n\n## callers\n{s}", .{ def_text, callers_text }) };+}++pub fn execPath(ctx: ToolCtx, rest: []const u8) !ToolOutput {+ const ends = pathEnds(rest) orelse return .{+ .text = try ctx.gpa.dupe(u8, "usage: codedb callpath <from> <to> — shortest resolved call chain (graphify path). Alias: path <from> <to>."),+ .is_error = true,+ };+ return spawn(ctx, &.{ "callpath", ends.from, ends.to });+}++test "firstIdent skips flags" {+ try std.testing.expectEqualStrings("handleCallpath", firstIdent("handleCallpath").?);+ try std.testing.expectEqualStrings("Store", firstIdent("--body Store").?);+ try std.testing.expect(firstIdent("") == null);+ try std.testing.expect(firstIdent(" ") == null);+}++test "pathEnds needs two identifiers" {+ const got = pathEnds("handleContext handleCallpath").?;+ try std.testing.expectEqualStrings("handleContext", got.from);+ try std.testing.expectEqualStrings("handleCallpath", got.to);+ try std.testing.expect(pathEnds("onlyOne") == null);+ try std.testing.expect(pathEnds("") == null);+}diff --git a/src/codedb_exec.zig b/src/codedb_exec.zignew file mode 100644index 00000000..03b69582--- /dev/null+++ b/src/codedb_exec.zig@@ -0,0 +1,206 @@+//! Native `codedb` tool dispatch. Split out of exec.zig (600-line cap).+//!+//! In-process: `list_dir` (PathConfine + gitignore) and `status` (snapshot+//! health). Everything else is a read-only spawn of the codedb binary.+//! Path-bearing subcommands (read/outline/deps/file) get the same jail as+//! read_file — the binary is not a second way out of the cwd.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const tools = @import("tools.zig");+const ToolCtx = tools.ToolCtx;+const ToolOutput = tools.ToolOutput;+const harness_policy = @import("harness_policy.zig");+const list_dir = @import("list_dir.zig");+const codedb_health = @import("codedb_health.zig");+const codedb_around = @import("codedb_around.zig");+const jobs = @import("jobs.zig");+const main_mod = @import("main.zig");+const hooks = @import("hooks.zig");++pub const deadline_ms: u64 = 60 * 1000;++/// What the catalog and prompt name. Hop verbs stay callable so a+/// follow-up is not a dead end, but they are not advertised (ADR 0019).+const advertised_subs = [_][]const u8{ "context", "around", "callpath", "list_dir", "status" };++const ok_subs = advertised_subs ++ [_][]const u8{+ "search", "symbol", "callers", "find", "outline", "read", "tree",+ "word", "deps", "glob", "ls", "file", "hot", "path",+ "explain",+};++const path_subs = [_][]const u8{ "outline", "read", "deps", "file" };++fn allowed(sub: []const u8) bool {+ for (ok_subs) |s| if (std.mem.eql(u8, s, sub)) return true;+ return false;+}++fn isPathSub(sub: []const u8) bool {+ for (path_subs) |s| if (std.mem.eql(u8, s, sub)) return true;+ return false;+}++fn firstPathArg(rest: []const u8) ?[]const u8 {+ var it = std.mem.tokenizeAny(u8, rest, " \t");+ var skip_next = false;+ while (it.next()) |tok| {+ if (skip_next) {+ skip_next = false;+ continue;+ }+ if (tok.len == 0) continue;+ if (tok[0] == '-') {+ if (std.mem.eql(u8, tok, "-L") or std.mem.eql(u8, tok, "--lines")) skip_next = true;+ continue;+ }+ return tok;+ }+ return null;+}++fn globEscapes(pattern: []const u8) bool {+ if (pattern.len == 0) return false;+ if (pattern[0] == '/') return true;+ var it = std.mem.tokenizeAny(u8, pattern, "/\\");+ while (it.next()) |comp| {+ if (std.mem.eql(u8, comp, "..")) return true;+ }+ return false;+}++pub fn exec(ctx: ToolCtx, input: std.json.Value) !ToolOutput {+ const gpa = ctx.gpa;+ const io = ctx.io;+ const cmd = tools.strField(input, "command") orelse return tools.missingArg(gpa, "command");+ var it = std.mem.tokenizeAny(u8, cmd, " \t");+ const sub = it.next() orelse return .{+ .text = try gpa.dupe(u8, "usage: codedb <command> — context <task> · around <name> · callpath A B · list_dir <path> · status"),+ .is_error = true,+ };+ if (std.mem.eql(u8, sub, "list_dir")) return list_dir.exec(ctx, it.rest());+ if (std.mem.eql(u8, sub, "status")) return codedb_health.exec(ctx);+ if (std.mem.eql(u8, sub, "around") or std.mem.eql(u8, sub, "explain")) return codedb_around.execAround(ctx, it.rest());+ if (std.mem.eql(u8, sub, "path")) return codedb_around.execPath(ctx, it.rest());+ if (!allowed(sub)) return .{+ .text = try std.fmt.allocPrint(gpa, "codedb command '{s}' is not allowed here — advertised: context <task> · around <name> · callpath A B · list_dir <path> · status", .{sub}),+ .is_error = true,+ };++ if (isPathSub(sub)) {+ if (firstPathArg(it.rest())) |path| {+ if (!harness_policy.confinedPath(path) or !harness_policy.noSymlinkEscape(io, path, ctx.agent_cwd))+ return tools.outsideCwd(gpa, path);+ }+ }+ if (std.mem.eql(u8, sub, "glob")) {+ if (firstPathArg(it.rest())) |pat| {+ if (globEscapes(pat)) return tools.outsideCwd(gpa, pat);+ }+ }++ var argv: std.ArrayList([]const u8) = .empty;+ defer argv.deinit(gpa);+ try argv.append(gpa, "codedb");+ try argv.append(gpa, sub);+ var rest = std.mem.tokenizeAny(u8, it.rest(), " \t");+ while (rest.next()) |tok| try argv.append(gpa, tok);++ const run = jobs.runCappedWithOptions(gpa, io, argv.items, 512 * 1024, 4096, deadline_ms, jobs.toolRunOptions(ctx.agent_cwd)) catch |e| switch (e) {+ error.FileNotFound => return .{+ .text = try gpa.dupe(u8, "codedb isn't installed — it's open source at github.com/justrach/codedb; install it, then run `codedb` once in the repo to index it. Folder listing still works: codedb list_dir ."),+ .is_error = true,+ },+ else => return tools.failure(gpa, e),+ };+ gpa.free(run.stderr);+ const text = run.stdout;+ if (run.timed_out) {+ defer gpa.free(text);+ return .{+ .text = try std.fmt.allocPrint(gpa, "codedb {s} timed out after {d}s and was killed — narrow the query, or run it through bash if it really needs that long", .{ sub, deadline_ms / 1000 }),+ .is_error = true,+ };+ }+ if (text.len == 0) {+ defer gpa.free(text);+ return .{ .text = try gpa.dupe(u8, "(codedb returned nothing — try `codedb status` or `codedb tree` to confirm the repo is indexed, or refine the query)") };+ }+ return .{ .text = text };+}++/// Opt-in exploratory read via `codedb read <path> [-L a-b] --compact`. Lossy+/// view for reasoning only; returns null on any codedb failure so the caller+/// falls back to the native byte-exact read (#66).+pub fn compactRead(gpa: Allocator, io: Io, path: []const u8, start: ?i64, end: ?i64) !?ToolOutput {+ var argv: std.ArrayList([]const u8) = .empty;+ defer argv.deinit(gpa);+ var lbuf: [48]u8 = undefined;+ try argv.append(gpa, "codedb");+ try argv.append(gpa, "read");+ try argv.append(gpa, path);+ if (start != null and end != null and start.? >= 1 and end.? >= start.?) {+ try argv.append(gpa, "-L");+ try argv.append(gpa, std.fmt.bufPrint(&lbuf, "{d}-{d}", .{ start.?, end.? }) catch return null);+ }+ try argv.append(gpa, "--compact");+ const run = jobs.runCapped(gpa, io, argv.items, tools.codedb_result_cap, 4096, 0) catch return null;+ defer gpa.free(run.stdout);+ defer gpa.free(run.stderr);+ const ok = switch (run.term) {+ .exited => |c| c == 0,+ else => false,+ };+ if (!ok or run.stdout.len == 0) return null;+ return ToolOutput{ .text = try std.fmt.allocPrint(gpa, "{s}\n[compact view — comments/blank lines stripped, line numbers shown; re-read WITHOUT compact before building an edit_file old_string]", .{run.stdout}) };+}++pub fn maybeCompactRead(ctx: ToolCtx, path: []const u8, start: ?i64, end: ?i64) !?ToolOutput {+ if (ctx.agent_cwd != null) return null;+ if (main_mod.g_codedb_present == null) main_mod.g_codedb_present = @import("skills.zig").binOnPath(ctx.io, "codedb");+ if (main_mod.g_codedb_present != true) return null;+ if (!hooks.codedbFileIndexed(ctx.io, ctx.gpa, path)) return null;+ return compactRead(ctx.gpa, ctx.io, path, start, end);+}++test "firstPathArg skips flags" {+ try std.testing.expectEqualStrings("src/main.zig", firstPathArg("-L 1-10 src/main.zig").?);+ try std.testing.expectEqualStrings("src/a.zig", firstPathArg("src/a.zig --compact").?);+ try std.testing.expect(firstPathArg("--compact") == null);+}++test "globEscapes rejects parent and absolute patterns" {+ try std.testing.expect(globEscapes("/etc/*"));+ try std.testing.expect(globEscapes("../**"));+ try std.testing.expect(globEscapes("foo/../bar"));+ try std.testing.expect(!globEscapes("**/*.zig"));+ try std.testing.expect(!globEscapes("src/*"));+}++test "allowed subcommands include list_dir and status, not update" {+ try std.testing.expect(allowed("list_dir"));+ try std.testing.expect(allowed("status"));+ try std.testing.expect(allowed("search"));+ try std.testing.expect(allowed("callpath"));+ try std.testing.expect(allowed("around"));+ try std.testing.expect(!allowed("update"));+ try std.testing.expect(!allowed("nuke"));+ try std.testing.expect(!allowed("mcp"));+}++test "advertised surface is the one-shots, hop verbs stay callable" {+ const advertised = advertised_subs;+ try std.testing.expectEqual(@as(usize, 5), advertised.len);+ for (advertised) |s| try std.testing.expect(allowed(s));+ try std.testing.expect(allowed("search"));+ try std.testing.expect(allowed("outline"));+ try std.testing.expect(allowed("read"));+ for (advertised) |s| {+ try std.testing.expect(!std.mem.eql(u8, s, "search"));+ try std.testing.expect(!std.mem.eql(u8, s, "outline"));+ try std.testing.expect(!std.mem.eql(u8, s, "read"));+ }+}diff --git a/src/codedb_health.zig b/src/codedb_health.zignew file mode 100644index 00000000..7f0a2904--- /dev/null+++ b/src/codedb_health.zig@@ -0,0 +1,92 @@+//! Snapshot health for the native codedb tool.+//!+//! The index lives in `codedb.snapshot` (gitignored, built by the codedb+//! binary). Graff never writes it. `status` reports whether it is present+//! so a model is not stuck between empty `search` and guessing `tree`.+//! `list_dir` does not need the snapshot — it walks the live tree.++const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;++const tools = @import("tools.zig");+const no_local_tools = @import("no_local_tools.zig");++pub const snapshot_name = "codedb.snapshot";++pub const Snapshot = struct {+ present: bool,+ bytes: u64 = 0,+};++pub fn probe(io: Io, cwd: []const u8) Snapshot {+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const path = if (cwd.len == 0 or std.mem.eql(u8, cwd, "."))+ snapshot_name+ else+ std.fmt.bufPrint(&buf, "{s}/{s}", .{ cwd, snapshot_name }) catch return .{ .present = false };+ const st = Io.Dir.cwd().statFile(io, path, .{}) catch return .{ .present = false };+ if (st.kind != .file) return .{ .present = false };+ return .{ .present = true, .bytes = st.size };+}++pub fn render(gpa: Allocator, snap: Snapshot) ![]u8 {+ if (snap.present) {+ return std.fmt.allocPrint(gpa, "codedb.snapshot present ({d} bytes). Prefer one-shot queries on this index: context <task>, around <name>, callpath A B. Folder listing does not need it: codedb list_dir <path>.", .{snap.bytes});+ }+ return gpa.dupe(u8, "codedb index missing — no codedb.snapshot in this cwd. Run `codedb` once in the repo to build it. Folder listing still works without an index: codedb list_dir .");+}++pub fn exec(ctx: tools.ToolCtx) !tools.ToolOutput {+ const cwd = ctx.agent_cwd orelse ".";+ const text = try render(ctx.gpa, probe(ctx.io, cwd));+ return .{ .text = text };+}++/// One-line prompt segment when local tools are on and the snapshot is gone.+/// Null when the index is present or `--no-local-tools` removed codedb —+/// repo_map already orients the tree, and a present index needs no nag.+pub fn segment(io: Io, _: Allocator) ?[]const u8 {+ if (no_local_tools.enabled) return null;+ if (probe(io, ".").present) return null;+ return "\n\nCodedb index: no codedb.snapshot here. `codedb search`/`symbol` need `codedb` run once to index. Folder listing works anyway: codedb list_dir .";+}++test "probe: missing snapshot" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const n = try tmp.dir.realPath(io, &buf);+ const snap = probe(io, buf[0..n]);+ try std.testing.expect(!snap.present);+}++test "probe: present snapshot reports size" {+ const io = std.testing.io;+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ tmp.dir.writeFile(io, .{ .sub_path = snapshot_name, .data = "abcd" }) catch unreachable;+ var buf: [std.fs.max_path_bytes]u8 = undefined;+ const n = try tmp.dir.realPath(io, &buf);+ const snap = probe(io, buf[0..n]);+ try std.testing.expect(snap.present);+ try std.testing.expectEqual(@as(u64, 4), snap.bytes);+}++test "render names list_dir in both states" {+ const missing = try render(std.testing.allocator, .{ .present = false });+ defer std.testing.allocator.free(missing);+ try std.testing.expect(std.mem.indexOf(u8, missing, "list_dir") != null);+ const present = try render(std.testing.allocator, .{ .present = true, .bytes = 12 });+ defer std.testing.allocator.free(present);+ try std.testing.expect(std.mem.indexOf(u8, present, "12 bytes") != null);+ try std.testing.expect(std.mem.indexOf(u8, present, "list_dir") != null);+}++test "segment is silent when no-local-tools is on" {+ const saved = no_local_tools.enabled;+ defer no_local_tools.enabled = saved;+ no_local_tools.enabled = true;+ try std.testing.expect(segment(std.testing.io, std.testing.allocator) == null);+}diff --git a/src/exec.zig b/src/exec.zigindex 7cb2a92c..37bb43d0 100644--- a/src/exec.zig+++ b/src/exec.zig@@ -30,7 +30,6 @@ const rawFetch = tools.rawFetch;const bash_stdout_cap = tools.bash_stdout_cap;const bash_stderr_cap = tools.bash_stderr_cap;const webfetch_cap = tools.webfetch_cap;-const codedb_result_cap = tools.codedb_result_cap;const subagent = @import("subagent.zig");const execSubagent = subagent.execSubagent;@@ -57,7 +56,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+const codedb_exec = @import("codedb_exec.zig"); // native codedb dispatch (list_dir / status / one-shots)// #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");@@ -96,12 +95,6 @@ test "isSshCommand: bare and pathed ssh, not scp or substrings" {try std.testing.expect(!isSshCommand(""));}-/// Wall-clock ceiling for one `codedb` query (#198). Every allowed subcommand-/// is a read that normally answers in seconds; a query that has not returned-/// in a minute is stuck, and before this it stayed stuck forever — the tool-/// blocked on EOF with no deadline at all.-const codedb_deadline_ms: u64 = 60 * 1000;-fn learningArgv(argv: *[10][]const u8, exe_path: []const u8, contribute: bool) usize {var argc: usize = 0;for ([_][]const u8{ exe_path, "--learning-privacy", if (contribute) "aggregate" else "local", "learn", "run" }) |arg| {@@ -407,11 +400,8 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {// #276: skipped entirely for a worktree-isolated agent — codedb's index is// built over the main checkout, not the scratch worktree, so a compact// read there could show stale or altogether wrong content.- if (want_compact and ctx.agent_cwd == null) {- if (main_mod.g_codedb_present == null) main_mod.g_codedb_present = skills.binOnPath(io, "codedb");- if (main_mod.g_codedb_present == true and hooks.codedbFileIndexed(io, gpa, path)) {- if (try codedbCompactRead(gpa, io, path, start_line, end_line)) |out| return out;- }+ if (want_compact) {+ if (try codedb_exec.maybeCompactRead(ctx, path, start_line, end_line)) |out| return out;}// #276 P0-1: resolve under the agent's isolated worktree when set —// path itself stays relative (that's the agent's own view, used in@@ -455,51 +445,7 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {},};}- if (std.mem.eql(u8, call.name, "codedb")) {- 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).- const ok_subs = [_][]const u8{ "search", "symbol", "callers", "find", "outline", "read", "tree", "context", "word", "deps", "glob", "ls", "file", "hot" };- var allowed = false;- 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, 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 {};- argv.append(gpa, sub) catch {};- while (it.next()) |tok| argv.append(gpa, tok) catch {};- // #198: this used to spawn by hand and block until EOF — no deadline, no- // process group, no Esc check — which is how abandoned sessions ended up- // owning dozens of `codedb search` children still asleep days later. The- // capped runner owns the group and tears it down on Esc or the deadline.- const run = runCappedWithOptions(gpa, io, argv.items, 512 * 1024, 4096, codedb_deadline_ms, toolRunOptions(null)) catch |e| switch (e) {- error.FileNotFound => return .{ .text = try gpa.dupe(u8, "codedb isn't installed — it's open source at github.com/justrach/codedb; install it, then run `codedb` once in the repo to index it"), .is_error = true },- else => return failure(gpa, e),- };- gpa.free(run.stderr);- const text = run.stdout;- if (run.timed_out) {- defer gpa.free(text);- return .{ .text = try std.fmt.allocPrint(gpa, "codedb {s} timed out after {d}s and was killed — narrow the query, or run it through bash if it really needs that long", .{ sub, codedb_deadline_ms / 1000 }), .is_error = true };- }- if (text.len == 0) {- defer gpa.free(text);- return .{ .text = try gpa.dupe(u8, "(codedb returned nothing — try `codedb tree` to confirm the repo is indexed, or refine the query)") };- }- // #440: this used to truncate anything past 64 KB, because an unbounded- // `read <big file>` once dumped 500KB into a subagent's context and- // ballooned it to 160k tokens. The guard was right and its method was- // destructive: the same 500KB now becomes a handle at tool time, so the- // context is bounded harder than it ever was here AND the bytes survive- // for a targeted read of the part that mattered.- return .{ .text = text };- }+ if (std.mem.eql(u8, call.name, "codedb")) return codedb_exec.exec(ctx, input);// #337: the read/splice/write/VERIFY path lives in edit_verify.zig, where// the post-edit check sits ON the success path — a write that did not land// can no longer be reported as `replaced N occurrence(s)`.@@ -553,32 +499,6 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {return .{ .text = try std.fmt.allocPrint(gpa, "unknown tool: {s}", .{call.name}), .is_error = true };}-/// Opt-in exploratory read via `codedb read <path> [-L a-b] --compact`. Lossy view-/// for reasoning only; returns null on any codedb failure so the caller falls back-/// to the native byte-exact read (#66).-fn codedbCompactRead(gpa: Allocator, io: Io, path: []const u8, start: ?i64, end: ?i64) !?ToolOutput {- var argv: std.ArrayList([]const u8) = .empty;- defer argv.deinit(gpa);- var lbuf: [48]u8 = undefined;- try argv.append(gpa, "codedb");- try argv.append(gpa, "read");- try argv.append(gpa, path);- if (start != null and end != null and start.? >= 1 and end.? >= start.?) {- try argv.append(gpa, "-L");- try argv.append(gpa, std.fmt.bufPrint(&lbuf, "{d}-{d}", .{ start.?, end.? }) catch return null);- }- try argv.append(gpa, "--compact");- const run = runCapped(gpa, io, argv.items, codedb_result_cap, 4096, 0) catch return null;- defer gpa.free(run.stdout);- defer gpa.free(run.stderr);- const ok = switch (run.term) {- .exited => |c| c == 0,- else => false,- };- if (!ok or run.stdout.len == 0) return null;- return ToolOutput{ .text = try std.fmt.allocPrint(gpa, "{s}\n[compact view — comments/blank lines stripped, line numbers shown; re-read WITHOUT compact before building an edit_file old_string]", .{run.stdout}) };-}-test "internal learning respects the parent privacy ceiling" {var argv: [10][]const u8 = undefined;var len = learningArgv(&argv, "graff", false);@@ -591,4 +511,8 @@ test { // main.zig is at the 600-line cap; exec.zig is these modules' importer,_ = exec_bash_stream;_ = @import("codedbpro_report.zig");_ = @import("tool_balance.zig");+ _ = @import("codedb_exec.zig");+ _ = @import("codedb_around.zig");+ _ = @import("codedb_health.zig");+ _ = @import("list_dir.zig");}diff --git a/src/prompt_snapshot_tests.zig b/src/prompt_snapshot_tests.zigindex 8fe68050..b439b270 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. 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+ \\and structural) over bash grep/find/ls. The codedb commands are context <task>, around <name>, callpath A B, list_dir <path>, and status — one call, not a chain. List a folder with codedb list_dir <path> (in-process; no index required). 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 f1fd6e37..92d363e7 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. 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+ \\and structural) over bash grep/find/ls. The codedb commands are context <task>, around <name>, callpath A B, list_dir <path>, and status — one call, not a chain. List a folder with codedb list_dir <path> (in-process; no index required). 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/prompts.zig b/src/prompts.zigindex ef3df401..14f74ac5 100644--- a/src/prompts.zig+++ b/src/prompts.zig@@ -275,7 +275,7 @@ pub const ultracode_system_note =\\\\ULTRACODE MODE: use the workflow tool for coding tasks. Tell\\code-exploration subagents to go through the repo with the codedb tool- \\(search / symbol / callers / outline / context) before reaching for+ \\(context / around / callpath / list_dir) before reaching for\\bash grep — it is indexed and structural.\\\\diff --git a/src/schema.zig b/src/schema.zigindex 59544b0a..fd1be09d 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 | 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.",+ .desc = "Indexed code nav (github.com/justrach/codedb). ONE command — not a hop chain: context <task> · around <name> · callpath A B · list_dir <path> · status. Prefer over bash grep/find/ls. list_dir is in-process (gitignore, PathConfine; no binary). status reports codedb.snapshot. Paths stay in the cwd.",.schema =- \\{"type": "object", "properties": {"command": {"type": "string", "description": "codedb subcommand + args, e.g. \"search parseHeader\", \"list_dir src\", \"symbol buildBody --body\""}}, "required": ["command"]}+ \\{"type": "object", "properties": {"command": {"type": "string", "description": "One of: \"context how does auth work\", \"around codedbGuard\", \"callpath exec codedbGuard\", \"list_dir src\", \"status\"."}}, "required": ["command"]},},.{ .name = result_read.tool_name, .desc = result_read.tool_desc, .schema = result_read.tool_schema },diff --git a/src/shapes.zig b/src/shapes.zigindex 9782be0d..7fb45556 100644--- a/src/shapes.zig+++ b/src/shapes.zig@@ -399,7 +399,7 @@ const ultracode_explicit_head =\\this turn into multi-agent orchestration. The workflow tool is\\available for it — available, not mandatory.\\Tell code-exploration subagents to go through the repo with the- \\codedb tool (search / symbol / callers / outline / context) before+ \\codedb tool (context / around / callpath / list_dir) before\\reaching for bash grep — it is indexed and structural.\\Escalate to the smallest rung that fits: work solo for a task scoped\\to 1-2 known files; spawn ONE scout when exploration would flood your@@ -425,8 +425,8 @@ const ultracode_persistent_note =\\prompt already has the shape catalog; instantiate one of those shapes\\rather than freeforming a structure. Below that bar, do the work\\yourself: 1-2 known files is solo work. Tell code-exploration- \\subagents to go through the repo with the codedb tool (search /- \\symbol / callers / outline / context) before reaching for bash grep —+ \\subagents to go through the repo with the codedb tool (context /+ \\around / callpath / list_dir) before reaching for bash grep —\\it is indexed and structural.];diff --git a/src/skills.zig b/src/skills.zigindex 3b476d6b..ae0c1574 100644--- a/src/skills.zig+++ b/src/skills.zig@@ -73,11 +73,11 @@ const McpNote = struct { server: []const u8, note: []const u8 };pub const mcp_notes = [_]McpNote{.{.server = "codedbpro",- .note = "The codedb-pro MCP server is connected (mcp__codedbpro__* tools). SEARCH ORDER: the native codedb tool is free and indexed — always try it first for code search (search/symbol/callers/outline/find); reach for mcp__codedbpro__faster_search or meta_search only when codedb can't answer (raw literal/regex content matches, fuzzy queries, non-indexed files) — codedb-pro is metered. Prefer mcp__codedbpro__read (mode=outline first, then symbol) over read_file for navigating large code files, and mcp__codedbpro__batch to run several independent reads/searches/edits in one round-trip. Keep edits on the native edit_file/write_file tools (/rewind-tracked; the cwd and explicit-external-target rules above apply). These tools are accelerators, not requirements: if an mcp__codedbpro__ call fails, fall back to read_file/codedb/bash and continue.",+ .note = "The codedb-pro MCP server is connected (mcp__codedbpro__* tools). SEARCH ORDER: the native codedb tool is free and indexed — always try it first (context/around/callpath/list_dir/status); reach for mcp__codedbpro__faster_search or meta_search only when codedb can't answer (raw literal/regex content matches, fuzzy queries, non-indexed files) — codedb-pro is metered. Prefer mcp__codedbpro__read (mode=outline first, then symbol) over read_file for navigating large code files, and mcp__codedbpro__batch to run several independent reads/searches/edits in one round-trip. Keep edits on the native edit_file/write_file tools (/rewind-tracked; the cwd and explicit-external-target rules above apply). These tools are accelerators, not requirements: if an mcp__codedbpro__ call fails, fall back to read_file/codedb/bash and continue.",},.{.server = "muonry",- .note = "The muonry MCP server is connected (mcp__muonry__* tools). SEARCH ORDER: the native codedb tool is free and indexed — always try it first for code search (search/symbol/callers/outline/find); use mcp__muonry__search or faster_search only when codedb can't answer (raw literal/regex content matches, non-code or non-indexed files) — muonry is metered. Prefer mcp__muonry__read (mode=outline first, then symbol) over read_file for navigating large code files, and mcp__muonry__batch to run several independent reads/searches/edits in one round-trip. Keep edits on the native edit_file/write_file tools (/rewind-tracked; the cwd and explicit-external-target rules above apply). These tools are accelerators, not requirements: if an mcp__muonry__ call fails, fall back to read_file/codedb/bash and continue.",+ .note = "The muonry MCP server is connected (mcp__muonry__* tools). SEARCH ORDER: the native codedb tool is free and indexed — always try it first (context/around/callpath/list_dir/status); use mcp__muonry__search or faster_search only when codedb can't answer (raw literal/regex content matches, non-code or non-indexed files) — muonry is metered. Prefer mcp__muonry__read (mode=outline first, then symbol) over read_file for navigating large code files, and mcp__muonry__batch to run several independent reads/searches/edits in one round-trip. Keep edits on the native edit_file/write_file tools (/rewind-tracked; the cwd and explicit-external-target rules above apply). These tools are accelerators, not requirements: if an mcp__muonry__ call fails, fall back to read_file/codedb/bash and continue.",},.{.server = "smolify",diff --git a/src/tools.zig b/src/tools.zigindex 20593d30..113b3720 100644--- a/src/tools.zig+++ b/src/tools.zig@@ -227,7 +227,7 @@ pub fn codedbGuard(ctx: ToolCtx, call: ToolCall) ?ToolOutput {// codedb result. Let bash through for un-indexed files (issue #54).if (!hooks.codedbFileIndexed(ctx.io, ctx.gpa, src_path)) return null;- const msg = std.fmt.allocPrint(ctx.gpa, "blocked: this repo is codedb-indexed — don't shell out to `{s}` to read or search source. Use the codedb tool (indexed + structural): search <query> · symbol <name> [--body] · callers <name> · deps <path> · outline <path> · read <path> · context <task>. If you genuinely need raw bash here, set GRAFF_NO_CODEDB_GUARD=1.", .{tool}) catch return .{ .text = &.{}, .is_error = true };+ const msg = std.fmt.allocPrint(ctx.gpa, "blocked: this repo is codedb-indexed — don't shell out to `{s}` to read or search source. Use the codedb tool: context <task> · around <name> · callpath A B · list_dir <path> · status. If you genuinely need raw bash here, set GRAFF_NO_CODEDB_GUARD=1.", .{tool}) catch return .{ .text = &.{}, .is_error = true };return .{ .text = msg, .is_error = true };}@@ -286,7 +286,7 @@ pub fn companionRoute(ctx: ToolCtx, call: ToolCall) ?ToolOutput {fn companionNativeFallback(bare: []const u8) []const u8 {if (std.mem.eql(u8, bare, "read")) return "read_file tool";if (std.mem.eql(u8, bare, "search") or std.mem.eql(u8, bare, "faster_search") or std.mem.eql(u8, bare, "meta_search"))- return "codedb tool (search/symbol/callers/outline), or bash grep";+ return "codedb tool (context/around/callpath), or bash grep";if (std.mem.eql(u8, bare, "edit") or std.mem.eql(u8, bare, "patch") or std.mem.eql(u8, bare, "replace"))return "edit_file tool";if (std.mem.eql(u8, bare, "create")) return "write_file tool";