Skip to content

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

Python

licensed codedb-pro: default toolset with enforcement, self-filing issues, daemon edits, /tools balance

Rach Pradhan2946c49a3202
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9f35fae3..b5ca964d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -10,6 +10,40 @@ The release workflow uses a tag's section here as its release notes (a
hand-written `docs/releases/<tag>.md` wins if present), so keeping this file
current is part of cutting a release.
+## v0.0.245 (2026-08-09)
+
+- Licensed codedb-pro is now the default toolset, not an ornament. The license
+ probe at startup pins the server's schemas eager (no per-session
+ `load_tool_schemas` toll that steered models back to the built-ins), the
+ system note makes `mcp__codedbpro__read`/`faster_search`/`batch` the stated
+ defaults for reads and searches, and the built-ins they replace are actually
+ *refused* while the licensed server is healthy: `read_file`, `codedb`, and
+ bash lines leading with `grep`/`rg`/`find` get a refusal naming the
+ replacement (shell searches point at `zigrep` directly; it always skips
+ vendor dirs, so the refusal says when `rg -uu` is the right call instead).
+ Plan mode is exempt (it denies MCP calls outright), and any codedb-pro
+ failure opens the fallback for the rest of the session — being in charge
+ must never leave the model with no working way to read.
+- codedb-pro failures file their own bug reports: the first failure per
+ signature (cap 3/session, root-only) spawns a background subagent that
+ dedupes against open issues and files on justrach/codegraff under the
+ `codedb-pro` label. The harness redacts before anything reaches a model or
+ the issue body — absolute/home paths, credential-looking tokens, URL query
+ strings — keeping only the tool name and the error essence. Unattended
+ sessions (or unapproved `gh`) draft to `.graff/issue-drafts/` instead of
+ publishing without consent.
+- Edits go through the persistent daemon instead of spawning zigpatch per
+ edit: `edit_file` keeps the /rewind snapshot and the on-disk verification,
+ but the byte-splice rides the always-on MCP connection (measured 0.34ms vs
+ 2.37ms per edit on small files — fork/exec was ~85% of the cost). A
+ measured size gate (4 MiB, matching the daemon's cache ceiling) sends big
+ files to the spawn path. Pairs with zigrepper 0.2.21, where the same edits
+ got 2.9x faster still (cache-backed snapshots, light edit loads).
+- `/tools` shows the session's tool balance: codedb-pro read/search/batch vs
+ zigrep vs native fallbacks, gate refusals, and errors. When suite usage
+ skews (8+ calls, one class ≥80%), the nudge rides the tool result so the
+ model hears it — once per dominant class, not on repeat.
+
## v0.0.244 (2026-08-08)
- Co-resident sessions see and coordinate with each other (#469): a per-user
diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.json
index 9536f508..88126691 100644
--- a/scripts/eval/tier1-manifest.json
+++ b/scripts/eval/tier1-manifest.json
@@ -14,7 +14,7 @@
"src/main.zig",
"src/repl.zig"
],
- "test_count_baseline": 1152,
+ "test_count_baseline": 1184,
"test_count_slack": 25,
"required_invariants": [
{
diff --git a/src/codedbpro_report.zig b/src/codedbpro_report.zig
new file mode 100644
index 00000000..419db479
--- /dev/null
+++ b/src/codedbpro_report.zig
@@ -0,0 +1,454 @@
+//! codedb-pro failure reporter: when an mcp__codedbpro__* tool call fails,
+//! dedupe the failure, redact everything an upstream issue does not strictly
+//! need (harness-side, BEFORE any model sees it), and spawn ONE background
+//! subagent to file it on justrach/codegraff under the `codedb-pro` label —
+//! the calling model just falls back to native tools and keeps working.
+//!
+//! Three bounds keep a down server from becoming an issue-filing storm:
+//! root-only (ctx.from_sub short-circuits, so the reporter subagent's own
+//! failures can never re-trigger it), a per-session signature set (the same
+//! tool+error reports once), and a hard spawn cap. The subagent's `gh` calls
+//! still pass the normal tool gate — unattended sessions draft to
+//! .graff/issue-drafts/ instead of publishing without consent.
+
+const std = @import("std");
+const Io = std.Io;
+const Allocator = std.mem.Allocator;
+const tools = @import("tools.zig");
+const util = @import("util.zig");
+const subagent = @import("subagent.zig");
+const mcp_schema_gate = @import("mcp_schema_gate.zig");
+const main_mod = @import("main.zig"); // g_codedbpro_licensed, plan_mode
+const skills = @import("skills.zig"); // mcpServerConnected
+
+pub const server_name = "codedbpro";
+pub const issue_repo = "justrach/codegraff";
+pub const issue_label = "codedb-pro";
+pub const label = "codedb-pro issue reporter";
+
+/// Hard bounds: at most this many reporter spawns a session, and this many
+/// distinct failure signatures remembered for dedupe.
+pub const max_reports: usize = 3;
+const max_seen: usize = 16;
+
+const State = struct {
+ mutex: Io.Mutex = .init,
+ seen: [max_seen]u64 = @splat(0),
+ seen_count: usize = 0,
+ reports: usize = 0,
+};
+
+var g_state: State = .{};
+
+/// The dedupe/cap decision, Io-free so tests need no thread pool (same split
+/// as subagent.zig's admitOneLocked). Callers hold State.mutex.
+fn admitLocked(state: *State, sig: u64) bool {
+ for (state.seen[0..state.seen_count]) |s| if (s == sig) return false;
+ if (state.reports >= max_reports) return false;
+ if (state.seen_count < max_seen) {
+ state.seen[state.seen_count] = sig;
+ state.seen_count += 1;
+ }
+ state.reports += 1;
+ return true;
+}
+
+/// Same tool plus the same redacted error essence = the same report. The
+/// excerpt is already path/token-scrubbed, so the signature never keys on
+/// anything sensitive either.
+fn signature(tool: []const u8, redacted: []const u8) u64 {
+ const essence = util.utf8Prefix(redacted, 128);
+ return std.hash.Wyhash.hash(std.hash.Wyhash.hash(0, tool), essence);
+}
+
+fn tokenish(ch: u8) bool {
+ return std.ascii.isAlphanumeric(ch) or ch == '+' or ch == '/' or ch == '_' or ch == '=' or ch == '-';
+}
+
+/// Harness-side redaction, applied BEFORE the failure text reaches any model
+/// or issue body: absolute/home paths become `<path>`, URLs keep scheme+host
+/// but lose query strings, and long credential-looking runs become
+/// `<redacted>`. Relative `src/foo.zig:42` references survive — they are the
+/// detail an issue actually needs. Output capped at 400 bytes.
+pub fn redact(gpa: Allocator, raw: []const u8) ![]u8 {
+ const capped = util.utf8Prefix(raw, 2048);
+ var out: std.ArrayList(u8) = .empty;
+ errdefer out.deinit(gpa);
+ var it = std.mem.tokenizeAny(u8, capped, " \t\r\n");
+ while (it.next()) |tok| {
+ const replacement: ?[]const u8 = blk: {
+ if (tok.len >= 2 and tok[0] == '/' or std.mem.startsWith(u8, tok, "~/")) break :blk "<path>";
+ if (std.mem.indexOf(u8, tok, "/Users/") != null or std.mem.indexOf(u8, tok, "/home/") != null) break :blk "<path>";
+ if (tok.len >= 24 and std.mem.indexOfAny(u8, tok, "0123456789") != null) {
+ var all = true;
+ for (tok) |ch| if (!tokenish(ch)) {
+ all = false;
+ break;
+ };
+ if (all) break :blk "<redacted>";
+ }
+ break :blk null;
+ };
+ if (out.items.len > 0) try out.append(gpa, ' ');
+ if (replacement) |r| {
+ try out.appendSlice(gpa, r);
+ } else if (std.mem.indexOf(u8, tok, "://") != null) {
+ // URLs keep scheme+host+path but drop the query string, wherever
+ // it sits — wrapping punctuation like "(https://…" is common.
+ const no_query = tok[0 .. std.mem.indexOfScalar(u8, tok, '?') orelse tok.len];
+ try out.appendSlice(gpa, util.utf8Prefix(no_query, 80));
+ } else {
+ try out.appendSlice(gpa, tok);
+ }
+ if (out.items.len >= 400) break;
+ }
+ const kept = util.utf8Prefix(out.items, 400);
+ const result = try gpa.dupe(u8, kept);
+ out.deinit(gpa);
+ return result;
+}
+
+/// The reporter's whole brief. Self-contained (subagents share no context),
+/// minimal on purpose: the user asked for NO detail beyond what an issue
+/// strictly needs, dedupe against existing issues first, and the
+/// `codedb-pro` label on every filing.
+fn buildPrompt(gpa: Allocator, tool: []const u8, redacted_err: []const u8) ![]u8 {
+ var safe_tool: std.ArrayList(u8) = .empty;
+ defer safe_tool.deinit(gpa);
+ for (tool) |ch| try safe_tool.append(gpa, if (std.ascii.isAlphanumeric(ch) or ch == '_' or ch == '-') ch else '_');
+ return std.fmt.allocPrint(gpa,
+ \\A licensed codedb-pro MCP tool call just failed in the parent graff session. Your ONLY job: make sure exactly one GitHub issue exists for it.
+ \\
+ \\Facts (the harness redacted everything else before you saw this — add NO detail beyond these facts; never include absolute paths, usernames, tokens, or file contents):
+ \\- failing tool: {s}
+ \\- redacted error excerpt: {s}
+ \\
+ \\Steps:
+ \\1. Dedupe first: `gh issue list --repo {s} --label {s} --state all --search "{s}" --limit 20`. If an issue already covers this tool + error, stop and report "duplicate: <url>".
+ \\2. Otherwise file it: `gh issue create --repo {s} --label {s} --title "codedb-pro: {s} failed" --body <body>` — the body is ONLY the two facts above, one sentence of context ("automated report from a graff session on a licensed codedb-pro tool failure"), and a note that details were redacted at the source. If gh rejects the label as unknown, run `gh label create {s} --repo {s}` once and retry; if that fails too, file without --label and put "label: {s}" in the body.
+ \\3. If `gh` is unavailable or the call is denied, write the would-be title and body to `.graff/issue-drafts/{s}.md` with write_file and report the draft path.
+ \\
+ \\Keep the issue minimal on purpose — the user wants no detail beyond what is strictly necessary. Report back: the issue URL, "duplicate: <url>", or the draft path.
+ , .{ tool, redacted_err, issue_repo, issue_label, tool, issue_repo, issue_label, tool, issue_label, issue_repo, issue_label, safe_tool.items });
+}
+
+/// The fallback hatch the enforcement half answers to: once ANY codedb-pro
+/// call has failed this session, the native tools it replaced are allowed
+/// again — the pro tools being "in charge" must never leave the model with
+/// no working way to read or search. Atomic: tool calls run on pool threads.
+var g_fallback_open: std.atomic.Value(bool) = .init(false);
+
+pub fn fallbackOpen() bool {
+ return g_fallback_open.load(.acquire);
+}
+
+/// The native tools the licensed pro tools replace. edit_file/write_file are
+/// deliberately NOT here: edits stay native regardless (they are
+/// /rewind-snapshotted; codedb-pro edits bypass /rewind).
+fn replacedNative(name: []const u8) bool {
+ return std.mem.eql(u8, name, "read_file") or std.mem.eql(u8, name, "codedb");
+}
+
+/// A bash call is only intercepted when the search command LEADS the line —
+/// `grep x log` is a replaced search, `curl … | grep x` is output filtering
+/// and stays allowed.
+fn leadingSearchCommand(cmd: []const u8) bool {
+ const trimmed = std.mem.trimStart(u8, cmd, " \t");
+ const end = std.mem.indexOfAny(u8, trimmed, " \t") orelse trimmed.len;
+ const first = trimmed[0..end];
+ return std.mem.eql(u8, first, "grep") or std.mem.eql(u8, first, "rg") or std.mem.eql(u8, first, "find");
+}
+
+/// Whether the licensed-pro enforcement applies to this call right now.
+/// Plan mode denies every MCP call, so blocking the natives there would
+/// leave NO way to read — it is exempt. A disconnected server or an open
+/// fallback likewise stand the gate down.
+fn enforcementActive(ctx: tools.ToolCtx) bool {
+ if (!main_mod.g_codedbpro_licensed or main_mod.plan_mode) return false;
+ if (fallbackOpen()) return false;
+ const reg = ctx.registry orelse return false;
+ return skills.mcpServerConnected(reg.tools, server_name);
+}
+
+/// What a blocked call is pointed at. Shell searches go to zigrep — the
+/// suite's own CLI, run directly via bash, no MCP round trip — when the
+/// binary is on PATH; reads and the codedb tool point at the pro MCP tools.
+fn replacementFor(call_name: []const u8, is_bash_search: bool, zigrep_installed: bool) []const u8 {
+ if (is_bash_search) return if (zigrep_installed)
+ "zigrep — run it directly via bash (e.g. `zigrep PATTERN src/`); it is the suite's search CLI. Caveat: zigrep always skips vendor dirs (node_modules & co) even with --no-ignore — use `rg -uu` for vendor dives"
+ else
+ "mcp__codedbpro__faster_search / meta_search";
+ if (std.mem.eql(u8, call_name, "read_file")) return "mcp__codedbpro__read (mode=outline first, then symbol/lines)";
+ return "mcp__codedbpro__faster_search / meta_search";
+}
+
+/// exec.zig consults this on every tool call: when the licensed pro tools are
+/// in charge, calls to the natives they replaced are refused with a pointer
+/// to the replacement. The refusal is guidance, not a security boundary —
+/// approvals are untouched, and any codedb-pro failure stands it down.
+pub fn nativeRefusal(ctx: tools.ToolCtx, call: tools.ToolCall) ?tools.ToolOutput {
+ if (!enforcementActive(ctx)) return null;
+ const is_bash_search = std.mem.eql(u8, call.name, "bash") and
+ if (tools.strField(call.input, "command")) |cmd| leadingSearchCommand(cmd) else false;
+ if (!is_bash_search and !replacedNative(call.name)) return null;
+ const pro = replacementFor(call.name, is_bash_search, skills.binOnPath(ctx.io, "zigrep"));
+ const text = std.fmt.allocPrint(ctx.gpa, "{s} is blocked while the LICENSED code-intelligence suite is in charge of reads/searches — use {s} instead. If a codedb-pro call fails, the native tools unblock automatically for the rest of the session (and the failure is reported upstream).", .{ call.name, pro }) catch return null;
+ return .{ .text = text, .is_error = true };
+}
+
+/// The splice request body, factored out so a test can pin the contract the
+/// live benchmark validated: op MUST be "str_replace" — without it the
+/// daemon answers "no content provided" (is_error) and every edit silently
+/// falls back to the zigpatch spawn, killing the fast path it bought.
+fn splicePayload(gpa: Allocator, file: []const u8, old: []const u8, new: []const u8, count: usize) ?std.json.Value {
+ var obj: std.json.ObjectMap = .empty;
+ errdefer obj.deinit(gpa);
+ obj.put(gpa, "file", .{ .string = file }) catch return null;
+ obj.put(gpa, "op", .{ .string = "str_replace" }) catch return null;
+ obj.put(gpa, "old_string", .{ .string = old }) catch return null;
+ obj.put(gpa, "new_string", .{ .string = new }) catch return null;
+ obj.put(gpa, "replace_all", .{ .bool = true }) catch return null;
+ obj.put(gpa, "expected", .{ .integer = @intCast(count) }) catch return null;
+ return .{ .object = obj };
+}
+
+/// The edit_file fast path (edit_verify.zig's splice site): a splice over the
+/// PERSISTENT codedb-pro connection skips zigpatch's fork/exec floor — same
+/// atomic write, and the caller still holds the /rewind snapshot and runs
+/// verifyOnDisk, so only the byte-splice is delegated, never the safety.
+/// null = fall through to the zigpatch spawn, then the native write (daemon
+/// absent, unlicensed, refused). `expected: count` makes the daemon itself
+/// enforce the occurrence semantics the caller already computed.
+///
+/// Size gate, measured (median per edit): with the daemon's cache-read fix
+/// (zigrepper handler_edit now snapshots from the stat-validated content
+/// cache instead of a fresh mmap — mmap'ing a just-renamed file cost ~7.6ms
+/// per 3.2MB on macOS), the daemon beats the spawn at every size up to its
+/// 4 MiB cache ceiling: 0.36 vs 2.4ms at 18KB, 2.49 vs 5.00ms at 1 MiB,
+/// 10.7 vs 11.5ms at 3.2MB. Past the ceiling the daemon falls back to the
+/// churned-mmap path and loses, so big files go straight to the spawn.
+pub const daemon_splice_max_bytes: usize = 4 << 20;
+
+pub fn spliceViaDaemon(gpa: Allocator, ctx: tools.ToolCtx, file: []const u8, display_path: []const u8, old: []const u8, new: []const u8, count: usize, file_bytes: usize) ?[]u8 {
+ if (file_bytes > daemon_splice_max_bytes) return null;
+ const reg = ctx.registry orelse return null;
+ if (!skills.mcpServerConnected(reg.tools, server_name)) return null;
+ var payload = splicePayload(gpa, file, old, new, count) orelse return null;
+ defer payload.object.deinit(gpa);
+ const r = reg.call(gpa, "mcp__codedbpro__edit", payload) catch return null;
+ const ok = !r.is_error;
+ gpa.free(r.text);
+ if (!ok) return null;
+ return std.fmt.allocPrint(gpa, "replaced {d} occurrence(s) in {s} (codedb-pro, verified)", .{ count, display_path }) catch null;
+}
+
+/// exec.zig's MCP branch calls this on any failed mcp__codedbpro__* call
+/// (transport error or is_error result). Never blocks the calling turn: the
+/// reporter runs as a background subagent, and every failure path here is
+/// silent by design — the tool result the model got already says it failed.
+pub fn onFailure(ctx: tools.ToolCtx, tool: []const u8, err_text: []const u8) void {
+ if (!std.mem.eql(u8, mcp_schema_gate.serverOf(tool), server_name)) return;
+ // First failure opens the native fallback — dedupe/cap below only govern
+ // ISSUE FILING, never the model's ability to keep working.
+ g_fallback_open.store(true, .release);
+ if (ctx.from_sub) return; // the reporter IS a subagent — never recurse
+ const gpa = ctx.gpa;
+ const redacted = redact(gpa, err_text) catch return;
+ defer gpa.free(redacted);
+ const sig = signature(tool, redacted);
+ g_state.mutex.lockUncancelable(ctx.io);
+ const admitted = admitLocked(&g_state, sig);
+ g_state.mutex.unlock(ctx.io);
+ if (!admitted) return;
+ const prompt = buildPrompt(gpa, tool, redacted) catch return;
+ defer gpa.free(prompt);
+ subagent.spawnBackground(ctx, label, prompt) catch {};
+}
+
+test "redact scrubs absolute paths, home paths and tokens, keeps relative refs" {
+ const a = std.testing.allocator;
+ const out = try redact(a, "open /Users/alice/project/secret.zig failed: token Ab3dEf9012345678ijklMNOP at src/exec.zig:399 (https://api.codedb.pro/v1?key=Ab3dEf9012345678ijklMNOP)");
+ defer a.free(out);
+ try std.testing.expect(std.mem.indexOf(u8, out, "alice") == null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "Ab3dEf9012345678ijklMNOP") == null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "<path>") != null);
+ try std.testing.expect(std.mem.indexOf(u8, out, "src/exec.zig:399") != null); // relative ref is the necessary detail
+ try std.testing.expect(std.mem.indexOf(u8, out, "?key=") == null); // URL query strings are not
+}
+
+test "redact caps its output" {
+ const a = std.testing.allocator;
+ const big = try a.alloc(u8, 5000);
+ defer a.free(big);
+ @memset(big, 'x');
+ const out = try redact(a, big);
+ defer a.free(out);
+ try std.testing.expect(out.len <= 400);
+}
+
+test "admitLocked dedupes one signature and caps the session" {
+ var s: State = .{};
+ try std.testing.expect(admitLocked(&s, 111));
+ try std.testing.expect(!admitLocked(&s, 111)); // same failure twice: one report
+ try std.testing.expect(admitLocked(&s, 222));
+ try std.testing.expect(admitLocked(&s, 333));
+ try std.testing.expect(!admitLocked(&s, 444)); // cap reached
+ try std.testing.expectEqual(@as(usize, max_reports), s.reports);
+}
+
+test "buildPrompt carries repo, label and redacted facts only" {
+ const a = std.testing.allocator;
+ const p = try buildPrompt(a, "mcp__codedbpro__read", "connection refused");
+ defer a.free(p);
+ try std.testing.expect(std.mem.indexOf(u8, p, issue_repo) != null);
+ try std.testing.expect(std.mem.indexOf(u8, p, "--label " ++ issue_label) != null);
+ try std.testing.expect(std.mem.indexOf(u8, p, "mcp__codedbpro__read") != null);
+ try std.testing.expect(std.mem.indexOf(u8, p, "connection refused") != null);
+ try std.testing.expect(std.mem.indexOf(u8, p, "gh issue list") != null); // dedupe-before-file
+}
+
+// ── the enforcement gate ────────────────────────────────────────────────────
+
+const mcp = @import("mcp.zig");
+
+fn gateTestCtx(a: Allocator, reg: *mcp.Registry) tools.ToolCtx {
+ return .{
+ .gpa = a,
+ .io = std.testing.io,
+ .client = undefined,
+ .provider = undefined,
+ .registry = reg,
+ .from_sub = false,
+ .approvals = null,
+ .tracer = null,
+ };
+}
+
+fn licensedRegistry() mcp.Registry {
+ var reg = mcp.Registry.emptyWithOAuthHome(std.testing.allocator, std.testing.io, "");
+ reg.tools = @constCast(&[_]mcp.Tool{.{ .server_index = 0, .original_name = "read", .qualified_name = "mcp__codedbpro__read", .description = "", .input_schema = .null }});
+ return reg;
+}
+
+fn bashCall(a: Allocator, cmd: []const u8) tools.ToolCall {
+ const input = std.fmt.allocPrint(a, "{{\"command\":\"{s}\"}}", .{cmd}) catch unreachable;
+ const parsed = std.json.parseFromSliceLeaky(std.json.Value, a, input, .{}) catch unreachable;
+ return .{ .id = "t", .name = "bash", .input = parsed };
+}
+
+fn namedCall(name: []const u8) tools.ToolCall {
+ return .{ .id = "t", .name = name, .input = .null };
+}
+
+test "replacementFor: shell searches point at zigrep directly, reads at the pro MCP tools" {
+ try std.testing.expect(std.mem.indexOf(u8, replacementFor("bash", true, true), "zigrep") != null);
+ try std.testing.expect(std.mem.indexOf(u8, replacementFor("bash", true, false), "mcp__codedbpro__faster_search") != null);
+ try std.testing.expect(std.mem.indexOf(u8, replacementFor("read_file", false, true), "mcp__codedbpro__read") != null);
+ try std.testing.expect(std.mem.indexOf(u8, replacementFor("codedb", false, true), "mcp__codedbpro__faster_search") != null);
+}
+
+test "nativeRefusal: licensed pro tools block the natives they replaced" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var reg = licensedRegistry();
+ const ctx = gateTestCtx(a, &reg);
+ const saved_licensed = main_mod.g_codedbpro_licensed;
+ const saved_plan = main_mod.plan_mode;
+ const saved_fallback = fallbackOpen();
+ defer {
+ main_mod.g_codedbpro_licensed = saved_licensed;
+ main_mod.plan_mode = saved_plan;
+ g_fallback_open.store(saved_fallback, .release);
+ }
+ main_mod.g_codedbpro_licensed = true;
+ main_mod.plan_mode = false;
+ g_fallback_open.store(false, .release);
+
+ try std.testing.expect(nativeRefusal(ctx, namedCall("read_file")) != null);
+ try std.testing.expect(nativeRefusal(ctx, namedCall("codedb")) != null);
+ try std.testing.expect(nativeRefusal(ctx, bashCall(a, "find . -name '*.zig'")) != null);
+ try std.testing.expect(nativeRefusal(ctx, bashCall(a, "rg TODO src")) != null);
+ // Untouched: edits stay native, non-search bash stays open, a piped grep
+ // filters command output rather than searching the tree.
+ try std.testing.expect(nativeRefusal(ctx, namedCall("edit_file")) == null);
+ try std.testing.expect(nativeRefusal(ctx, bashCall(a, "git status")) == null);
+ try std.testing.expect(nativeRefusal(ctx, bashCall(a, "curl -s x | grep err")) == null);
+}
+
+test "nativeRefusal stands down: unlicensed, plan mode, fallback open, server gone" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var reg = licensedRegistry();
+ const ctx = gateTestCtx(a, &reg);
+ const saved_licensed = main_mod.g_codedbpro_licensed;
+ const saved_plan = main_mod.plan_mode;
+ const saved_fallback = fallbackOpen();
+ defer {
+ main_mod.g_codedbpro_licensed = saved_licensed;
+ main_mod.plan_mode = saved_plan;
+ g_fallback_open.store(saved_fallback, .release);
+ }
+ const call = namedCall("read_file");
+
+ main_mod.g_codedbpro_licensed = false; // unlicensed: conservative note, no gate
+ main_mod.plan_mode = false;
+ g_fallback_open.store(false, .release);
+ try std.testing.expect(nativeRefusal(ctx, call) == null);
+
+ main_mod.g_codedbpro_licensed = true;
+ main_mod.plan_mode = true; // plan mode denies MCP — natives are the only readers
+ try std.testing.expect(nativeRefusal(ctx, call) == null);
+
+ main_mod.plan_mode = false;
+ g_fallback_open.store(true, .release); // a pro failure opened the fallback
+ try std.testing.expect(nativeRefusal(ctx, call) == null);
+
+ g_fallback_open.store(false, .release);
+ var empty = mcp.Registry.emptyWithOAuthHome(std.testing.allocator, std.testing.io, "");
+ try std.testing.expect(nativeRefusal(gateTestCtx(a, &empty), call) == null); // server gone
+}
+
+test "splicePayload pins the daemon contract (op str_replace, replace_all, expected)" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var payload = splicePayload(a, "/tmp/x", "old", "new", 2) orelse return error.TestExpectedPayload;
+ defer payload.object.deinit(a);
+ const obj = payload.object;
+ try std.testing.expectEqualStrings("str_replace", obj.get("op").?.string); // missing op = daemon rejects, fast path never fires
+ try std.testing.expectEqualStrings("old", obj.get("old_string").?.string);
+ try std.testing.expectEqualStrings("new", obj.get("new_string").?.string);
+ try std.testing.expect(obj.get("replace_all").?.bool);
+ try std.testing.expectEqual(@as(i64, 2), obj.get("expected").?.integer);
+}
+
+test "spliceViaDaemon stands down cleanly: no registry, no connected codedbpro" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ var client: std.http.Client = undefined;
+ const no_reg: tools.ToolCtx = .{ .gpa = a, .io = std.testing.io, .client = &client, .provider = undefined, .registry = null, .from_sub = false, .approvals = null, .tracer = null };
+ try std.testing.expect(spliceViaDaemon(a, no_reg, "/tmp/x", "x", "o", "n", 1, 100) == null);
+ var empty = mcp.Registry.emptyWithOAuthHome(a, std.testing.io, "");
+ const no_pro = tools.ToolCtx{ .gpa = a, .io = std.testing.io, .client = &client, .provider = undefined, .registry = &empty, .from_sub = false, .approvals = null, .tracer = null };
+ try std.testing.expect(spliceViaDaemon(a, no_pro, "/tmp/x", "x", "o", "n", 1, 100) == null); // never reaches reg.call
+ // The measured size gate: past it, big files go straight to the spawn.
+ try std.testing.expect(spliceViaDaemon(a, no_pro, "/tmp/x", "x", "o", "n", 1, daemon_splice_max_bytes + 1) == null);
+}
+
+test "onFailure opens the native fallback even from a subagent (no spawn, no recurse)" {
+ const saved_fallback = fallbackOpen();
+ defer g_fallback_open.store(saved_fallback, .release);
+ g_fallback_open.store(false, .release);
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ var reg = licensedRegistry();
+ var ctx = gateTestCtx(arena_state.allocator(), &reg);
+ ctx.from_sub = true; // returns before the spawn path, which tests must not hit
+ onFailure(ctx, "mcp__codedbpro__read", "connection refused");
+ try std.testing.expect(fallbackOpen());
+ onFailure(ctx, "mcp__deepwiki__ask_question", "boom"); // not ours: no effect
+ try std.testing.expect(fallbackOpen());
+}
diff --git a/src/command_catalog.zig b/src/command_catalog.zig
index ceec0977..3969f2ab 100644
--- a/src/command_catalog.zig
+++ b/src/command_catalog.zig
@@ -66,6 +66,7 @@ pub const commands = [_]Item{
.{ .name = "/todo", .desc = "show the current task list" },
.{ .name = "/jobs", .desc = "list background jobs" },
.{ .name = "/cost", .desc = "session token usage and cost" },
+ .{ .name = "/tools", .desc = "session tool balance: codedb-pro vs zigrep vs native usage, gate refusals, skew" },
.{ .name = "/animation", .desc = "pick the thinking animation; persists to settings" },
.{ .name = "/theme", .usage = "/theme [name]", .desc = "pick a color theme; /theme off resets to your terminal default; persists" },
.{ .name = "/fleet", .usage = "/fleet [on|off]", .desc = "federated DGM contribution (propose/submit/elite_pull)" },
diff --git a/src/commands_misc.zig b/src/commands_misc.zig
index ae3e6012..24c19057 100644
--- a/src/commands_misc.zig
+++ b/src/commands_misc.zig
@@ -9,6 +9,8 @@ const Value = std.json.Value;
const Allocator = std.mem.Allocator;
const main_mod = @import("main.zig");
+const tool_balance = @import("tool_balance.zig"); // /tools: session tool-class tally
+const codedbpro_report = @import("codedbpro_report.zig"); // /tools: licensed-gate fallback state
const provider_mod = @import("provider.zig");
const agent_mod = @import("agent.zig");
const util = @import("util.zig");
@@ -243,6 +245,13 @@ pub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8,
try out.flush();
return true;
}
+ if (std.mem.eql(u8, line, "/tools")) {
+ var snap = tool_balance.snapshot();
+ const text = try tool_balance.render(arena, &snap, main_mod.g_codedbpro_licensed, codedbpro_report.fallbackOpen());
+ try out.writeAll(text);
+ try out.flush();
+ return true;
+ }
if (std.mem.startsWith(u8, line, "/mcp")) {
const arg = std.mem.trim(u8, line["/mcp".len..], " \t");
const reg = root.registry.?; // always present now
diff --git a/src/edit_verify.zig b/src/edit_verify.zig
index 2ca6c2be..8026d80e 100644
--- a/src/edit_verify.zig
+++ b/src/edit_verify.zig
@@ -28,6 +28,7 @@ const approvals_mod = @import("approvals.zig");
const confinedPath = approvals_mod.confinedPath;
const noSymlinkEscape = approvals_mod.noSymlinkEscape;
const runCapped = @import("jobs.zig").runCapped;
+const codedbpro_report = @import("codedbpro_report.zig"); // persistent-daemon splice fast path
/// Whole-file read ceiling for the splice source (unchanged from exec.zig).
const edit_read_cap: usize = 1024 * 1024;
@@ -237,6 +238,18 @@ pub fn applyEdit(ctx: ToolCtx, path: []const u8, resolved: []const u8, old: []co
if (ctx.snapshots) |snaps| if (!ctx.from_sub) snaps.record(path, .{ .content = data }); // pre-edit content for /rewind
+ // Fastest splice first: the persistent codedb-pro daemon skips
+ // zigpatch's ~2.4ms fork/exec floor (~0.3ms over the pipe, measured).
+ // The /rewind snapshot above already ran and verifyOnDisk still backs
+ // the result — only the byte-splice is delegated. null falls through
+ // to the zigpatch spawn, then the native write.
+ if (codedbpro_report.spliceViaDaemon(gpa, ctx, resolved, path, old, new, count, data.len)) |msg| {
+ preserveMode(io, resolved, prev_stat); // daemon renames a fresh inode into place, same as zigpatch
+ const verdict = verifyOnDisk(gpa, io, resolved, data, replaced, old, new, true);
+ if (verdict != .ok) return .{ .text = try verdictText(gpa, path, verdict, "codedb-pro"), .is_error = true };
+ return .{ .text = msg };
+ }
+
// Premium splice: when the zigrep suite is installed, zigpatch does the
// write — an atomic tmp+rename byte-level --all splice (our count
// checks above already enforce the uniqueness semantics). Any failure,
diff --git a/src/exec.zig b/src/exec.zig
index cc0830b9..9c413ec7 100644
--- a/src/exec.zig
+++ b/src/exec.zig
@@ -15,6 +15,8 @@ const Allocator = std.mem.Allocator;
const main_mod = @import("main.zig");
const util = @import("util.zig");
+const codedbpro_report = @import("codedbpro_report.zig"); // licensed-companion failure → redacted issue filer
+const tool_balance = @import("tool_balance.zig"); // session-wide tool-class tally (/tools)
const ToolCall = tools.ToolCall;
const tools = @import("tools.zig");
@@ -120,7 +122,7 @@ pub fn execTool(ctx: ToolCtx, call: ToolCall) ToolOutput {
// #255: reserved before any gate/dispatch runs so tool_started/
// tool_finished bracket the whole call, including a gate denial below.
const call_id: u64 = if (ctx.tracer) |tr| tr.toolStarted(call.name, call.input) else 0;
- if (noLocalToolsGate(ctx, call) orelse codedbGuard(ctx, call) orelse companionRoute(ctx, call) orelse hookGate(ctx, call)) |blocked| {
+ if (noLocalToolsGate(ctx, call) orelse codedbGuard(ctx, call) orelse companionRoute(ctx, call) orelse hookGate(ctx, call) orelse licensedNativeGate(ctx, call)) |blocked| {
var out = blocked;
out.ms = t0.untilNow(ctx.io, .awake).toMilliseconds();
if (ctx.tracer) |tr| {
@@ -145,10 +147,31 @@ pub fn execTool(ctx: ToolCtx, call: ToolCall) ToolOutput {
tr.toolFinished(call.name, call_id, out.ms, out.is_error, out.text.len);
}
if (ctx.tools_used) |ts| ts.add(ctx.io, ctx.gpa, call.name, out.is_error);
+ // Session-wide class tally (/tools) — and when suite usage NEWLY skews,
+ // the nudge rides this tool result so the model hears it, not just the
+ // user's /tools view. Edge-triggered: a few per session at most. The
+ // superseded out.text is deliberately NOT freed (it can be a static
+ // empty slice; freeing it would corrupt) — a rare small abandonment.
+ if (tool_balance.record(ctx.gpa, call, out.is_error)) |nudge| {
+ defer ctx.gpa.free(nudge);
+ out.text = std.fmt.allocPrint(ctx.gpa, "{s}\n\n[{s}]", .{ out.text, nudge }) catch out.text;
+ }
runPostToolHooks(ctx, call, out);
return out;
}
+/// Licensed codedb-pro in charge: the natives the suite replaced are refused
+/// until a pro failure opens the fallback (plan mode exempt — it denies MCP
+/// outright). Lives in the OUTER gate chain: still downstream of
+/// agent_tool_gate like every gate here, and the refusal path returns before
+/// tool_balance.record, so a blocked native counts as a REFUSAL — /tools
+/// never mistakes a block for native usage.
+fn licensedNativeGate(ctx: ToolCtx, call: ToolCall) ?ToolOutput {
+ const refusal = codedbpro_report.nativeRefusal(ctx, call) orelse return null;
+ tool_balance.recordRefusal();
+ return refusal;
+}
+
/// #330 layer 2: refuse a host-touching built-in even if a provider hallucinates
/// one that was never advertised (layer 1 is schema.zig). FIRST in the guard
/// chain; an `mcp__*` name never matches, so the sandbox proxy keeps working.
@@ -194,7 +217,11 @@ fn execToolInner(ctx: ToolCtx, call: ToolCall) !ToolOutput {
// add one, and never short-circuits an approval check.
if (mcp_schema_gate.blocked(reg.tools, call.name))
return .{ .text = try mcp_schema_gate.refusalText(gpa, call.name), .is_error = true };
- const r = try reg.call(gpa, call.name, call.input);
+ const r = reg.call(gpa, call.name, call.input) catch |err| {
+ codedbpro_report.onFailure(ctx, call.name, @errorName(err));
+ return failure(gpa, err);
+ };
+ if (r.is_error) codedbpro_report.onFailure(ctx, call.name, r.text);
return .{ .text = r.text, .is_error = r.is_error };
}
@@ -519,3 +546,8 @@ test "internal learning respects the parent privacy ceiling" {
len = learningArgv(&argv, "graff", true);
try std.testing.expectEqualSlices([]const u8, &.{ "graff", "--learning-privacy", "aggregate", "learn", "run", "--submit" }, argv[0..len]);
}
+
+test { // main.zig is at the 600-line cap; exec.zig is these modules' importer, so the compiled-in references live here (the reach check diffs the test binary, not which file holds the line)
+ _ = @import("codedbpro_report.zig");
+ _ = @import("tool_balance.zig");
+}
diff --git a/src/skills.zig b/src/skills.zig
index fa522023..84b655b0 100644
--- a/src/skills.zig
+++ b/src/skills.zig
@@ -67,7 +67,7 @@ pub const skills_registry = [_]SkillDef{
/// Edits inside the cwd stay native: edit_file/write_file are
/// /rewind-snapshotted and already splice via zigpatch, whereas codedb-pro
/// edit/patch/replace bypass /rewind. Explicit external targets use gated bash.
-const codedbpro_note_licensed = "The codedb-pro MCP server is connected and LICENSED (mcp__codedbpro__* tools) — prefer it, you are paying for it. Use mcp__codedbpro__read (mode=outline first, then symbol/lines) instead of read_file for navigating code, mcp__codedbpro__faster_search / meta_search for content and fuzzy search (the native codedb tool stays a fine fast path for indexed symbol/outline/callers/find lookups), and mcp__codedbpro__batch to run several independent reads/searches in one round-trip. KEEP EDITS inside the cwd on the native edit_file/write_file tools — they are snapshot-tracked for /rewind and already splice via zigpatch; codedb-pro edit/patch/replace bypass /rewind, so do not route edits through it. An explicitly user-requested external target is the exception: use permission-gated bash with quoted paths and explain that /rewind does not cover it. Whenever an mcp__codedbpro__ call fails, fall back to read_file/codedb/bash.";
+const codedbpro_note_licensed = "The codedb-pro MCP server is connected and LICENSED, and its mcp__codedbpro__* tools ship with FULL schemas already loaded (pinned eager — no load_tool_schemas round trip needed). You are paying for them, so they REPLACE the native read/search defaults: use mcp__codedbpro__read (mode=outline first, then symbol/lines) instead of read_file for navigating code, mcp__codedbpro__faster_search / meta_search instead of the codedb tool and bash grep/find for symbol, content and fuzzy search, and mcp__codedbpro__batch to run several independent reads/searches in one round-trip. The native read_file/codedb (and leading bash grep/rg/find) are BLOCKED while the licensed server is healthy — read/search calls are refused with a pointer to the pro equivalent, shell searches with a pointer to `zigrep` (the suite's own search CLI — run it directly via bash); any codedb-pro failure automatically unblocks the natives for the rest of the session (and is reported upstream, so just fall back and keep working). KEEP EDITS inside the cwd on the native edit_file/write_file tools — they are snapshot-tracked for /rewind and already splice via zigpatch; codedb-pro edit/patch/replace bypass /rewind, so do not route edits through it. An explicitly user-requested external target is the exception: use permission-gated bash with quoted paths and explain that /rewind does not cover it.";
const McpNote = struct { server: []const u8, note: []const u8 };
pub const mcp_notes = [_]McpNote{
diff --git a/src/subagent.zig b/src/subagent.zig
index 2e62dbf9..b2626fc2 100644
--- a/src/subagent.zig
+++ b/src/subagent.zig
@@ -278,6 +278,14 @@ fn spawnSubBackground(ctx: ToolCtx, label: []const u8, prompt: []const u8, sys_o
) };
}
+/// Programmatic fire-and-forget spawn for harness-internal reporters (the
+/// codedbpro failure → issue filer): no tool-call input to parse, no persona,
+/// no pin — the session-default seat in the shared cwd. execSubagent stays
+/// the model-facing path; this never surfaces a ToolOutput to anyone.
+pub fn spawnBackground(ctx: ToolCtx, label: []const u8, prompt: []const u8) !void {
+ _ = try spawnSubBackground(ctx, label, prompt, null, "", .shared_cwd, false, null, null, vision_ask.forPrompt(prompt));
+}
+
/// Pure formatting for agent_output's status line: the "structured
/// completion event" shape (#276 P0-3 design point 3) — running / completed
/// / failed, plus the usage summary, plus the full result once done.
diff --git a/src/tool_balance.zig b/src/tool_balance.zig
new file mode 100644
index 00000000..a15cde79
--- /dev/null
+++ b/src/tool_balance.zig
@@ -0,0 +1,268 @@
+//! Session-wide tool-CLASS tally: how the model's reads/searches actually
+//! split across the licensed codedb-pro tools, zigrep, and the native
+//! fallbacks — plus how often the licensed gate had to refuse a native call.
+//! The per-turn ToolSink (trace.zig) already logs names for the trajectory,
+//! but nothing aggregated by class, so "the model hammered faster_search 40
+//! times and never opened a file outline" was invisible. This is the
+//! aggregate: /tools renders it, and the skew line names a dominant class.
+//!
+//! Counting hooks: exec.zig's central post-call point (every tool call) and
+//! codedbpro_report.nativeRefusal (gate refusals, which never reach a call).
+//! Counters are plain u64s touched through @atomicRmw/@atomicLoad — tool
+//! calls run on pool threads, and a mutex here would invite cancellation
+//! deadlock for a three-instruction critical section.
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+const tools = @import("tools.zig");
+
+pub const Class = enum {
+ pro_read, // mcp__codedbpro__read
+ pro_search, // faster_search / meta_search
+ pro_batch, // batch
+ pro_other, // any other mcp__codedbpro__*
+ zigrep, // leading `zigrep` via bash
+ native_search, // leading grep/rg/find via bash — only runs unlicensed or post-fallback
+ native_read, // read_file / codedb — same
+ other,
+
+ fn label(self: Class) []const u8 {
+ return switch (self) {
+ .pro_read => "read",
+ .pro_search => "search",
+ .pro_batch => "batch",
+ .pro_other => "other",
+ .zigrep => "zigrep",
+ .native_search => "grep/rg/find",
+ .native_read => "read_file/codedb",
+ .other => "other",
+ };
+ }
+};
+
+const class_count = @as(usize, @intFromEnum(Class.other)) + 1; // `other` must stay LAST (std.meta.fields is deprecated in this std)
+var g_counts: [class_count]u64 = @splat(0);
+var g_refused: u64 = 0;
+var g_errors: u64 = 0;
+
+fn bump(counter: *u64) void {
+ _ = @atomicRmw(u64, counter, .Add, 1, .monotonic);
+}
+
+fn load(counter: *const u64) u64 {
+ return @atomicLoad(u64, counter, .monotonic);
+}
+
+fn firstToken(cmd: []const u8) []const u8 {
+ const trimmed = std.mem.trimStart(u8, cmd, " \t");
+ const end = std.mem.indexOfAny(u8, trimmed, " \t") orelse trimmed.len;
+ return trimmed[0..end];
+}
+
+/// The class one tool call belongs to. Bash is inspected by LEADING command
+/// only — a piped `| grep` filters output and stays `other`.
+pub fn classOf(call: tools.ToolCall) Class {
+ const name = call.name;
+ if (std.mem.eql(u8, name, "read_file") or std.mem.eql(u8, name, "codedb")) return .native_read;
+ if (std.mem.eql(u8, name, "bash")) {
+ const cmd = tools.strField(call.input, "command") orelse return .other;
+ const first = firstToken(cmd);
+ if (std.mem.eql(u8, first, "zigrep")) return .zigrep;
+ if (std.mem.eql(u8, first, "grep") or std.mem.eql(u8, first, "rg") or std.mem.eql(u8, first, "find")) return .native_search;
+ return .other;
+ }
+ if (std.mem.eql(u8, name, "mcp__codedbpro__read")) return .pro_read;
+ if (std.mem.eql(u8, name, "mcp__codedbpro__faster_search") or std.mem.eql(u8, name, "mcp__codedbpro__meta_search")) return .pro_search;
+ if (std.mem.eql(u8, name, "mcp__codedbpro__batch")) return .pro_batch;
+ if (std.mem.startsWith(u8, name, "mcp__codedbpro__")) return .pro_other;
+ return .other;
+}
+
+/// Edge-trigger state for the steering nudge: 0 = none/balanced, else the
+/// dominant Class + 1 already nudged this session. The nudge fires once per
+/// dominant class — a model that keeps hammering after being told gets no
+/// repeats, and a shift to a DIFFERENT dominant class re-arms it.
+var g_last_skew: std.atomic.Value(u8) = .init(0);
+
+fn isSuite(class: Class) bool {
+ return switch (class) {
+ .pro_read, .pro_search, .pro_batch, .pro_other, .zigrep => true,
+ else => false,
+ };
+}
+
+/// The dominant suite class when usage is skewed (8+ suite calls, one class
+/// at 80%+), null when balanced or too thin to judge. Alloc-free; record()
+/// only formats a message when this edge-triggers.
+pub fn skewClass(snap: *const Snapshot) ?Class {
+ const total = snap.suiteTotal();
+ if (total < 8) return null;
+ const classes = [_]Class{ .pro_read, .pro_search, .pro_batch, .zigrep };
+ var top: Class = .pro_read;
+ for (classes) |c| if (snap.get(c) > snap.get(top)) {
+ top = c;
+ };
+ if (snap.get(top) * 5 < total * 4) return null;
+ return top;
+}
+
+/// exec.zig's post-call hook. Errors counted apart: a failing dominant tool
+/// is a different story than a preferred one. Returns a gpa-owned steering
+/// nudge when suite usage NEWLY skews (the caller appends it to the tool
+/// result so the model hears it, not just /tools) — null otherwise.
+pub fn record(gpa: Allocator, call: tools.ToolCall, is_error: bool) ?[]u8 {
+ const class = classOf(call);
+ bump(&g_counts[@intFromEnum(class)]);
+ if (is_error) bump(&g_errors);
+ if (!isSuite(class)) return null;
+ var snap = snapshot();
+ const top = skewClass(&snap) orelse {
+ g_last_skew.store(0, .release);
+ return null;
+ };
+ const marker: u8 = @intCast(@intFromEnum(top) + 1);
+ if (g_last_skew.swap(marker, .acq_rel) == marker) return null;
+ return std.fmt.allocPrint(gpa, "tool balance: {d}/{d} suite calls were {s} — read (outline-first), search and batch are all available; balance them", .{ snap.get(top), snap.suiteTotal(), top.label() }) catch null;
+}
+
+/// codedbpro_report.nativeRefusal's hook: a native call the licensed gate
+/// turned away. High counts are the gate working, not a failure — but they
+/// also say the model needed steering.
+pub fn recordRefusal() void {
+ bump(&g_refused);
+}
+
+pub const Snapshot = struct {
+ counts: [class_count]u64 = @splat(0),
+ refused: u64 = 0,
+ errors: u64 = 0,
+
+ pub fn get(self: *const Snapshot, class: Class) u64 {
+ return self.counts[@intFromEnum(class)];
+ }
+
+ /// Every read/search the licensed suite owns: pro tools plus zigrep.
+ pub fn suiteTotal(self: *const Snapshot) u64 {
+ return self.get(.pro_read) + self.get(.pro_search) + self.get(.pro_batch) + self.get(.pro_other) + self.get(.zigrep);
+ }
+};
+
+pub fn snapshot() Snapshot {
+ var snap: Snapshot = .{};
+ inline for (0..class_count) |i| snap.counts[i] = load(&g_counts[i]);
+ snap.refused = load(&g_refused);
+ snap.errors = load(&g_errors);
+ return snap;
+}
+
+/// Test seam: a fresh tally.
+pub fn reset() void {
+ inline for (0..class_count) |i| @atomicStore(u64, &g_counts[i], 0, .monotonic);
+ @atomicStore(u64, &g_refused, 0, .monotonic);
+ @atomicStore(u64, &g_errors, 0, .monotonic);
+ g_last_skew.store(0, .monotonic);
+}
+
+/// The "not overleveraging just one" check for /tools: same rule record()
+/// edge-triggers on, formatted for the report. null when balanced or thin.
+pub fn skewWarning(alloc: Allocator, snap: *const Snapshot) ?[]const u8 {
+ const top = skewClass(snap) orelse return null;
+ return std.fmt.allocPrint(alloc, "skew: {d}/{d} suite calls were {s} — read (outline-first), search and batch are all available; balance them", .{ snap.get(top), snap.suiteTotal(), top.label() }) catch null;
+}
+
+/// The /tools body. `licensed`/`fallback_open` come from codedbpro_report's
+/// gate state so the reader can tell "natives unused because blocked" from
+/// "natives unused because chosen".
+pub fn render(alloc: Allocator, snap: *const Snapshot, licensed: bool, fallback_open: bool) ![]const u8 {
+ var aw: std.Io.Writer.Allocating = .init(alloc);
+ const w = &aw.writer;
+ try w.writeAll("tool balance this session:\n");
+ try w.print(" codedb-pro: read {d} · search {d} · batch {d} · other {d}\n", .{ snap.get(.pro_read), snap.get(.pro_search), snap.get(.pro_batch), snap.get(.pro_other) });
+ try w.print(" zigrep: {d}\n", .{snap.get(.zigrep)});
+ try w.print(" native: read_file/codedb {d} · grep/rg/find {d}\n", .{ snap.get(.native_read), snap.get(.native_search) });
+ if (licensed) try w.print(" gate: {d} blocked native attempt(s) · fallback {s}\n", .{ snap.refused, if (fallback_open) "OPEN (a codedb-pro call failed)" else "closed" });
+ if (snap.errors > 0) try w.print(" errors: {d} failed tool call(s)\n", .{snap.errors});
+ if (skewWarning(alloc, snap)) |warn| try w.print(" {s}\n", .{warn});
+ return alloc.dupe(u8, w.buffered());
+}
+
+test "classOf sorts pro tools, zigrep, shell search and natives" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const bash = struct {
+ fn call(alloc: Allocator, cmd: []const u8) tools.ToolCall {
+ const src = std.fmt.allocPrint(alloc, "{{\"command\":\"{s}\"}}", .{cmd}) catch unreachable;
+ const v = std.json.parseFromSliceLeaky(std.json.Value, alloc, src, .{}) catch unreachable;
+ return .{ .id = "t", .name = "bash", .input = v };
+ }
+ };
+ try std.testing.expectEqual(Class.pro_read, classOf(.{ .id = "t", .name = "mcp__codedbpro__read", .input = .null }));
+ try std.testing.expectEqual(Class.pro_search, classOf(.{ .id = "t", .name = "mcp__codedbpro__meta_search", .input = .null }));
+ try std.testing.expectEqual(Class.pro_batch, classOf(.{ .id = "t", .name = "mcp__codedbpro__batch", .input = .null }));
+ try std.testing.expectEqual(Class.zigrep, classOf(bash.call(a, "zigrep TODO src")));
+ try std.testing.expectEqual(Class.native_search, classOf(bash.call(a, "find . -name '*.zig'")));
+ try std.testing.expectEqual(Class.other, classOf(bash.call(a, "curl -s x | grep err"))); // piped: output filtering
+ try std.testing.expectEqual(Class.native_read, classOf(.{ .id = "t", .name = "read_file", .input = .null }));
+ try std.testing.expectEqual(Class.other, classOf(.{ .id = "t", .name = "edit_file", .input = .null }));
+}
+
+test "record/snapshot/skew: a dominant class is named, balanced usage is quiet" {
+ reset();
+ defer reset();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const search: tools.ToolCall = .{ .id = "t", .name = "mcp__codedbpro__faster_search", .input = .null };
+ for (0..9) |_| _ = record(a, search, false);
+ _ = record(a, .{ .id = "t", .name = "mcp__codedbpro__read", .input = .null }, false);
+ recordRefusal();
+ var snap = snapshot();
+ try std.testing.expectEqual(@as(u64, 10), snap.suiteTotal());
+ try std.testing.expectEqual(@as(u64, 1), snap.refused);
+ const warn = skewWarning(a, &snap) orelse return error.TestExpectedSkew;
+ try std.testing.expect(std.mem.indexOf(u8, warn, "search") != null);
+
+ reset();
+ for (0..3) |_| _ = record(a, search, false);
+ for (0..3) |_| _ = record(a, .{ .id = "t", .name = "mcp__codedbpro__read", .input = .null }, false);
+ for (0..3) |_| _ = record(a, .{ .id = "t", .name = "mcp__codedbpro__batch", .input = .null }, false);
+ var even = snapshot();
+ try std.testing.expect(skewWarning(a, &even) == null);
+ // ...and below the 8-call floor the warning stays out of thin sessions.
+ reset();
+ for (0..5) |_| _ = record(a, search, false);
+ var thin = snapshot();
+ try std.testing.expect(skewWarning(a, &thin) == null);
+}
+
+test "record edge-triggers the steering nudge: once per dominant class" {
+ reset();
+ defer reset();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ const search: tools.ToolCall = .{ .id = "t", .name = "mcp__codedbpro__faster_search", .input = .null };
+ var nudges: usize = 0;
+ for (0..9) |_| if (record(a, search, false)) |_| {
+ nudges += 1;
+ };
+ try std.testing.expectEqual(@as(usize, 1), nudges); // fired exactly once, at the crossing
+ // A non-suite call never nudges.
+ try std.testing.expect(record(a, .{ .id = "t", .name = "edit_file", .input = .null }, false) == null);
+}
+
+test "render shows classes, gate state and skew" {
+ reset();
+ defer reset();
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const a = arena_state.allocator();
+ for (0..9) |_| _ = record(a, .{ .id = "t", .name = "mcp__codedbpro__faster_search", .input = .null }, false);
+ recordRefusal();
+ var snap = snapshot();
+ const text = try render(a, &snap, true, false);
+ try std.testing.expect(std.mem.indexOf(u8, text, "search 9") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "fallback closed") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "skew:") != null);
+}
diff --git a/src/tool_schema_tests.zig b/src/tool_schema_tests.zig
index f30cedfe..72c73b6a 100644
--- a/src/tool_schema_tests.zig
+++ b/src/tool_schema_tests.zig
@@ -280,6 +280,28 @@ test "#416: deferring a real MCP server's schemas cuts the served catalog in hal
try testing.expect(after.len > deferred.len and after.len < eager.len);
}
+test "pinEagerRuntime: a post-configure license probe promotes the server for the first catalog" {
+ var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ gate.reset();
+ gate.g_policy = .{};
+ defer {
+ gate.reset();
+ gate.g_policy = .{};
+ }
+ const tools = try realServerTools(arena);
+ try testing.expect(!gate.pinnedEager("smolify"));
+ gate.pinEagerRuntime(arena, "smolify");
+ try testing.expect(gate.pinnedEager("smolify"));
+ gate.pinEagerRuntime(arena, "smolify"); // a second probe must not grow the list
+ try testing.expectEqual(@as(usize, 1), gate.g_policy.eager.len);
+ // The pin is what isDeferred consults, so the pinned server's tools serve eagerly...
+ for (tools) |t| try testing.expect(!gate.isDeferred(tools, t));
+ // ...and nothing deferred means load_tool_schemas drops out of the catalog too.
+ try testing.expect(!gate.anyDeferred(tools));
+}
+
test "#416: every provider wire format defers identically, and stays valid JSON" {
var arena_state = std.heap.ArenaAllocator.init(testing.allocator);
defer arena_state.deinit();