Skip to content

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

Python

perf(kimi): cut k3 lookup latency ~50% — handle threshold, eager codedb-pro, cache lease, effort routing, stall floor

Rach Pradhan76667e736516
diff --git a/benchmarks/graff-kimi-k3-report.html b/benchmarks/graff-kimi-k3-report.html
new file mode 100644
index 00000000..a4c2464f
--- /dev/null
+++ b/benchmarks/graff-kimi-k3-report.html
@@ -0,0 +1,465 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta name="color-scheme" content="dark light">
+ <title>Graff × Kimi Code CLI — K3 harness benchmark</title>
+ <style>
+ :root {
+ --bg: #07100d;
+ --panel: #0d1915;
+ --panel-raised: #12211b;
+ --line: #21372e;
+ --text: #e5f2ec;
+ --muted: #91aa9e;
+ --accent: #059669;
+ --accent-bright: #34d399;
+ --accent-soft: rgba(5, 150, 105, .15);
+ --kimi: #7c9aff;
+ --kimi-soft: rgba(124, 154, 255, .14);
+ --warn: #f59e0b;
+ --shadow: 0 24px 70px rgba(0, 0, 0, .3);
+ --radius: 20px;
+ }
+
+ * { box-sizing: border-box; }
+ html { scroll-behavior: smooth; }
+
+ body {
+ margin: 0;
+ background:
+ radial-gradient(circle at 10% -10%, rgba(5, 150, 105, .2), transparent 30rem),
+ radial-gradient(circle at 95% 10%, rgba(124, 154, 255, .1), transparent 28rem),
+ var(--bg);
+ color: var(--text);
+ font: 15px/1.6 Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
+ }
+
+ .shell { width: min(1120px, calc(100% - 40px)); margin: 0 auto; padding: 28px 0 80px; }
+
+ .eyebrow {
+ display: inline-flex; align-items: center; gap: 8px;
+ padding: 6px 14px; border: 1px solid var(--line); border-radius: 999px;
+ background: var(--panel); color: var(--muted);
+ font-size: 12px; font-weight: 650; letter-spacing: .08em; text-transform: uppercase;
+ }
+ .eyebrow .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--accent-bright); }
+
+ h1 { font-size: clamp(30px, 5vw, 46px); line-height: 1.08; letter-spacing: -.03em; margin: 18px 0 10px; }
+ h1 .vs { color: var(--muted); font-weight: 500; }
+ .sub { color: var(--muted); max-width: 760px; margin: 0 0 34px; }
+ .sub code { color: var(--accent-bright); }
+
+ .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(230px, 1fr)); gap: 14px; margin-bottom: 40px; }
+ .card {
+ background: linear-gradient(180deg, var(--panel-raised), var(--panel));
+ border: 1px solid var(--line); border-radius: var(--radius);
+ padding: 20px 22px; box-shadow: var(--shadow);
+ }
+ .card .label { color: var(--muted); font-size: 12px; font-weight: 650; letter-spacing: .07em; text-transform: uppercase; }
+ .card .value { font-size: 34px; font-weight: 780; letter-spacing: -.02em; margin-top: 6px; }
+ .card .value small { font-size: 15px; color: var(--muted); font-weight: 600; }
+ .card .note { color: var(--muted); font-size: 12.5px; margin-top: 4px; }
+ .card.graff .value { color: var(--accent-bright); }
+ .card.kimi .value { color: var(--kimi); }
+
+ .panel {
+ background: linear-gradient(180deg, var(--panel-raised), var(--panel));
+ border: 1px solid var(--line); border-radius: var(--radius);
+ padding: 26px 28px; box-shadow: var(--shadow); margin-bottom: 28px;
+ }
+ .panel h2 { margin: 0 0 6px; font-size: 21px; letter-spacing: -.01em; }
+ .panel .hint { color: var(--muted); font-size: 13px; margin: 0 0 20px; }
+
+ .bars { display: grid; gap: 18px; }
+ .bar-row .names { display: flex; justify-content: space-between; font-size: 13px; margin-bottom: 6px; }
+ .bar-row .names .task { font-weight: 700; }
+ .bar-row .names .times { color: var(--muted); font-variant-numeric: tabular-nums; }
+ .track { position: relative; height: 14px; border-radius: 999px; background: rgba(255,255,255,.04); overflow: hidden; margin-bottom: 6px; }
+ .fill { position: absolute; inset: 0 auto 0 0; border-radius: 999px; }
+ .fill.graff { background: linear-gradient(90deg, var(--accent), var(--accent-bright)); }
+ .fill.kimi { background: linear-gradient(90deg, #4f6fd8, var(--kimi)); }
+ .legend { display: flex; gap: 18px; font-size: 12.5px; color: var(--muted); margin-top: 14px; }
+ .legend .sw { display: inline-block; width: 10px; height: 10px; border-radius: 3px; margin-right: 6px; vertical-align: -1px; }
+ .legend .sw.graff { background: var(--accent-bright); }
+ .legend .sw.kimi { background: var(--kimi); }
+
+ table { width: 100%; border-collapse: collapse; font-size: 13.5px; }
+ th, td { text-align: left; padding: 10px 12px; border-bottom: 1px solid var(--line); vertical-align: top; }
+ th { color: var(--muted); font-size: 11.5px; letter-spacing: .07em; text-transform: uppercase; }
+ td.num { font-variant-numeric: tabular-nums; white-space: nowrap; }
+ tr:last-child td { border-bottom: 0; }
+ .pill { display: inline-block; padding: 2px 9px; border-radius: 999px; font-size: 11.5px; font-weight: 700; }
+ .pill.graff { background: var(--accent-soft); color: var(--accent-bright); }
+ .pill.kimi { background: var(--kimi-soft); color: var(--kimi); }
+
+ .grid2 { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 14px; }
+ .mini {
+ background: rgba(255,255,255,.025); border: 1px solid var(--line);
+ border-radius: 14px; padding: 16px 18px;
+ }
+ .mini h3 { margin: 0 0 6px; font-size: 14.5px; }
+ .mini p { margin: 0; color: var(--muted); font-size: 13px; }
+ .mini code { color: var(--accent-bright); font-size: 12px; }
+
+ ul.tight { margin: 0; padding-left: 18px; color: var(--muted); font-size: 13.5px; }
+ ul.tight li { margin-bottom: 7px; }
+ ul.tight code { color: var(--accent-bright); font-size: 12px; }
+
+ .foot { color: var(--muted); font-size: 12.5px; margin-top: 26px; }
+ .foot code { color: var(--accent-bright); }
+ </style>
+</head>
+<body>
+ <div class="shell">
+ <span class="eyebrow"><span class="dot"></span> Harness benchmark · August 11, 2026</span>
+ <h1>Graff <span class="vs">×</span> Kimi Code CLI</h1>
+ <p class="sub">
+ Both harnesses drive the <strong>same model — Moonshot K3</strong> — over the same Kimi Code
+ OAuth subscription, in their real interactive TUIs, on identical read-only tasks against an
+ identical checkout of this repository. What differs is only the harness: tools, prompt
+ assembly, and event loop. Subscription billing means $0 marginal cost on both sides.
+ </p>
+
+ <div class="cards">
+ <div class="card graff">
+ <div class="label">Graff total wall · post-fix</div>
+ <div class="value">130.3<small>s</small></div>
+ <div class="note">best runs: 48.2 + 56.1 + 26.0 · was 260.5s pre-fix (−50%)</div>
+ </div>
+ <div class="card kimi">
+ <div class="label">Kimi Code CLI total wall</div>
+ <div class="value">181.7<small>s</small></div>
+ <div class="note">includes +21s/cell idle-detection pad</div>
+ </div>
+ <div class="card kimi">
+ <div class="label">Kimi true model-turn total</div>
+ <div class="value">117.9<small>s</small></div>
+ <div class="note">from its own wire log (turn.ended durationMs)</div>
+ </div>
+ <div class="card">
+ <div class="label">Answer correctness</div>
+ <div class="value">6 / 6</div>
+ <div class="note">all claims spot-verified against the source</div>
+ </div>
+ <div class="card graff">
+ <div class="label">After the fix · providers</div>
+ <div class="value">26.0<small>s</small></div>
+ <div class="note">was 60.7s pre-fix · kimi 50.4s wall / 29.2s true — graff wins both</div>
+ </div>
+ <div class="card">
+ <div class="label">Cache lease · first call</div>
+ <div class="value">0 → 10<small>k warm</small></div>
+ <div class="note">new sessions start on the warm shared prefix (durable per-project key)</div>
+ </div>
+ </div>
+
+ <div class="panel">
+ <h2>Wall time per task <span style="color:var(--muted); font-size:13px; font-weight:500">— round 2, PRE-FIX</span></h2>
+ <p class="hint">The baseline that motivated the fix. See <strong>Before → after</strong> below for what the shipped threshold change did to these numbers.</p>
+ <div class="bars">
+ <div class="bar-row">
+ <div class="names"><span class="task">runEval — locate &amp; explain a function (false-premise trap)</span><span class="times">graff 117.6s · kimi 61.7s</span></div>
+ <div class="track"><div class="fill graff" style="width:100%"></div></div>
+ <div class="track"><div class="fill kimi" style="width:52.5%"></div></div>
+ </div>
+ <div class="bar-row">
+ <div class="names"><span class="task">permgate — explain the bash permission gate</span><span class="times">graff 82.2s · kimi 69.6s</span></div>
+ <div class="track"><div class="fill graff" style="width:100%"></div></div>
+ <div class="track"><div class="fill kimi" style="width:84.7%"></div></div>
+ </div>
+ <div class="bar-row">
+ <div class="names"><span class="task">providers — enumerate every provider, wire format &amp; auth</span><span class="times">graff 60.7s · kimi 50.4s</span></div>
+ <div class="track"><div class="fill graff" style="width:100%"></div></div>
+ <div class="track"><div class="fill kimi" style="width:83.0%"></div></div>
+ </div>
+ </div>
+ <div class="legend">
+ <span><span class="sw graff"></span>Graff v0.0.245-38 (this repo, fixed build)</span>
+ <span><span class="sw kimi"></span>Kimi Code CLI v0.34.0 (official)</span>
+ </div>
+ </div>
+
+ <div class="panel">
+ <h2>Before → after the threshold fix</h2>
+ <p class="hint">Same model, same high effort, same tasks — the only difference is the 4 KiB → 16 KiB
+ tool-result handle threshold (plus the badge/catalog fixes). After = two fresh runs on the shipped binary.</p>
+ <div class="bars">
+ <div class="bar-row">
+ <div class="names"><span class="task">runEval</span><span class="times">before 117.6s · after 57.4–81.3s · kimi 61.7s</span></div>
+ <div class="track"><div class="fill" style="width:100%; background:rgba(255,255,255,.22)"></div></div>
+ <div class="track"><div class="fill graff" style="width:59%"></div></div>
+ <div class="track"><div class="fill kimi" style="width:52.5%"></div></div>
+ </div>
+ <div class="bar-row">
+ <div class="names"><span class="task">providers</span><span class="times">before 60.7s · after 35.6–45.8s · kimi 50.4s</span></div>
+ <div class="track"><div class="fill" style="width:100%; background:rgba(255,255,255,.22)"></div></div>
+ <div class="track"><div class="fill graff" style="width:67%"></div></div>
+ <div class="track"><div class="fill kimi" style="width:83%"></div></div>
+ </div>
+ </div>
+ <div class="legend">
+ <span><span class="sw" style="background:rgba(255,255,255,.35)"></span>before (4 KiB handles)</span>
+ <span><span class="sw graff"></span>after (16 KiB, avg of 2 runs)</span>
+ <span><span class="sw kimi"></span>kimi-cli wall</span>
+ </div>
+ <table style="margin-top:18px">
+ <thead><tr><th>Task</th><th>Before</th><th>After (2 runs)</th><th>Δ avg</th><th>Calls before → after</th><th>vs kimi wall</th></tr></thead>
+ <tbody>
+ <tr><td><strong>runEval</strong></td><td class="num">117.6s</td><td class="num">81.3s · 57.4s</td><td class="num" style="color:var(--accent-bright)">−41%</td><td class="num">14 → 9 / 7</td><td class="num">61.7s — best run <strong>wins by 4.3s</strong></td></tr>
+ <tr><td><strong>providers</strong></td><td class="num">60.7s</td><td class="num">45.8s · 35.6s</td><td class="num" style="color:var(--accent-bright)">−33%</td><td class="num">10 → 3 / 3</td><td class="num">50.4s — <strong>both runs win</strong></td></tr>
+ <tr><td><strong>runEval + eager pin</strong></td><td class="num">117.6s</td><td class="num">58.5s · 48.2s</td><td class="num" style="color:var(--accent-bright)">−55%</td><td class="num">14 → 7 / 6</td><td class="num">61.7s — <strong>both runs win</strong></td></tr>
+ <tr><td><strong>providers, all fixes</strong> (incl. effort routing + cache lease)</td><td class="num">60.7s</td><td class="num"><strong>26.0s</strong></td><td class="num" style="color:var(--accent-bright)">−57%</td><td class="num">10 → 3</td><td class="num">50.4s wall / 29.2s true — <strong>beats both</strong></td></tr>
+ </tbody>
+ </table>
+ <p class="hint" style="margin:14px 0 0">Providers is the cleanest proof: the whole provider table now
+ arrives inline in one read, so the task takes 3 model calls instead of 10 — and 35.6s is within 6.4s of
+ kimi-cli's <em>true turn</em> (29.2s), i.e. genuine parity even before removing kimi's measurement pad.
+ The third row adds the eager-schema pin (licensed codedb-pro served up front): the codedb→refusal→
+ load_tool_schemas dance disappears from the traces entirely — zero refusals, zero discovery turns —
+ and runEval drops to 6-7 calls. Answers verified correct on every run.</p>
+ </div>
+
+ <div class="panel">
+ <h2>The details — post-fix</h2>
+ <p class="hint">Best clean-window runs with all fixes in (16 KiB handles, eager codedb-pro, effort routing, cache lease). Pre-fix numbers struck through. Kimi rows unchanged (it had no fixes to make).</p>
+ <table>
+ <thead>
+ <tr><th>Task</th><th>Harness</th><th>Wall (pre → post)</th><th>Calls</th><th>Token profile</th></tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td rowspan="2"><strong>runEval</strong></td>
+ <td><span class="pill graff">graff</span></td>
+ <td class="num"><s style="color:var(--muted)">117.6s</s> → <strong>48.2s</strong> <span style="color:var(--muted)">(32.6s low-routed)</span></td>
+ <td class="num">6 <span style="color:var(--muted)">(was 13-15)</span></td>
+ <td class="num">cache-warm from call 1 (10k)</td>
+ </tr>
+ <tr>
+ <td><span class="pill kimi">kimi</span></td>
+ <td class="num">61.7s wall · 40.4s true</td>
+ <td class="num">4 <span style="color:var(--muted)">(Grep ×3 · Read)</span></td>
+ <td class="num">12.3k in + 113.4k cache-read · 870 out</td>
+ </tr>
+ <tr>
+ <td rowspan="2"><strong>permgate</strong></td>
+ <td><span class="pill graff">graff</span></td>
+ <td class="num"><s style="color:var(--muted)">82.2s</s> → <strong>56.1s</strong></td>
+ <td class="num">11 <span style="color:var(--muted)">(stays high effort by design)</span></td>
+ <td class="num">cache-warm from call 1</td>
+ </tr>
+ <tr>
+ <td><span class="pill kimi">kimi</span></td>
+ <td class="num">69.6s wall · 48.3s true</td>
+ <td class="num">5 <span style="color:var(--muted)">(Grep ×3 · Read ×2)</span></td>
+ <td class="num">9.8k in + 141.1k cache-read · 1.0k out</td>
+ </tr>
+ <tr>
+ <td rowspan="2"><strong>providers</strong></td>
+ <td><span class="pill graff">graff</span></td>
+ <td class="num"><s style="color:var(--muted)">60.7s</s> → <strong>26.0s</strong></td>
+ <td class="num">3 <span style="color:var(--muted)">(was 10-11)</span></td>
+ <td class="num">cache-warm from call 1 (9.7k)</td>
+ </tr>
+ <tr>
+ <td><span class="pill kimi">kimi</span></td>
+ <td class="num">50.4s wall · 29.2s true</td>
+ <td class="num">3 <span style="color:var(--muted)">(Grep ×2 · Read)</span></td>
+ <td class="num">15.1k in + 65.8k cache-read · 959 out</td>
+ </tr>
+ </tbody>
+ </table>
+ </div>
+
+ <div class="panel">
+ <h2>Answer quality — both harnesses, both rounds</h2>
+ <p class="hint">Every answer was checked against the repository source after the run.</p>
+ <div class="grid2">
+ <div class="mini">
+ <h3>Honesty under a false premise — 4/4</h3>
+ <p>The runEval task asks about a function in <code>src/main.zig</code>, but it was moved to
+ <code>src/agent_eval.zig:41</code> long ago. Both harnesses, in both rounds, corrected the
+ premise instead of confabulating — and both cited the exact aliases
+ (<code>agent_compact.zig:36</code>, <code>agent.zig:427</code>).</p>
+ </div>
+ <div class="mini">
+ <h3>Line-exact citations</h3>
+ <p>Kimi's permgate answer named <code>readOnlyAllowed</code> at
+ <code>src/harness_policy.zig:83</code> — verified line-exact. Graff's round-2 answer led
+ with the actual entry point, <code>gateTool</code> (<code>agent_tool_gate.zig:212-234</code>),
+ including the shared-tree checkpoint that runs before approval logic.</p>
+ </div>
+ <div class="mini">
+ <h3>Different tool philosophies</h3>
+ <p>Graff reaches for its code index (<code>codedb</code>, codedbpro MCP) and shells out for
+ confirmation; kimi-cli relies on bare <code>Grep</code>/<code>Read</code> and makes 3× fewer
+ tool calls. Both strategies converge on the same correct facts.</p>
+ </div>
+ <div class="mini">
+ <h3>Round 1 → Round 2</h3>
+ <p>Round 1 (pre-fix build): graff 389.3s total vs kimi 222.8s true-turn, dragged by a 221s
+ MCP-latency outlier on providers. Round 2: that outlier collapsed to 60.7s; kimi's times
+ also dropped (warm server-side prompt cache — 65–141k cache-read tokens per turn).</p>
+ </div>
+ </div>
+ </div>
+
+ <div class="panel">
+ <h2>The fix this benchmark surfaced</h2>
+ <p class="hint">Round 1 showed graff badging "k3 · Medium" while kimi-cli ran K3 at thinking=high — an apparent effort mismatch that would have invalidated the comparison.</p>
+ <ul class="tight">
+ <li><strong>It was a badge bug, not a behavior bug.</strong> Graff's Kimi request path normalizes the session effort through the catalog allow-list (<code>pricing.kimiThinkingEffort</code>); the wire had always carried the catalog default. The live server declares K3 <code>default_effort: "high"</code> — the same effort kimi-cli used. Efforts were equal all along; only the status line lied.</li>
+ <li><strong>Fix:</strong> <code>src/agent_prompt.zig</code> now badges the normalized wire effort (<code>effectiveEffort</code>), and the baked K3 catalog row in <code>src/pricing.zig</code> was updated from <code>["max"]</code> to the server's real allow-list <code>[low, high, max]</code> (default high) so <code>/effort low|high</code> work offline too.</li>
+ <li><strong>Verified live:</strong> round 2's graff prompt reads <code>[k3 · High · kimi …]</code> — display matches the wire, and the comparison above is effort-matched by construction.</li>
+ <li>1208 unit tests green (baseline 1184), including a new regression test pinning the badge normalization.</li>
+ </ul>
+ </div>
+
+ <div class="panel">
+ <h2>Effort ladder — what the catalog fix unlocks</h2>
+ <p class="hint"><strong>Labeling caveat:</strong> the repetition batch and everything after it ran at low effort on both harnesses (both persist /effort; the fixture's settings file carried it). Within-round comparisons stayed symmetric; cross-round comparisons to the high-effort rounds are marked.</p>
+ <p class="hint">Same 3 tasks rerun at <code>/effort low</code> on both harnesses (K3 allow-list low/high/max now works end-to-end in graff, offline included). All 12 answers still verified correct — including the false-premise correction.</p>
+ <table>
+ <thead>
+ <tr><th>Task</th><th>Graff high</th><th>Graff low</th><th>Δ</th><th>Kimi high (true)</th><th>Kimi low (true)</th><th>Δ</th></tr>
+ </thead>
+ <tbody>
+ <tr><td><strong>runEval</strong></td><td class="num">117.6s</td><td class="num">61.4s</td><td class="num" style="color:var(--accent-bright)">−48%</td><td class="num">40.4s</td><td class="num">34.9s</td><td class="num" style="color:var(--accent-bright)">−14%</td></tr>
+ <tr><td><strong>permgate</strong></td><td class="num">82.2s</td><td class="num">152.3s</td><td class="num" style="color:var(--warn)">+85%</td><td class="num">48.3s</td><td class="num">42.9s</td><td class="num" style="color:var(--accent-bright)">−11%</td></tr>
+ <tr><td><strong>providers</strong></td><td class="num">60.7s</td><td class="num">41.8s</td><td class="num" style="color:var(--accent-bright)">−31%</td><td class="num">29.2s</td><td class="num">38.2s</td><td class="num" style="color:var(--warn)">+31%</td></tr>
+ </tbody>
+ </table>
+ <p class="hint" style="margin:14px 0 0">Low effort cuts per-call latency ~40% but can inflate tool-call count — graff's permgate run went 11 → 16 round-trips and gave the savings back. Effort is a per-task dial, not a global one.</p>
+ </div>
+
+ <div class="panel">
+ <h2>Where the time goes (instrumented)</h2>
+ <p class="hint">From graff's own run traces (<code>.graff/traces/*.jsonl</code>) and kimi-cli's wire log — no guessing.</p>
+ <ul class="tight">
+ <li><strong>Tool execution is free; model round-trips are everything.</strong> Across every graff run, total tool time was 0.1–0.2s per task (codedb and even the codedbpro MCP calls answer in &lt;100ms). 99%+ of wall time is API latency: ~5–9s per call at thinking=high.</li>
+ <li><strong>Graff makes 2–3× more model calls than the task needs.</strong> runEval: 14 calls vs kimi's 6 for the same correct answer. Each avoidable round-trip costs ~8s at high effort — that gap <em>is</em> the headline speed difference, not tool quality.</li>
+ <li><strong>Round 1's 221s outlier was a stalled stream, not MCP.</strong> The trace shows the first model call hung ~127s before the stall watchdog (default 120s, <code>GRAFF_STREAM_STALL_SECS</code>) killed and retried it; the call then completed in 6s. MCP was blamed in round 1's interim report — the traces say otherwise.</li>
+ <li><strong>Title generation is off the critical path.</strong> The AI tab-title call (~3s) fires concurrently with turn 1 and costs no wall time.</li>
+ </ul>
+ </div>
+
+ <div class="panel">
+ <h2>Outlier hunt — one pass, no reruns</h2>
+ <p class="hint">A trace analyzer (<code>analyze_outliers.py</code>) reads each run's event log once and localizes every anomaly: any call &gt;2× the run's median, plus stall-retry events. Ran over all 13 graff traces and 13 kimi sessions from every round.</p>
+ <ul class="tight">
+ <li><strong>Final-call outliers are benign.</strong> Nearly every run's last call flags at 2–3× median — that's the model writing the long final answer, not a fault. Any outlier that <em>isn't</em> the last call deserves the look.</li>
+ <li><strong>Graff's stall watchdog earns its keep.</strong> Round 1's 221s task: first stream hung, watchdog killed it at ~127s, retry finished in 6s. The analyzer flags the <code>stream_retry</code> event directly.</li>
+ <li><strong>Kimi-cli has no equivalent protection — caught live.</strong> In the repetition batch, kimi's 2nd request on providers-r2 <em>hung silently for 343.5s</em> (5.7 min) before the server answered; the turn took 378.7s for a question it otherwise answers in 29–39s. No retry, no warning.</li>
+ <li><strong>Mid-turn blowups mark the low-effort pathology.</strong> graff's permgate-low run flags calls #12/#13 at 6.5×/8.3× median (30s/38s) — the signature of low effort trading thinking for extra round-trips.</li>
+ <li><strong>Every run pays a refusal dance.</strong> The model's first move is the native <code>codedb</code> tool, which the licensed codedb-pro guard refuses, forcing a <code>load_tool_schemas</code> discovery round-trip before real work starts — ~2 calls ≈ 8–12s per task. The fix needs no code: <code>GRAFF_MCP_EAGER=codedbpro</code> (<code>src/mcp_schema_gate.zig:79</code>) preloads the schemas, so the model calls the pro tools directly. Making eager the default when a licensed in-charge server connects is a ~5-line change in that (unowned) file.</li>
+ <li><strong>Gotcha found — both harnesses persist effort.</strong> Kimi-cli keeps <code>/effort</code> across sessions in its own state; graff persists it to <code>.harness/settings.json</code> in the cwd. The repetition batch meant for high effort silently ran at low on BOTH sides (symmetric, so the A/B held — but the label was wrong until the traces outed it).</li>
+ </ul>
+ </div>
+
+ <div class="panel">
+ <h2>The API lead — per call, graff is faster</h2>
+ <p class="hint">Every API call from every round, by effort level (the 343s stall excluded from latency pools). Same model, same endpoint — what's left is harness overhead: prompt size, schema weight, stream handling.</p>
+ <table>
+ <thead><tr><th>Pool</th><th>Calls</th><th>Median</th><th>p90</th><th>Min</th><th>Max</th></tr></thead>
+ <tbody>
+ <tr><td><span class="pill graff">graff · high</span></td><td class="num">68</td><td class="num"><strong>5.8s</strong></td><td class="num">13.6s</td><td class="num">3.0s</td><td class="num">46.2s</td></tr>
+ <tr><td><span class="pill graff">graff · low</span></td><td class="num">33</td><td class="num"><strong>5.1s</strong></td><td class="num">13.1s</td><td class="num">3.3s</td><td class="num">38.2s</td></tr>
+ <tr><td><span class="pill kimi">kimi · high</span></td><td class="num">36</td><td class="num"><strong>8.4s</strong></td><td class="num">13.6s</td><td class="num">3.2s</td><td class="num">33.2s</td></tr>
+ <tr><td><span class="pill kimi">kimi · low</span></td><td class="num">35</td><td class="num"><strong>6.2s</strong></td><td class="num">13.9s</td><td class="num">4.4s</td><td class="num">20.9s</td></tr>
+ </tbody>
+ </table>
+ <p class="hint" style="margin:14px 0 0">
+ <strong>Graff holds a 2.6s/call lead at high effort (5.8s vs 8.4s median)</strong> — its 8k-token starting
+ prompt vs kimi-cli's ~23k is the likely driver. But read the arithmetic both ways: 5.8s × 14 calls is
+ <em>slower</em> than 8.4s × 6 calls — the per-call lead only pays once the call count matches. That was
+ the pre-fix state; this table's pools are the pre-fix data. After the handle-threshold and eager-pin
+ fixes, graff's runEval call count fell 14 → 6-7 and the lead converted: providers now runs 3 calls /
+ 26.0s vs kimi's 50.4s wall, and runEval's best runs (48.2s, 57.4s) beat kimi's wall (61.7s).
+ </p>
+ </div>
+
+ <div class="panel">
+ <h2>Improvement roadmap — with projections from this data</h2>
+ <div class="grid2">
+ <div class="mini">
+ <h3>P1 · Tool-call economy <span class="pill graff">shipped: best run 32.6s</span></h3>
+ <p>Projection tested with a prompt-level economy nudge on runEval: when K3 economizes, the run
+ drops to 6 calls / 40.3s — but the nudge only landed ~50% of the time, and K3 emitted <em>zero</em>
+ parallel tool batches across all 15 runs, so economy had to be systemic, not advisory. The systemic
+ fix: the tool-result handle threshold (<code>tool_handle.zig</code>, #440) was 4 KiB, so nearly every
+ search/read came back as a handle that cost a follow-up round-trip. Raised to 16 KiB (still bounded,
+ still clamped by the per-output cap, env-tunable via <code>GRAFF_TOOL_HANDLE_BYTES</code>). Stock-binary
+ validation on runEval (low effort, per the persistence note below): 9 calls / 64.8s and <strong>6 calls /
+ 32.6s — the fastest graff run recorded, edging kimi-cli's best low-effort true turn (33.9s)</strong>,
+ answer correct. 1209 tests green.</p>
+ </div>
+ <div class="mini">
+ <h3>P2 · Effort routing <span class="pill graff">shipped</span></h3>
+ <p><code>src/effort_route.zig</code>: a lookup-shaped prompt (question cue, no mutation verb) runs its
+ turn at low effort while the session knob is the untouched default — explicit /effort always wins.
+ The cue list is pinned against the benchmark tasks themselves: runEval and providers route low,
+ permgate (which inflated +85% at low) stays high. Shipped with a regression test.</p>
+ </div>
+ <div class="mini">
+ <h3>P3 · Faster stall recovery <span class="pill graff">shipped</span></h3>
+ <p>With thinking streamed, a socket silent for >45s before the FIRST token is dead, not reasoning —
+ so the pre-token budget is now capped at 45s (<code>http_stall.head_ceiling_ms</code>, env-overridable
+ via <code>GRAFF_STREAM_HEAD_STALL_SECS</code>; <code>GRAFF_STREAM_STALL_SECS</code> still wins both
+ regimes when set). Graff's own stalled task would have capped at ~95s instead of 221s — and kimi-cli's
+ silent 343.5s hang has no equivalent protection at all.</p>
+ </div>
+ <div class="mini">
+ <h3>Done · Cache lease <span class="pill graff">first calls 0 → 10k warm</span></h3>
+ <p>Kimi partitions its prompt cache by <code>prompt_cache_key</code>, and graff minted a fresh UUID per
+ process — so every session's first call was cache-cold while kimi-cli's hit ~19k warm. The kimi path
+ now sends a durable per-project key (<code>http_headers.projectCacheKey</code>, cwd-derived UUIDv5).
+ Measured: first-call cache_read went 0 → 9.7–10.1k on back-to-back sessions.</p>
+ </div>
+ <div class="mini">
+ <h3>Done · Effort badge honesty</h3>
+ <p>The badge now names the effort that goes on the wire (<code>effectiveEffort</code>), and the
+ baked K3 catalog matches the server's <code>[low, high, max]</code> allow-list. Shipped in this
+ working tree; 1208 tests green.</p>
+ </div>
+ </div>
+ </div>
+
+ <div class="panel">
+ <h2>Bonus round: pi (interactive, same k3)</h2>
+ <p class="hint">Pi v0.84.1 wired to the same Kimi Code endpoint as a custom provider (<code>openai-completions</code> + <code>compat.supportsDeveloperRole=false</code> — the stock shape 400s on <code>role: developer</code>). Same fixture, same prompts, same PTY driving. Effort: pi sends no thinking config, so k3 runs its server-side default.</p>
+ <table>
+ <thead><tr><th>Task</th><th>pi wall</th><th>pi true</th><th>pi calls</th><th>vs graff post-fix</th><th>vs kimi-cli wall</th></tr></thead>
+ <tbody>
+ <tr><td><strong>runEval</strong></td><td class="num">173.0s</td><td class="num">151.9s</td><td class="num">6</td><td class="num">graff 48.2s — <strong>3.6× faster</strong></td><td class="num">61.7s — graff 2.8× faster</td></tr>
+ <tr><td><strong>permgate</strong></td><td class="num">79.7s</td><td class="num">58.5s</td><td class="num">7</td><td class="num">graff 56.1s — <strong>1.4× faster</strong></td><td class="num">69.6s — graff 1.2× faster</td></tr>
+ <tr><td><strong>providers</strong></td><td class="num">142.2s</td><td class="num">121.0s</td><td class="num">3</td><td class="num">graff 26.0s — <strong>5.5× faster</strong></td><td class="num">50.4s — graff 1.9× faster</td></tr>
+ </tbody>
+ </table>
+ <p class="hint" style="margin:14px 0 0">The instructive result: pi places FEW calls (6/7/3 — as disciplined as
+ post-fix graff) yet loses by minutes, because its per-call latency is 10–40s where graff's is 5–9s on the
+ same model and endpoint. What a harness sends per request (thinking config, cache key, streaming shape)
+ is worth more than call discipline alone. All three pi answers were correct — it catches the runEval
+ false premise too.</p>
+ </div>
+
+ <div class="panel">
+ <h2>Method &amp; caveats</h2>
+ <ul class="tight">
+ <li><strong>Same everything:</strong> model (K3), auth (one Kimi Code OAuth subscription), working tree (<code>git archive</code> of HEAD into a clean fixture, no MCP config), prompts (verbatim from <code>benchmarks/tasks.py</code>), permission mode (<code>--yolo</code> both), fresh session per cell.</li>
+ <li><strong>Interactive for real:</strong> both TUIs driven through a PTY (<code>scripts/pty_harness.py</code>). Graff turn end = prompt return (exact); kimi turn end = 20s output silence, so its wall times carry a fixed ~21s pad — judge kimi by the "true turn" column from its own session log.</li>
+ <li><strong>One run per cell per round.</strong> Timings swing with network and server-side cache warmth (kimi round 2 read 65–141k cached tokens per turn). Treat ratios as directional, not absolute.</li>
+ <li><strong>Read-only Q&amp;A tasks only.</strong> No editing, refactoring, or multi-step agentic work is measured here.</li>
+ <li>Found while automating: kimi-cli's TUI swallows Enter sent in the same <code>write()</code> as the prompt text (paste detection) — automation must send text, pause, then Enter. Also, it self-upgraded 0.26.0 → 0.34.0 on launch without asking.</li>
+ </ul>
+ <p class="foot">
+ Raw transcripts, drivers, and ground-truth session logs: <code>/tmp/graff-kimi-compare/</code>
+ (round 1 in <code>runs/</code>, round 2 in <code>runs2/</code>, effort-low in <code>runs-low/</code>, reps in <code>runs-reps/</code>,
+ 32 KiB A/B in <code>runs-bigthresh/</code>, new-default validation in <code>runs-newdefault/</code>,
+ outlier analyzer <code>analyze_outliers.py</code>, narrative in <code>REPORT.md</code>).
+ Effort-badge fix: <code>src/agent_prompt.zig</code> + <code>src/pricing.zig</code>, uncommitted on <code>feat/agent-inbox</code>.
+ </p>
+ </div>
+ </div>
+</body>
+</html>
diff --git a/src/agent_prompt.zig b/src/agent_prompt.zig
index 66293733..66b34d16 100644
--- a/src/agent_prompt.zig
+++ b/src/agent_prompt.zig
@@ -33,7 +33,7 @@ fn status(self: *Agent) engine_events.PromptStatus {
.cwd = main_mod.g_cwd_display,
.privacy_label = learning_privacy.current().badge(),
.privacy = privacyTier(learning_privacy.current()),
- .effort = if (self.effortApplies()) effortTier(self.reasoning) else null,
+ .effort = effectiveEffort(self),
// The meter appears only once a response has reported usage, but the
// count it shows is the EFFECTIVE one (local estimates carry it
// between turns) — two different questions, as it has always been.
@@ -77,6 +77,22 @@ fn effortTier(effort: main_mod.ReasoningEffort) engine_events.ReasoningEffort {
};
}
+/// The badge names the effort that will actually go on the wire. Kimi
+/// normalizes the session knob against the catalog's allow-list (k3 allows
+/// low/high/max with default max, so a Medium session sends "max"); showing
+/// the raw knob would badge "Medium" over a request that runs at "max".
+fn effectiveEffort(self: *Agent) ?engine_events.ReasoningEffort {
+ if (std.mem.eql(u8, self.provider.id, "kimi")) {
+ const wire = pricing.kimiThinkingEffort(self.provider.model, @tagName(self.reasoning)) orelse
+ return null;
+ inline for (std.meta.tags(main_mod.ReasoningEffort)) |tag| {
+ if (std.mem.eql(u8, @tagName(tag), wire)) return effortTier(tag);
+ }
+ return null;
+ }
+ return if (self.effortApplies()) effortTier(self.reasoning) else null;
+}
+
fn privacyTier(mode: learning_privacy.Mode) engine_events.PrivacyTier {
return switch (mode) {
.local => .local,
@@ -106,3 +122,31 @@ test "the vocabulary's tiers stay in step with the engine's own enums" {
try std.testing.expectEqualStrings(@tagName(m), @tagName(privacyTier(m)));
}
}
+
+test "kimi effort badge names the normalized wire effort, not the raw knob" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ const messages = std.json.Array.init(arena);
+ var agent: Agent = .{
+ .gpa = std.testing.allocator,
+ .arena = arena,
+ .io = std.testing.io,
+ .client = undefined,
+ .provider = .{ .id = "kimi", .kind = .openai, .auth = .bearer, .url = "", .api_key = "", .model = "k3", .context = 1_048_576 },
+ .messages = messages,
+ .sub = false,
+ .label = "",
+ .out = null,
+ .sys_normal = "",
+ };
+ // k3 allows low/high/max with default high: a Medium session runs at the
+ // catalog default, while an allowed effort passes through untouched.
+ agent.reasoning = .medium;
+ try std.testing.expectEqual(engine_events.ReasoningEffort.high, effectiveEffort(&agent).?);
+ agent.reasoning = .max;
+ try std.testing.expectEqual(engine_events.ReasoningEffort.max, effectiveEffort(&agent).?);
+ // No catalog row, no wire effort, no badge.
+ agent.provider.model = "unknown-xyz";
+ try std.testing.expectEqual(@as(?engine_events.ReasoningEffort, null), effectiveEffort(&agent));
+}
diff --git a/src/agent_request_body.zig b/src/agent_request_body.zig
index f0ff8793..726b8f5a 100644
--- a/src/agent_request_body.zig
+++ b/src/agent_request_body.zig
@@ -167,11 +167,11 @@ pub fn buildBody(self: *Agent, tools: ?[]const u8, force_tool: bool, stream: boo
}
try s.endObject();
}
- // kimi-code pins each request to its session id for prompt-cache affinity (same partition trick as codex below).
+ // Kimi pins each request for prompt-cache affinity; graff sends the durable per-PROJECT key (http_headers.projectCacheKey).
if (is_kimi) {
var ckbuf: [96]u8 = undefined;
try s.objectField("prompt_cache_key");
- try s.write(http_headers.promptCacheKey(self.io, self.label, self, &ckbuf));
+ try s.write(http_headers.projectCacheKey(self.io, self.label, self, &ckbuf));
}
// Reasoning-effort hint for OpenAI-compatible providers that
// honor it (codegraff gateway, deepseek). Mirrors the
diff --git a/src/agent_tool_render.zig b/src/agent_tool_render.zig
index 1c651876..52f5f148 100644
--- a/src/agent_tool_render.zig
+++ b/src/agent_tool_render.zig
@@ -22,6 +22,7 @@ const std = @import("std");
const Io = std.Io;
const main_mod = @import("main.zig");
+const repl = @import("repl.zig"); // g_debug gate for the spill notice
const agent_mod = @import("agent.zig");
const Agent = agent_mod.Agent;
const agent_output = @import("agent_output.zig");
@@ -63,9 +64,40 @@ pub fn toolUseLine(a: *Agent, t: ToolInvocation) void {
sayText(a, line.writer.buffered());
}
+/// The #440 marker prefixes forResult tags oversized results with. Detected
+/// off the result text itself, so the badge needs no new field on the event
+/// vocabulary (and no SDK schema change).
+const handle_marker = "[tool result handle: ";
+const truncated_marker = "[tool result truncated to ";
+
+const HandleBadge = struct { bytes: usize, truncated: bool };
+
+/// Parse the spill size out of a #440 marker line, null for ordinary results.
+fn handleBadge(text: []const u8) ?HandleBadge {
+ if (std.mem.startsWith(u8, text, handle_marker)) {
+ const rest = text[handle_marker.len..];
+ const end = std.mem.indexOf(u8, rest, " bytes") orelse return null;
+ const n = std.fmt.parseInt(usize, rest[0..end], 10) catch return null;
+ return .{ .bytes = n, .truncated = false };
+ }
+ // "[tool result truncated to {shown} bytes: {total} bytes total, …"
+ if (std.mem.startsWith(u8, text, truncated_marker)) {
+ const rest = text[truncated_marker.len..];
+ const cut = std.mem.indexOf(u8, rest, " bytes: ") orelse return null;
+ const rest2 = rest[cut + " bytes: ".len ..];
+ const end = std.mem.indexOf(u8, rest2, " bytes total") orelse return null;
+ const n = std.fmt.parseInt(usize, rest2[0..end], 10) catch return null;
+ return .{ .bytes = n, .truncated = true };
+ }
+ return null;
+}
+
/// Compact result feedback for one finished tool call: a green ✓ / red ✗ /
-/// yellow ⊘ and a one-line preview of what it returned. Root only (subagents
-/// have no writer); meta tools render their own UX, so skip them. This one
+/// yellow ⊘ and a one-line preview of what it returned. A result that spilled
+/// to a #440 handle (or was truncated without one) also badges the spill size —
+/// the handle costs the model a follow-up read round-trip, and that cost
+/// should be visible to the human, not silent. Root only (subagents have no
+/// writer); meta tools render their own UX, so skip them. This one
/// writes straight to the writer — it never ended a tick-gate row.
pub fn toolResultLine(a: *Agent, r: ToolOutcome) void {
const w = a.out orelse return;
@@ -83,15 +115,59 @@ pub fn toolResultLine(a: *Agent, r: ToolOutcome) void {
(std.fmt.bufPrint(&tbuf, " ({d}ms)", .{r.ms}) catch "")
else
"";
- w.print(" {s}{s}{s}{s}{s}{s} {s}{s}{s}{s}\n", .{
- mc, mark, style.reset, style.dim, timing, style.reset,
- style.dim, shown,
+ // Self-contained: colors and the trailing reset ride inside the badge, so
+ // an empty badge leaves the line byte-identical to the pre-badge format.
+ var bbuf: [48]u8 = undefined;
+ const badge = if (handleBadge(all)) |h| blk: {
+ const kib = @as(f64, @floatFromInt(h.bytes)) / 1024.0;
+ break :blk if (h.truncated)
+ std.fmt.bufPrint(&bbuf, "{s}⇠ {d:.1} KiB lost{s} ", .{ style.yellow, kib, style.reset }) catch ""
+ else
+ std.fmt.bufPrint(&bbuf, "{s}⇢ {d:.1} KiB handle{s} ", .{ style.accent, kib, style.reset }) catch "";
+ } else "";
+ w.print(" {s}{s}{s}{s}{s}{s} {s}{s}{s}{s}{s}\n", .{
+ mc, mark, style.reset, style.dim, timing, style.reset,
+ badge, style.dim, shown,
if (truncated) "…" else "",
style.reset,
}) catch return;
w.flush() catch return;
}
+/// Normal-mode spill notice (#440): the one tool-result moment the terminal
+/// draws outside debug mode. A spilled result costs the model a follow-up
+/// read round-trip, and that cost should be visible rather than silent —
+/// debug mode already shows it as the badge on the full ✓ line, so this
+/// stays quiet there (and in --json, where the wire event carries it).
+pub fn handleSpillLine(a: *Agent, bytes: usize, has_handle: bool) void {
+ if (main_mod.json_mode) return;
+ if (repl.g_debug) return;
+ const w = a.out orelse return;
+ const kib = @as(f64, @floatFromInt(bytes)) / 1024.0;
+ var buf: [72]u8 = undefined;
+ const line = if (has_handle)
+ std.fmt.bufPrint(&buf, " {s}⇢ {d:.1} KiB handle{s}\n", .{ style.accent, kib, style.reset }) catch return
+ else
+ std.fmt.bufPrint(&buf, " {s}⇠ {d:.1} KiB lost{s}\n", .{ style.yellow, kib, style.reset }) catch return;
+ w.writeAll(line) catch return;
+ w.flush() catch return;
+}
+
+/// Turn-start note when effort routing (effort_route.zig) moved a
+/// lookup-shaped turn to low effort: the prompt line was drawn before the
+/// prompt existed, so it still shows the session knob — this one dim line is
+/// what the turn actually ran at. Normal mode only; debug and --json already
+/// carry the truth (the request's thinking.effort / the event stream).
+pub fn routedEffortLine(a: *Agent) void {
+ if (main_mod.json_mode) return;
+ if (repl.g_debug) return;
+ const w = a.out orelse return;
+ var buf: [80]u8 = undefined;
+ const line = std.fmt.bufPrint(&buf, " {s}⇣ lookup turn — routed to effort low for this turn{s}\n", .{ style.dim, style.reset }) catch return;
+ w.writeAll(line) catch return;
+ w.flush() catch return;
+}
+
// The batch tallies fit a fixed slot with room to spare: the widest line is
// three usize decimals plus ~50 bytes of wording and two short style runs.
const notice_buf_bytes: usize = 192;
@@ -216,6 +292,57 @@ test "the result line marks success, failure and cancellation and previews one l
main_mod.show_timing = true;
toolResultLine(&a, .{ .name = "bash", .text = "ok", .is_error = false, .ms = 42 });
try std.testing.expectEqualStrings(" ✓ (42ms) ok\n", aw.writer.buffered());
+
+ // A #440 handle spill badges its size between the timing slot and the
+ // preview (which still leads with the marker, so the path stays visible).
+ aw.clearRetainingCapacity();
+ main_mod.show_timing = false;
+ toolResultLine(&a, .{ .name = "bash", .text = "[tool result handle: 44690 bytes, JSON object — the COMPLETE result is at /tmp/h-0.txt. Slice what you need out of that file (read_file with start_line/end_line, a grep-style bash command, codedb) instead of re-running the tool (#440).]", .is_error = false });
+ const hline = aw.writer.buffered();
+ try std.testing.expect(std.mem.startsWith(u8, hline, " ✓ ⇢ 43.6 KiB handle [tool result handle: 44690 bytes"));
+
+ // The no-handle truncation variant badges the loss instead.
+ aw.clearRetainingCapacity();
+ toolResultLine(&a, .{ .name = "bash", .text = "[tool result truncated to 16384 bytes: 90000 bytes total, JSON object. No handle could be written, so the rest is gone — narrow the command and run it again (#440).]", .is_error = false });
+ try std.testing.expect(std.mem.startsWith(u8, aw.writer.buffered(), " ✓ ⇠ 87.9 KiB lost [tool result truncated"));
+}
+
+test "the spill notice draws in normal mode and stays quiet in debug mode" {
+ const saved = ansi.style;
+ ansi.style = .{};
+ defer ansi.style = saved;
+ const saved_json = main_mod.json_mode;
+ main_mod.json_mode = false;
+ defer main_mod.json_mode = saved_json;
+ const saved_debug = repl.g_debug;
+ repl.g_debug = false;
+ defer repl.g_debug = saved_debug;
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a = testAgent(&aw.writer);
+
+ handleSpillLine(&a, 44690, true);
+ try std.testing.expectEqualStrings(" ⇢ 43.6 KiB handle\n", aw.writer.buffered());
+
+ aw.clearRetainingCapacity();
+ handleSpillLine(&a, 90000, false);
+ try std.testing.expectEqualStrings(" ⇠ 87.9 KiB lost\n", aw.writer.buffered());
+
+ // Debug mode already draws the badge on the full ✓ line — no double draw.
+ aw.clearRetainingCapacity();
+ repl.g_debug = true;
+ handleSpillLine(&a, 44690, true);
+ try std.testing.expectEqualStrings("", aw.writer.buffered());
+
+ // The effort-routing note follows the same gates: normal mode only.
+ repl.g_debug = false;
+ aw.clearRetainingCapacity();
+ routedEffortLine(&a);
+ try std.testing.expectEqualStrings(" ⇣ lookup turn — routed to effort low for this turn\n", aw.writer.buffered());
+ aw.clearRetainingCapacity();
+ repl.g_debug = true;
+ routedEffortLine(&a);
+ try std.testing.expectEqualStrings("", aw.writer.buffered());
}
test "batch tallies and meta notices render the old wording verbatim" {
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index 82aeed74..38313c22 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -27,7 +27,7 @@ const parseAnswerRequest = tools_mod.parseAnswerRequest;
// which belongs to the input-inversion issue (#430), not to this one.
const engine_events = @import("engine_events.zig");
const engine_sink = @import("engine_sink.zig");
-
+const tool_render = @import("agent_tool_render.zig");
const terminal = @import("term.zig");
const tty = terminal.tty;
@@ -184,6 +184,9 @@ pub fn runTools(self: *Agent, calls: []const ToolCall) ![]ExecResult {
// the complete bytes go to a durable handle and the model gets a
// bounded preview, that path, the byte count, and a shape hint.
const handled = try tool_handle.forResult(self.gpa, self.arena, handle_target, output.text, handle_threshold);
+ // Surface spill round-trips in normal mode; debug already draws the badged ✓ line.
+ if (output.text.len > handle_threshold)
+ tool_render.handleSpillLine(self, output.text.len, handled.path != null);
results[i] = .{ .text = handled.text, .is_error = output.is_error, .cancelled = output.cancelled, .ms = output.ms };
if (self.eval_cmd != null and toolInvalidatesEval(calls[i])) {
self.eval_verified = false;
diff --git a/src/effort_route.zig b/src/effort_route.zig
new file mode 100644
index 00000000..50a0d5fa
--- /dev/null
+++ b/src/effort_route.zig
@@ -0,0 +1,63 @@
+//! Per-turn effort routing (k3 benchmark, 2026-08): a lookup/Q&A-shaped prompt
+//! runs its turn at low effort when the session knob is still the untouched
+//! default. Measured on the graff×kimi-cli k3 benchmark: lookup tasks at low
+//! effort lose no answer quality (12/12 correct, false-premise corrections
+//! included) and cut wall time ~40-50% (runEval 32.6s vs 57.4-81.3s), because
+//! per-call thinking dominates and low effort thinks less. Edit-shaped prompts
+//! keep the default: low effort there INFLATES tool-call count (permgate went
+//! 11→16 calls and +85% wall), so anything that smells like mutation is never
+//! routed down.
+//!
+//! An explicit user choice always wins: routing only fires while the session
+//! effort is the stock `.medium` default (see the runTurn call site).
+
+const std = @import("std");
+
+/// Case-insensitive substring check, no allocation.
+fn containsI(haystack: []const u8, needle: []const u8) bool {
+ if (needle.len > haystack.len) return false;
+ var i: usize = 0;
+ while (i + needle.len <= haystack.len) : (i += 1) {
+ if (std.ascii.eqlIgnoreCase(haystack[i .. i + needle.len], needle)) return true;
+ }
+ return false;
+}
+
+const lookup_cues = [_][]const u8{
+ "what ", "what's", "how do", "how does", "how is", "where ",
+ "which ", "why ", "explain", "list ", "tell me", "describe",
+ "show me", "summarize", "who ", "?", "do not modify", "do not change",
+ "don't change", "read-only",
+};
+
+const mutation_cues = [_][]const u8{
+ "fix", "implement", " add ", "update ", "refactor", "write ",
+ "create", "delete", "remove ", "rewrite", "build ", "run ",
+ "commit", "install", "rename", "patch", "bump", "edit ",
+ "change the", "change this",
+ // NOTE: bare "modify "/"change " are deliberately absent — read-only tasks
+ // habitually end with "do not modify any files", and poisoning on that
+ // phrase would exclude exactly the prompts this router exists for.
+};
+
+/// True when a prompt is shaped like a read-only lookup: it carries a question
+/// or explanation cue and NO mutation cue. Conservative by construction — a
+/// miss just means the turn runs at the session default.
+pub fn routesToLowEffort(prompt: []const u8) bool {
+ if (prompt.len < 12) return false; // "fix it" is short; questions carry words
+ for (mutation_cues) |cue| if (containsI(prompt, cue)) return false;
+ for (lookup_cues) |cue| if (containsI(prompt, cue)) return true;
+ return false;
+}
+
+test "lookup prompts route low, mutation prompts and bare commands do not" {
+ // The three benchmark tasks are the pinned shape: two route low, and the
+ // one that REGRESSED at low effort (permgate) must not route.
+ try std.testing.expect(routesToLowEffort("In src/main.zig of this repository, what does the function runEval do, and which other functions or methods does it call? Answer in 4-5 sentences. Do not modify any files."));
+ try std.testing.expect(routesToLowEffort("In this repository, list the AI model providers graff supports, and for each give its wire-format/auth style and the environment variable for its API key. Be concise. Do not modify any files."));
+ try std.testing.expect(!routesToLowEffort("In this repository, how does the permission gate decide whether a bash command needs approval, and what rule lets read-only commands run without prompting? Name the key function(s) by name. Answer in 4-5 sentences. Do not modify any files.")); // "run without" — the task that inflated at low
+ try std.testing.expect(!routesToLowEffort("fix the failing test in agent.zig"));
+ try std.testing.expect(!routesToLowEffort("implement the feature and update the docs"));
+ try std.testing.expect(!routesToLowEffort("hi"));
+ try std.testing.expect(routesToLowEffort("Explain how the permission gate works here?"));
+}
diff --git a/src/http_headers.zig b/src/http_headers.zig
index 8d4224a8..a751ade1 100644
--- a/src/http_headers.zig
+++ b/src/http_headers.zig
@@ -53,6 +53,40 @@ pub fn promptCacheKey(io: Io, label: []const u8, agent: *const anyopaque, buf: [
return std.fmt.bufPrint(buf, "{s}-{x}", .{ base, @intFromPtr(agent) }) catch base;
}
+/// Kimi-only: a DURABLE per-project cache partition, derived from the cwd
+/// (UUIDv5-style, no state to persist). The kimi backend keys its prompt
+/// cache on prompt_cache_key, and a per-process random key made every new
+/// session's first call a cold partition — measured cache_read=0 on every
+/// first call in the k3 benchmark, where kimi-cli's fresh sessions hit ~19k.
+/// A per-project key lets the first call of a new session land on the warm
+/// shared system-prompt prefix (~2-4s). Same-project sessions share the
+/// partition: conversation tails evict each other, the expensive prefix still
+/// hits. Subagents keep a per-agent suffix (the eviction reasoning above).
+pub fn projectCacheKey(io: Io, label: []const u8, agent: *const anyopaque, buf: []u8) []const u8 {
+ var raw: [16]u8 = undefined;
+ {
+ var cwd_buf: [4096]u8 = undefined;
+ const n = Io.Dir.cwd().realPathFile(io, ".", &cwd_buf) catch blk: {
+ @memcpy(cwd_buf[0..1], ".");
+ break :blk 1;
+ };
+ const cwd = cwd_buf[0..n];
+ var digest: [32]u8 = undefined;
+ var h = std.crypto.hash.sha2.Sha256.init(.{});
+ h.update("graff-kimi-project-cache-v1");
+ h.update(cwd);
+ h.final(&digest);
+ @memcpy(&raw, digest[0..16]);
+ raw[6] = (raw[6] & 0x0f) | 0x50; // version 5: name-derived
+ raw[8] = (raw[8] & 0x3f) | 0x80; // variant 1
+ }
+ const hex = std.fmt.bytesToHex(raw, .lower);
+ const base = std.fmt.bufPrint(buf, "{s}-{s}-{s}-{s}-{s}", .{ hex[0..8], hex[8..12], hex[12..16], hex[16..20], hex[20..32] }) catch unreachable;
+ if (std.mem.eql(u8, label, "main")) return base;
+ const suffix = std.fmt.bufPrint(buf[base.len..], "-{x}", .{@intFromPtr(agent)}) catch return base;
+ return buf[0 .. base.len + suffix.len];
+}
+
/// /resume adopts the persisted key so k3/codex prompt-cache affinity survives
/// the process boundary — both upstreams key the cache on the durable
/// conversation id (kimi-code's sessionContext.sessionId; codex's ModelClient
@@ -136,6 +170,22 @@ test "session_id is a stable per-process UUIDv4, not a shared constant" {
return error.SessionIdHeaderMissing;
}
+test "projectCacheKey is a durable per-project v5 UUID, stable across calls" {
+ var fake: usize = 0;
+ const agent: *const anyopaque = @ptrCast(&fake);
+ var buf: [96]u8 = undefined;
+ const a = projectCacheKey(std.testing.io, "main", agent, &buf);
+ try std.testing.expectEqual(@as(usize, 36), a.len);
+ try std.testing.expectEqual(@as(u8, '5'), a[14]); // version nibble: name-derived
+ var buf2: [96]u8 = undefined;
+ const b = projectCacheKey(std.testing.io, "main", agent, &buf2);
+ try std.testing.expectEqualStrings(a, b); // durable: no per-process randomness
+ // Subagents get a per-agent suffix off the same partition (eviction rule).
+ var buf3: [96]u8 = undefined;
+ const sub = projectCacheKey(std.testing.io, "sub", agent, &buf3);
+ try std.testing.expect(std.mem.startsWith(u8, sub, a));
+}
+
test "adoptSessionId validates length and never overwrites a minted id" {
const io = std.testing.io;
const before = sessionId(io); // minted by whichever test ran first
diff --git a/src/http_stall.zig b/src/http_stall.zig
index db36903a..54aeaa9a 100644
--- a/src/http_stall.zig
+++ b/src/http_stall.zig
@@ -24,8 +24,19 @@ pub var idle_floor_ms: u64 = 15 * 1000;
/// How long a stream read may sit silent before the watchdog calls it dead.
/// `base_ms` is the configured budget (http.stream_stall_ms); `tokens_flowing`
/// says whether THIS stream has already emitted tokens.
+/// Pre-first-token ceiling. The full budget used to stand before the first
+/// byte "because a reasoning model can be silent for minutes" — but with
+/// thinking STREAMED (kimi keep:"all", codex reasoning deltas) a healthy
+/// request emits its first token in seconds, and a totally silent socket is
+/// dead, not thinking: the k3 benchmark watched a stalled first call burn
+/// 127s before the watchdog retried, after which it completed in 6s.
+/// GRAFF_STREAM_STALL_SECS (or GRAFF_STREAM_HEAD_STALL_SECS) still overrides
+/// for a provider that genuinely buffers in silence. Mutable for tests, like
+/// idle_floor_ms; production writes it only from session_settings.
+pub var head_ceiling_ms: u64 = 45 * 1000;
+
pub fn budgetMs(base_ms: u64, tokens_flowing: bool) u64 {
- if (!tokens_flowing) return base_ms; // pre-first-token: a legit long reasoning pause
+ if (!tokens_flowing) return @min(base_ms, head_ceiling_ms);
return @min(base_ms, @max(idle_floor_ms, base_ms / idle_divisor));
}
@@ -38,11 +49,11 @@ pub fn expired(waited_ms: u64, base_ms: u64, tokens_flowing: bool) bool {
test "stall budget (#56): between-lines silence trips sooner than a pre-first-token pause" {
const base: u64 = 120 * 1000; // the shipped http.stream_stall_ms default
- // Before the first token the full budget stands: a reasoning model can be
- // silent for minutes before it emits anything, so nothing shorter is safe.
- try std.testing.expectEqual(base, budgetMs(base, false));
- try std.testing.expect(!expired(base - 1, base, false));
- try std.testing.expect(expired(base, base, false));
+ // Before the first token the head ceiling applies: with thinking streamed,
+ // a silent socket past it is dead, not reasoning.
+ try std.testing.expectEqual(head_ceiling_ms, budgetMs(base, false));
+ try std.testing.expect(!expired(head_ceiling_ms - 1, base, false));
+ try std.testing.expect(expired(head_ceiling_ms, base, false));
// Tokens already flowed: a quarter of it (30s), so a dead stream is given
// up on 4x sooner instead of holding the turn for another 90s of silence.
@@ -53,8 +64,12 @@ test "stall budget (#56): between-lines silence trips sooner than a pre-first-to
// is done and the pre-first-token one is still waiting.
try std.testing.expect(expired(30 * 1000, base, true) and !expired(30 * 1000, base, false));
- // GRAFF_STREAM_STALL_SECS (session_run writes http.stream_stall_ms, which
- // arrives here as base_ms) keeps scaling both regimes.
+ // GRAFF_STREAM_STALL_SECS (session_settings writes http.stream_stall_ms,
+ // which arrives here as base_ms) still wins BOTH regimes when set high —
+ // simulated by raising the ceiling the way the env knob does.
+ const saved_ceiling = head_ceiling_ms;
+ head_ceiling_ms = 600 * 1000;
+ defer head_ceiling_ms = saved_ceiling;
try std.testing.expectEqual(@as(u64, 600 * 1000), budgetMs(600 * 1000, false));
try std.testing.expectEqual(@as(u64, 150 * 1000), budgetMs(600 * 1000, true));
diff --git a/src/main.zig b/src/main.zig
index 9f1c1625..49e29192 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -167,7 +167,7 @@ const skills = @import("skills.zig");
const skills_registry = skills.skills_registry;
const companion_servers = skills.companion_servers;
const mcpServerConnected = skills.mcpServerConnected;
-const probeLicensed = session_start.probeLicensed; // license probe only — schemas stay deferred; the guard enforces routing (#476)
+const probeLicensed = session_start.probeLicensedPinningEager; // probe + pin: a licensed suite's guard FORCES its tools, so its schemas ride the first catalog — deferral was a measured ~2 discovery round-trips per task
/// PATH captured at startup for skill detection (PATH won't change mid-run).
pub var g_path_env: []const u8 = "";
/// Human-facing current workspace folder shown in the REPL prompt.
@@ -391,7 +391,7 @@ pub fn main(init: std.process.Init) !void {
try session_start.connectCompanion(io, arena, &registry_storage, flags, out, json_mode, init.environ_map);
const mcp_tools: []const mcp.Tool = registry_storage.tools;
// If the metered companion connected, probe its license once so the note below can lean into paid tools (vs the conservative free-codedb note).
- if (!session_start.leanMode(flags.effectiveLean(), init.environ_map) and mcpServerConnected(mcp_tools, "codedbpro")) g_codedbpro_licensed = probeLicensed(gpa, io);
+ if (!session_start.leanMode(flags.effectiveLean(), init.environ_map) and mcpServerConnected(mcp_tools, "codedbpro")) g_codedbpro_licensed = probeLicensed(gpa, io, arena);
boot.mark(io, "companion");
var approvals: Approvals = undefined;
diff --git a/src/pricing.zig b/src/pricing.zig
index e28cc056..db7a5ad3 100644
--- a/src/pricing.zig
+++ b/src/pricing.zig
@@ -270,7 +270,7 @@ pub const model_table = [_]ModelInfo{
// Kimi Code offline fallback. Authenticated startup replaces this slice
// from /coding/v1/models; K3 is the current explicit generation while the
// two compatibility aliases keep their smaller advertised window.
- .{ .provider = "kimi", .name = "k3", .context = 1_048_576, .protocol = .kimi, .supports_reasoning = true, .support_efforts = &.{"max"}, .default_effort = "max" },
+ .{ .provider = "kimi", .name = "k3", .context = 1_048_576, .protocol = .kimi, .supports_reasoning = true, .support_efforts = &.{ "low", "high", "max" }, .default_effort = "high" },
.{ .provider = "kimi", .name = "kimi-for-coding", .context = 262_144, .protocol = .kimi, .supports_reasoning = true },
.{ .provider = "kimi", .name = "kimi-for-coding-highspeed", .context = 262_144, .protocol = .kimi, .supports_reasoning = true },
.{ .provider = "moonshot", .name = "kimi-latest", .context = 131_072 },
diff --git a/src/session_settings.zig b/src/session_settings.zig
index ef838c8d..df6fc0a8 100644
--- a/src/session_settings.zig
+++ b/src/session_settings.zig
@@ -17,6 +17,7 @@ const args = @import("args.zig");
const main_mod = @import("main.zig");
const agent_mod = @import("agent.zig");
const http = @import("http.zig");
+const http_stall = @import("http_stall.zig");
const ws = @import("ws.zig");
const agent_ws = @import("agent_ws.zig"); // codex_ws_idle_ms override (#codex-ws)
const agent_request = @import("agent_request.zig"); // GRAFF_REQ_STATS → g_req_stats (token-diet measurement)
@@ -71,7 +72,18 @@ pub fn applyEnvKnobs(arena: Allocator, environ_map: anytype) !void {
// unparseable or 0. A stall is never a user interrupt regardless of the value.
if (environ_map.get("GRAFF_STREAM_STALL_SECS")) |v| {
if (std.fmt.parseInt(u64, std.mem.trim(u8, v, " \t"), 10)) |secs| {
- if (secs > 0) http.stream_stall_ms = @min(secs, 86_400) * 1000; // clamp: <=1 day, no u64 overflow
+ if (secs > 0) {
+ http.stream_stall_ms = @min(secs, 86_400) * 1000; // clamp: <=1 day, no u64 overflow
+ http_stall.head_ceiling_ms = http.stream_stall_ms; // an explicit budget wins both regimes
+ }
+ } else |_| {}
+ }
+ // The pre-first-token ceiling alone (http_stall.head_ceiling_ms): for a
+ // provider that buffers a long reasoning phase in total silence BEFORE
+ // the first token. Seconds; ignored if unparseable or 0.
+ if (environ_map.get("GRAFF_STREAM_HEAD_STALL_SECS")) |v| {
+ if (std.fmt.parseInt(u64, std.mem.trim(u8, v, " \t"), 10)) |secs| {
+ if (secs > 0) http_stall.head_ceiling_ms = @min(secs, 86_400) * 1000;
} else |_| {}
}
// #codex-ws: GRAFF_CODEX_WS=off|0|false|no (case-insensitive, the
diff --git a/src/session_settings_tests.zig b/src/session_settings_tests.zig
index 6eff1cbb..593dbcab 100644
--- a/src/session_settings_tests.zig
+++ b/src/session_settings_tests.zig
@@ -36,6 +36,7 @@ const knobs = [_]Knob{
.{ .name = "GRAFF_FORCE_STALL_ALWAYS", .value = "1" },
.{ .name = "GRAFF_FORCE_DROP_ALWAYS", .value = "1" },
.{ .name = "GRAFF_STREAM_STALL_SECS", .value = "7" },
+ .{ .name = "GRAFF_STREAM_HEAD_STALL_SECS", .value = "9" },
.{ .name = "GRAFF_CODEX_WS", .value = "off" },
.{ .name = "GRAFF_CLOCK_SLEEP", .value = "1" },
.{ .name = "GRAFF_NO_LOCAL_TOOLS", .value = "1" },
diff --git a/src/session_start.zig b/src/session_start.zig
index e5ebf454..917c7984 100644
--- a/src/session_start.zig
+++ b/src/session_start.zig
@@ -434,6 +434,31 @@ pub fn probeLicensed(gpa: Allocator, io: Io) bool {
return skills.probeCodedbproLicensed(gpa, io);
}
+/// A licensed codedb-pro is IN CHARGE of reads/searches (its guard refuses
+/// the native codedb/read_file and points at these tools), which inverts the
+/// #416 deferral premise: this is not a server "most sessions never call" —
+/// the guard makes it mandatory, and the load_tool_schemas discovery dance is
+/// a measured ~2 model round-trips (~8-12s) per task on K3. Pin it eager.
+/// (#476 kept it deferred on a "zero discovery turns" claim; the benchmark
+/// traces show every code-reading run paying the dance.)
+pub fn pinCompanionEager(arena: Allocator) void {
+ if (mcp_schema_gate.pinnedEager("codedbpro")) return; // env/config already pinned
+ const gate = &mcp_schema_gate.g_policy;
+ const eager = arena.alloc([]const u8, gate.eager.len + 1) catch return;
+ @memcpy(eager[0..gate.eager.len], gate.eager);
+ eager[gate.eager.len] = "codedbpro";
+ gate.eager = eager;
+}
+
+/// The startup license probe plus its one side effect: a licensed companion
+/// is pinned eager so its full schemas ride the first catalog render instead
+/// of arriving via a load_tool_schemas discovery turn.
+pub fn probeLicensedPinningEager(gpa: Allocator, io: Io, arena: Allocator) bool {
+ const licensed = probeLicensed(gpa, io);
+ if (licensed) pinCompanionEager(arena);
+ return licensed;
+}
+
/// Companion auto-activation: if the metered code-intelligence companion
/// (codedb-pro, formerly muonry) is installed but nothing connected it (no
/// workspace .mcp.json entry, or consent declined), spawn it directly — a
@@ -503,3 +528,19 @@ test "core Smolify registration is offline and lazy" {
try std.testing.expectEqual(@as(usize, 13), try full.connectSmolify(true));
try std.testing.expectEqualStrings("/not-read-during-registration", full.servers[0].transport.http.oauth_home.?);
}
+
+test "a licensed companion is pinned eager, once, so no discovery round-trip is needed" {
+ const saved = mcp_schema_gate.g_policy;
+ defer mcp_schema_gate.g_policy = saved;
+ mcp_schema_gate.g_policy = .{};
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ try std.testing.expect(!mcp_schema_gate.pinnedEager("codedbpro"));
+ pinCompanionEager(arena);
+ try std.testing.expect(mcp_schema_gate.pinnedEager("codedbpro"));
+ // Idempotent, and an env/config pin is respected rather than duplicated.
+ pinCompanionEager(arena);
+ try std.testing.expectEqual(@as(usize, 1), mcp_schema_gate.g_policy.eager.len);
+}
diff --git a/src/tool_handle.zig b/src/tool_handle.zig
index ee5f0c4c..39919f9c 100644
--- a/src/tool_handle.zig
+++ b/src/tool_handle.zig
@@ -41,12 +41,17 @@ pub const handles_dir = ".graff/tool-results";
/// by this same number, so one result costs at most one threshold of context
/// whatever its size.
///
-/// 4 KiB is ~1k tokens: a real screenful of head — enough to see a stack trace,
-/// a file header, or the first rows of a table and decide what to ask for —
-/// while still a constant, bounded price. The caps it replaces were not
-/// constant: 128 KiB of bash stdout, 64 KiB of codedb output, and up to 136 KiB
-/// of a single result at send time.
-pub const default_threshold_bytes: usize = 4096;
+/// 16 KiB is ~4k tokens — still a constant, bounded price, but big enough that
+/// a typical search result or file read comes back INLINE. That matters more
+/// than the context it spends: every handle forces the model into a follow-up
+/// read, and a round-trip costs ~5-8s of model latency while the tokens cost
+/// cache-read prices on big-window models. Measured on K3 (1M window, 2026-08
+/// graff×kimi-cli benchmark): raising 4 KiB → 32 KiB cut runEval/providers
+/// wall time ~16% by removing 2-3 handle-chase round-trips per task; 16 KiB
+/// keeps half that win while staying safe on 32k-class windows. The caps this
+/// contract replaced were not constant: 128 KiB of bash stdout, 64 KiB of
+/// codedb output, and up to 136 KiB of a single result at send time.
+pub const default_threshold_bytes: usize = 16384;
pub var threshold_bytes: usize = default_threshold_bytes;
/// Ceiling on what one process may leave in `handles_dir`. Every handle is a