Skip to content

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

Python

feat: fold #677 teleport/GC and #675 DeepSeek lean bash into 282

Cursor Agent2211fc7ce3fe
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dd7dc6ee..e4f3a3de 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,9 +27,16 @@ current is part of cutting a release.
serializing `"tools":,` (0.0.280 HTTP 400).
- `#694`/`#697`/`#679` numbered records 0042/0043; those slots are
TUI claims and Pi SWE. Remapped to **0048–0050**.
+- `#677` / ADR 0051: `/teleport` restores a snapshot tar onto another
+ CLI backend; `/snapshot gc` keeps the newest n trees. Leftover of
+ `#554`. `#677` numbered this 0042; remapped (0042 is TUI claims).
+- `#675` / ADR 0052–0055: lean `-p` bounces a prose-only first "done";
+ short Codegraff flakes retry twice; DeepSeek family default low
+ sends `thinking.type=disabled`; lean bash auto-backgrounds at 15s.
+ `#675` numbered those 0048–0051; remapped off 282's 0048–0051.
- `#277` (Smolify OAuth) and `#200` (idle localhost) closed as
- abandoned vs tip; issues stay parked. Live leftovers: `#675`, `#677`.
-- Suite floor **1849** (was 1804). Scratch helpers live in
+ abandoned vs tip; issues stay parked.
+- Suite floor **1861** (was 1849). Scratch helpers live in
`agent_request_scratch.zig` so the request loop stays under 600.
- 12-task in-house remasure after #697 still unique vs grok / OpenCode:
**12/12 · 201s · 52 calls · $0.34** (`run-20260831-021035-composite`).
diff --git a/docs/adr/0037-experiment-pool-is-opt-in.md b/docs/adr/0037-experiment-pool-is-opt-in.md
index b1641137..0b77d701 100644
--- a/docs/adr/0037-experiment-pool-is-opt-in.md
+++ b/docs/adr/0037-experiment-pool-is-opt-in.md
@@ -22,4 +22,5 @@ path, branch, keep-reason, and diffstat. `graff worktree list` tags them
## Consequences
Seats are FIFO. A fourth child after `--experiment 3` uses normal isolation.
-Dependent pipeline stages still need #295. Docker snapshots stay #554.
+Dependent pipeline stages still need #295. Docker snapshots stay #554;
+teleport and snapshot GC are ADR 0051.
diff --git a/docs/adr/0051-sandbox-teleport-and-gc.md b/docs/adr/0051-sandbox-teleport-and-gc.md
new file mode 100644
index 00000000..d67440c3
--- /dev/null
+++ b/docs/adr/0051-sandbox-teleport-and-gc.md
@@ -0,0 +1,25 @@
+# 0051. Sandbox leftover of #554 is teleport plus snapshot GC
+
+Status: accepted 2026-08-29
+
+## Context
+
+#554 shipped the Docker CLI seam, `/snapshot`, and `/rewind <id>`. Two exo
+misses stayed open: restoring a `docker_image_tar` on a *different* backend,
+and deleting leftover snapshot trees. ADR 0037 still pointed experiment-pool
+Docker snapshots here.
+
+## Decision
+
+`/teleport <id> [docker|container]` restores a captured tar onto another CLI
+backend. Apple Container (`container`) is the second backend — same wire as
+`docker`, different `bin_name`. Dest defaults to `container` when the live
+backend is docker or nothing is attached. `/snapshot gc [n]` keeps the newest
+n snapshots (default 1) and deletes the rest. The conversation is never
+rewound. Missing CLIs stay explanations, not crashes.
+
+## Consequences
+
+Daytona is still not a backend. There is no `graff registry` client. A
+snapshot's kind stays `docker_image_tar` even when the dest CLI is
+`container`. Experiment-pool isolation is still opt-in worktrees (ADR 0037).
diff --git a/docs/adr/0052-lean-oneshot-bounces-prose.md b/docs/adr/0052-lean-oneshot-bounces-prose.md
new file mode 100644
index 00000000..3c8ebde1
--- /dev/null
+++ b/docs/adr/0052-lean-oneshot-bounces-prose.md
@@ -0,0 +1,63 @@
+# 0052. Lean `-p` bounces a first-turn prose-only "done"
+
+Status: accepted 2026-08-29
+
+#675 numbered this 0048. 282 already owns 0048 (HTTP client generations);
+this cut remaps the record.
+
+## Context
+
+ADR 0047 ran Codegraff `deepseek-v4-flash` SWE. Pi 5/6 in 492s. Graff
+2/6 in 199s. The three misses (`map-conflict`, `json-stream`,
+`validated`) were 4-second one-call replies (~1.5k in / ~160 out) that
+described a patch and never called a tool. An isolated retry of those
+three recovered two. Same miss as everyone on `label-sort`.
+
+Empty-completion retry only covers whitespace. A 158-token "I fixed
+it" ends the turn. Forcing `tool_choice=required` is already reserved
+for `--strict` / `--eval`; DeepSeek thinking mode has rejected it
+before. Do not steal Pi's four-tool catalog (ADR 0024).
+
+## Decision
+
+On lean `-p` (unattended, file tools advertised, not review, not a
+subagent), a first-turn completion that has text and zero tool calls
+is not done. Append one user bounce naming `read_file` / `edit_file` /
+`write_file` and re-open the loop. One bounce only (`model_calls == 1`).
+
+Lean intro also says a file change described in prose is not done.
+
+## Confirm — `deepseek-v4-flash` after bounce (`run-20260829-063114.jsonl`)
+
+Same `--suite swe -j 6` seat as ADR 0047.
+
+| harness | pass | wall (sum) | first | RSS | in | out | calls |
+|---|---:|---:|---:|---:|---:|---:|---:|
+| graff-dev | **4/6** | 250s | 0.03s | 91.2M | 170k | 25k | 26 |
+
+| task | before (0047) | after |
+|---|---|---|
+| cookie-store | ✓ 91s / 8 | ✓ 133s / 7 |
+| config-parse | ✓ 33s / 4 | ✗ 5s / 1* |
+| label-sort | ✗ 63s / 6 | ✗ 5s / 1* |
+| map-conflict | ✗ 4s / 1 | ✓ 20s / 5 |
+| json-stream | ✗ 4s / 1 | ✓ 65s / 8 |
+| validated | ✗ 4s / 1 | ✓ 20s / 4 |
+
+\*follow-up API error under `-j 6` (resp 110 B, ~450 ms). Isolated
+serial retry (`run-20260829-063451.jsonl`): `config-parse` ✓ 48s / 5,
+`label-sort` ✗ 62s / 5 (check, exit 0). Do not stitch that into 5/6.
+
+The confirm run used tools on the first call (lean intro). Bounce is
+the backstop when the model writes "I fixed it" with zero tools. No
+`fake_done` notes on this run.
+
+## Consequences
+
+- `graff -p "what is 2+2"` pays one extra call if the first reply has
+ no tool. Acceptable for a coding harness.
+- Interactive REPL / TUI / `--no-lean` / subagents are unchanged.
+- Revisit if a named flash model needs `tool_choice=required` on the
+ first call; do not restore a global force.
+- Follow-up `-j 6` flakes and the OpenCode A/B are ADR 0053 (graff
+ 5/6 in 362s after the retry).
diff --git a/docs/adr/0053-codegraff-flake-retry-opencode.md b/docs/adr/0053-codegraff-flake-retry-opencode.md
new file mode 100644
index 00000000..e939a41d
--- /dev/null
+++ b/docs/adr/0053-codegraff-flake-retry-opencode.md
@@ -0,0 +1,56 @@
+# 0053. Retry short Codegraff follow-up flakes; OpenCode A/B on the same seat
+
+Status: accepted 2026-08-29
+
+#675 numbered this 0049. 282 already owns 0049 (session branches);
+this cut remaps the record.
+
+## Context
+
+ADR 0052 bounced lean `-p` prose-only first turns. DeepSeek flash SWE
+moved 2/6 → 4/6. The leftover miss besides `label-sort` was
+`config-parse` dying in ~5s after a successful 4-tool first batch: a
+~110-byte / ~450 ms `api_error` under `-j 6`. Isolated serial retry
+passed. Overload / `server_error` needles did not match. A missing
+`error.message` becomes `unknown error` (`apiErrorMessage`).
+
+Same-seat OpenCode was missing from `graff-evals`. Fair A/B is the
+same `CODEGRAFF_API_KEY` → `gateway.codegraff.com/v1`. Do not steal
+Pi's four-tool catalog (ADR 0024) or OpenCode's ~1G heap.
+
+## Decision
+
+- Treat short generic envelopes (`unknown error`, `Internal Server
+ Error`, empty `api_error`) and tiny unparseable bodies (≤256 B) as
+ bounded retries (2). `invalid_request` / auth / quota / not-found
+ stay fail-fast.
+- Add `opencode-codegraff` (`opencode run --auto --format json` +
+ tracked `opencode-codegraff.json`). Do not commit OpenCode auth.
+- Eval failures keep a 400-byte `stderr_tail` so the next envelope is
+ visible.
+
+## Confirm — `deepseek-v4-flash` (`run-20260829-072310` + `072758`)
+
+Same `--suite swe -j 6` seat as ADR 0047 / 0052.
+
+| harness | pass | wall (sum) | first | RSS | in | out | calls |
+|---|---:|---:|---:|---:|---:|---:|---:|
+| graff-dev (`072758`) | **5/6** | 362s | 0.05s | 91.1M | 346k | 38k | 38 |
+| opencode-codegraff (`072310`) | **5/6** | 261s | 3.6s | 1064M | 61k | 8k | 36 |
+| pi-codegraff (0047) | **5/6** | 492s | 0.7s | 186M | 480k | 56k | 46 |
+
+The parallel A/B (`072310`) still had graff 4/6 (`config-parse` 5s /
+1). After the `unknown error` / tiny-body retry, graff `072758` is
+5/6; `config-parse` ✓ 30s / 4. Same `label-sort` miss on all three
+harnesses. Do not stitch the two graff suite scores.
+
+OpenCode `first` is the first JSONL event (~3.6s), not TUI paint.
+Graff `first` is the stderr `calling` line. Do not treat 0.05s as a
+TUI steal.
+
+## Consequences
+
+- Score is now tied with Pi and OpenCode. Wall is not: OpenCode 261s
+ vs graff 362s is mostly `cookie-store` variance (89s on `072310`,
+ 185s on `072758`). RSS stays ~91M; do not take OpenCode's heap.
+- Revisit if a named 400 should retry; do not retry `invalid_request`.
diff --git a/docs/adr/0054-deepseek-thinking-disabled-at-low.md b/docs/adr/0054-deepseek-thinking-disabled-at-low.md
new file mode 100644
index 00000000..2b599274
--- /dev/null
+++ b/docs/adr/0054-deepseek-thinking-disabled-at-low.md
@@ -0,0 +1,51 @@
+# 0054. DeepSeek flash default is thinking off
+
+Status: accepted 2026-08-29
+
+#675 numbered this 0050. 282 already owns 0050 (warmed TLS);
+this cut remaps the record.
+
+## Context
+
+ADR 0046 maps flash default `.medium` to `reasoning_effort: low`.
+That stops GLM/Gemini thinking novels. DeepSeek V4 is different:
+thinking is **on at high** unless the request carries
+`thinking: {type: disabled}`. Official docs: `low` still thinks;
+it only lowers CoT. `none` is a 400 on Chat Completions.
+
+DeepSeek flash SWE after ADR 0053: graff **5/6 in 362s** vs OpenCode
+**5/6 in 261s**. The 100s gap is not catalog or heap. cookie-store
+call 2 was **75s / 1.9MB** of `reasoning_content` at `low`. An earlier
+A/B without that dump was 89s / 9 calls (OpenCode 76s / 9). Pi sets
+`reasoning: false`. OpenCode omits the field (default = thinking on);
+it still won on a no-dump draw. Do not steal Pi's four-tool catalog
+or OpenCode's ~1G heap.
+
+## Decision
+
+DeepSeek family (native `deepseek`, or a `deepseek*` model on
+codegraff/fireworks) sends `thinking.type=disabled` when the wire
+effort is `low` (flash default). `/effort high` (and any non-low)
+sends `type=enabled` plus that effort. GLM keeps `low` only —
+`type=disabled` still thinks there (ADR 0046). Do not shrink the
+keep-list.
+
+## Consequences
+
+- Flash SWE wall is generation without CoT dumps, not Zig vs JS.
+- `/effort` remains the only way thinking comes back (no auto-flip).
+- Revisit if a named DeepSeek flash pin needs default thinking.
+
+## Confirm (2026-08-29)
+
+Live `deepseek-v4-flash` pong on `gateway.codegraff.com`:
+
+| knob | reasoning_tokens | rc_len |
+|---|---:|---:|
+| omit | 21 | 79 |
+| `reasoning_effort=low` | 31 | 112 |
+| `thinking.type=disabled` | **0** | **0** |
+| disabled + low | **0** | **0** |
+| enabled + high | 29 | 117 |
+
+`--suite swe -j 6` after this cut (`074142`): 4/6 in **210s** / 91M (cookie-store 83s / 14, no 1.9MB dump). `config-parse` was the 110-byte “Body must be valid JSON” flake (retry in the same branch). After that retry (`074659`): **5/6 in 353s** — leftover wall was hung bash (ADR 0055), not CoT. Same `label-sort` miss. Later 0-token / balance-reservation runs are burnt gateway, not a model result. Do not steal Pi’s catalog.
diff --git a/docs/adr/0055-lean-oneshot-bash-15s.md b/docs/adr/0055-lean-oneshot-bash-15s.md
new file mode 100644
index 00000000..6bbbff0a
--- /dev/null
+++ b/docs/adr/0055-lean-oneshot-bash-15s.md
@@ -0,0 +1,35 @@
+# 0055. Lean `-p` bash auto-backgrounds at 15s
+
+Status: accepted 2026-08-29
+
+#675 numbered this 0051. 282 already owns 0051 (sandbox teleport / GC);
+this cut remaps the record.
+
+## Context
+
+ADR 0026 waits 120s before promoting root foreground bash: a human
+may be watching a long compile. Lean `-p` has no human. After ADR
+0054 killed DeepSeek CoT dumps, SWE wall was **5/6 in 353s** —
+`json-stream` sat **120s** on `python3 test_json_stream.py`,
+`cookie-store` **71s** on another hang. API calls were 2–13s.
+OpenCode’s 261s lead was those waits, not catalog or heap.
+
+## Decision
+
+Unattended + lean (`-p` default) auto-backgrounds at **15s**. The
+process is not killed (ADR 0026). An explicit `timeout` still wins.
+Interactive / `--no-lean` stay 120s. Do not steal Pi’s catalog.
+
+## Consequences
+
+A hung test returns a job id in 15s; the model can edit or
+`bash_kill`. A 20-minute compile on `-p` also backgrounds at 15s —
+`bash_output(wait_ms>0)` still waits for exit (ADR 0010).
+
+## Confirm (2026-08-29)
+
+`run-20260829-075402`, thinking off + 15s bash. cookie-store **30s**
+(was 114s / 71s hang). json-stream **22s** (was 155s / 120s hang).
+Suite 4/6 in **143s** / 91M — `validated` died on a concurrent
+reservation / empty balance, not the wait. Same `label-sort` miss.
+0-token follow-ups after that are burnt gateway. Do not stitch.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index cb7e3da6..5bd49c01 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -61,6 +61,11 @@ record only when you need the evidence or the edge cases.
| [0048](0048-model-http-client-recovery-uses-generations.md) | Model HTTP calls lease a recoverable client generation; request-construction TLS failure rotates safely without deinitializing in-flight users. |
| [0049](0049-resume-branches-have-independent-durable-identity.md) | `--resume SOURCE --branch DEST` clones provider history and peer cursor state once; every later save belongs only to DEST. |
| [0050](0050-reuse-warmed-tls-on-known-networks.md) | Reuse warmed TLS: MCP probe/initialized stay on the persistent HTTP client; WSS CA is scanned once per process; WS→SSE keeps the prewarmed pool; MCP HTTP accepts gzip. |
+| [0051](0051-sandbox-teleport-and-gc.md) | `/teleport` restores a snapshot tar onto another CLI backend; `/snapshot gc` keeps the newest n trees. |
+| [0052](0052-lean-oneshot-bounces-prose.md) | Lean `-p` bounces a first-turn prose-only "done"; one user note naming file tools, then re-open. |
+| [0053](0053-codegraff-flake-retry-opencode.md) | Retry short Codegraff follow-up flakes (2); `opencode-codegraff` A/B on the same seat. Auth/quota stay fail-fast. |
+| [0054](0054-deepseek-thinking-disabled-at-low.md) | DeepSeek family default low sends `thinking.type=disabled`; `/effort high` still thinks. GLM stays low-only. |
+| [0055](0055-lean-oneshot-bash-15s.md) | Lean `-p` bash auto-backgrounds at 15s; interactive / `--no-lean` stay 120s (ADR 0026). |
## When to write one
diff --git a/docs/releases/v0.0.282.md b/docs/releases/v0.0.282.md
index 42716c78..1c445f38 100644
--- a/docs/releases/v0.0.282.md
+++ b/docs/releases/v0.0.282.md
@@ -96,21 +96,49 @@ tokens / list$ / RSS (`run-20260831-021035-composite`). Calls stayed
one model-variance retry of `atomic-symlink-write`. `peer-resume`
(the #697-shaped fixture) passed. First-token is not a named win.
+## Sandbox teleport and snapshot GC (ADR 0051 / #677)
+
+Leftover of `#554`. `/teleport <id> [docker|container]` restores a
+captured `docker_image_tar` onto another CLI backend. Apple Container
+is the second backend (same wire, different `bin_name`). Dest defaults
+to `container` when the live backend is docker or nothing is attached.
+`/snapshot gc [n]` keeps the newest n snapshot trees (default 1).
+The conversation is never rewound. Missing CLIs explain, they do not
+crash. `#677` numbered this 0042; remapped to **0051**.
+
+## DeepSeek thinking-off and lean 15s bash (ADR 0052–0055 / #675)
+
+Hillclimb of DeepSeek flash SWE on the Codegraff seat. Do not steal
+Pi's four-tool catalog or OpenCode's ~1G heap.
+
+1. Lean `-p` bounces a first-turn prose-only "done" (ADR 0052).
+2. Short Codegraff follow-up flakes retry twice (ADR 0053), including
+ the 110-byte `invalid_request_error` / "Body must be valid JSON".
+ Auth / quota / a real invalid prompt stay fail-fast.
+ `opencode-codegraff` is the same-seat OpenCode A/B harness.
+3. DeepSeek family default low sends `thinking.type=disabled`
+ (ADR 0054). `/effort high` still thinks. GLM stays `low`-only.
+4. Lean `-p` bash auto-backgrounds at 15s (ADR 0055). Interactive
+ stays 120s (ADR 0026).
+
+`#675` numbered these 0048–0051. 282 already owns 0048–0051; remapped
+to **0052–0055**. Keep-alive-only bodies share the short-flake retry
+in `agent_gateway_retry.zig` so 282's request-scratch split stays.
+
## Parked
`#277` (Streamable HTTP OAuth / Smolify) and `#200` (idle localhost
servers) were closed as abandoned vs tip; the issues stay inventory in
[yxlyx-leftovers.md](../yxlyx-leftovers.md). Smolify is not a reserved
-core MCP. Live leftovers that still apply are `#675` (DeepSeek
-thinking-off / 15s lean bash) and `#677` (`/teleport` + snapshot GC).
+core MCP.
## Tests
-This cut raises the release-cut floor to **1849** (slack 25). Paste
+This cut raises the release-cut floor to **1861** (slack 25). Paste
spans, Codex WS errors, HTTP generations, session branches, MCP
-TLS-reuse, and empty-catalog omit tests land on top of the 1804
-floor from 281. The suite count is re-ratcheted after
-`zig build test` on this revision.
+TLS-reuse, empty-catalog omit, teleport/GC, and DeepSeek/lean-bash
+tests land on top of the 1804 floor from 281. The suite count is
+re-ratcheted after `zig build test` on this revision.
`agent_request.zig` split request-scratch helpers into
`agent_request_scratch.zig` so the Codex WS merge stays under the
600-line ceiling.
diff --git a/docs/yxlyx-leftovers.md b/docs/yxlyx-leftovers.md
index a2e80cf5..76c4b3db 100644
--- a/docs/yxlyx-leftovers.md
+++ b/docs/yxlyx-leftovers.md
@@ -6,7 +6,9 @@ Landed on [v0.0.282](releases/v0.0.282.md): `#674` atomic paste spans,
`#693` Codex WS `type:error`, `#694` HTTP client generations (ADR 0048),
`#697` clone-on-write session branches (ADR 0049; `#698` was a yxlyx reopen
of the same head and is closed as duplicate), `#679` MCP TLS reuse
-(ADR 0050), `#695` omit an empty tool catalog. Still parked below.
+(ADR 0050), `#695` omit an empty tool catalog, `#677` `/teleport` +
+`/snapshot gc` (ADR 0051), `#675` DeepSeek thinking-off / lean 15s bash
+(ADR 0052–0055). Still parked below.
| Issue | In this repo today | This cut |
| --- | --- | --- |
diff --git a/graff-evals/README.md b/graff-evals/README.md
index e27b6acd..a287a166 100644
--- a/graff-evals/README.md
+++ b/graff-evals/README.md
@@ -32,6 +32,8 @@ harness under test spends model calls.
CODEGRAFF_API_KEY=cg_sk_… ./run.py --suite swe --harness graff-dev,pi-codegraff --model glm-5.3-flash -j 6
# same seat, other models (ADR 0047): deepseek-v4-flash, gemini-3.7-flash, kimi-k2.6
CODEGRAFF_API_KEY=cg_sk_… ./run.py --suite swe --harness graff-dev,pi-codegraff --model deepseek-v4-flash -j 6
+# same seat, OpenCode vs graff (ADR 0053; needs `opencode` on PATH):
+CODEGRAFF_API_KEY=cg_sk_… ./run.py --suite swe --harness graff-dev,opencode-codegraff --model deepseek-v4-flash -j 6
# multi-harness in-house PR suite (OpenCode needs --dir; see harnesses.json):
./run.py --suite inhouse --harness graff-dev,grok,opencode --model grok-4.6 -j 1
```
diff --git a/graff-evals/harnesses.json b/graff-evals/harnesses.json
index b17c0caa..93575b24 100644
--- a/graff-evals/harnesses.json
+++ b/graff-evals/harnesses.json
@@ -149,6 +149,14 @@
"default_model": "gemini-3.7-flash",
"note": "uses ~/.pi/agent/models.json provider codegraff → gateway.codegraff.com; Gemini tool loops need the codegraff-gemini-echo extension"
},
+ "opencode-codegraff": {
+ "cmd": ["{repo}/graff-evals/opencode-codegraff.sh", "-m", "codegraff/{model}", "--dir", "{sandbox}", "{prompt}"],
+ "answer": "opencode-json",
+ "usage": "opencode-json",
+ "capabilities": [],
+ "default_model": "deepseek-v4-flash",
+ "note": "OpenCode on the Codegraff gateway (same CODEGRAFF_API_KEY seat as graff-dev / pi-codegraff). Wrapper needs `opencode` on PATH (~/.opencode/bin)."
+ },
"pi-xai": {
"cmd": ["{repo}/graff-evals/pi-xai.sh", "-p", "--mode", "json", "--provider", "xai", "--model", "{model}", "--no-session", "{prompt}"],
"answer": "pi-json",
diff --git a/graff-evals/opencode-codegraff.json b/graff-evals/opencode-codegraff.json
new file mode 100644
index 00000000..bb4dd642
--- /dev/null
+++ b/graff-evals/opencode-codegraff.json
@@ -0,0 +1,31 @@
+{
+ "$schema": "https://opencode.ai/config.json",
+ "model": "codegraff/deepseek-v4-flash",
+ "provider": {
+ "codegraff": {
+ "npm": "@ai-sdk/openai-compatible",
+ "name": "Codegraff",
+ "options": {
+ "baseURL": "https://gateway.codegraff.com/v1",
+ "apiKey": "{env:CODEGRAFF_API_KEY}",
+ "headers": {
+ "User-Agent": "Mozilla/5.0 (compatible; graff-evals/1.0)"
+ }
+ },
+ "models": {
+ "deepseek-v4-flash": {
+ "name": "DeepSeek V4 Flash"
+ },
+ "glm-5.3-flash": {
+ "name": "GLM 5.3 Flash"
+ },
+ "gemini-3.7-flash": {
+ "name": "Gemini 3.7 Flash"
+ },
+ "kimi-k2.6": {
+ "name": "Kimi K2.6"
+ }
+ }
+ }
+ }
+}
diff --git a/graff-evals/opencode-codegraff.sh b/graff-evals/opencode-codegraff.sh
new file mode 100755
index 00000000..e54094d0
--- /dev/null
+++ b/graff-evals/opencode-codegraff.sh
@@ -0,0 +1,17 @@
+#!/bin/sh
+# Drive OpenCode on the Codegraff gateway (same seat as graff-dev / pi-codegraff).
+set -e
+root=$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)
+export PATH="${HOME}/.opencode/bin:${PATH}"
+export OPENCODE_CONFIG="${OPENCODE_CONFIG:-$root/graff-evals/opencode-codegraff.json}"
+export OPENCODE_DISABLE_AUTOUPDATE=1
+export OPENCODE_DISABLE_DEFAULT_PLUGINS=1
+if [ -z "${CODEGRAFF_API_KEY:-}" ]; then
+ echo "opencode-codegraff: CODEGRAFF_API_KEY is unset" >&2
+ exit 127
+fi
+if ! command -v opencode >/dev/null 2>&1; then
+ echo "opencode-codegraff: opencode not found (https://opencode.ai/docs)" >&2
+ exit 127
+fi
+exec opencode run --auto --format json --pure "$@"
diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.json
index 4ad0369e..84dd57a9 100644
--- a/scripts/eval/tier1-manifest.json
+++ b/scripts/eval/tier1-manifest.json
@@ -15,7 +15,7 @@
"src/repl.zig",
"TUI/root.zig"
],
- "test_count_baseline": 1849,
+ "test_count_baseline": 1861,
"test_count_slack": 25,
"required_invariants": [
{
diff --git a/src/agent_empty_completion.zig b/src/agent_empty_completion.zig
index 987b4402..8e5743f4 100644
--- a/src/agent_empty_completion.zig
+++ b/src/agent_empty_completion.zig
@@ -1,14 +1,18 @@
-//! Degenerate-completion policy for Agent.runTurn. A provider completion can
-//! arrive with no text, no tool calls, and no non-"stop" finish reason —
-//! observed live on the chat wire as `content: null`, no `tool_calls`
-//! (mid-task, right after a successful write_file). The step functions then
-//! return "" and the turn ends silently: the session sits there looking dead.
-//! Instead, rewind the history the step function just appended and re-ask,
-//! bounded per turn so a wedged provider can't spin up unbounded spend.
+//! Degenerate-completion policy for Agent.runTurn.
+//!
+//! 1. Empty / whitespace-only completions (no tool calls) used to end the
+//! turn silently. Rewind and re-ask, bounded.
+//! 2. Lean `-p` text-only first completions (DeepSeek flash SWE): the model
+//! describes a patch and stops. That is not done — bounce once with a
+//! user note (ADR 0052). Do not steal Pi's four-tool catalog (ADR 0024 / 0047).
+//!
//! Split from agent.zig (600-line goal); wired only in runTurn.
const std = @import("std");
const Agent = @import("agent.zig").Agent;
+const main_mod = @import("main.zig");
+const no_local_tools = @import("no_local_tools.zig");
+const messages = @import("messages.zig");
/// Retries allowed per turn for consecutive degenerate completions.
pub const max_consecutive: u8 = 2;
@@ -21,17 +25,30 @@ pub fn shouldRetry(final_text: []const u8, retries: u8) bool {
return std.mem.trim(u8, final_text, " \t\r\n").len == 0;
}
-/// Handle a degenerate completion inside runTurn: spend one bounded retry by
-/// rewinding the history the step function just appended (clamped — an
-/// in-request compaction may already have shrunk it) and re-opening the WS
-/// chain, whose watermark is keyed to the dropped messages. Returns true when
-/// the caller should `continue` the loop.
+/// Lean `-p` described a fix and never called a tool. One bounce.
+pub const bounce_note = "You described a change but did not call any tool. Inspect and edit the files with read_file / edit_file / write_file; do not claim the tree is already updated.";
+
+pub fn shouldBounce(unattended: bool, lean: bool, text_only: bool, review: bool, sub: bool, tool_calls: u64, model_calls: u64, final_text: []const u8) bool {
+ if (!unattended or !lean or text_only or review or sub) return false;
+ if (tool_calls != 0 or model_calls != 1) return false;
+ return std.mem.trim(u8, final_text, " \t\r\n").len > 0;
+}
+
+/// Handle a degenerate completion inside runTurn. Returns true when the
+/// caller should `continue` the loop.
pub fn handle(self: *Agent, final_text: []const u8, hist_len: usize) !bool {
- if (!shouldRetry(final_text, self.empty_completion_retries)) return false;
- self.empty_completion_retries += 1;
- self.closeCodexWs();
- self.messages.shrinkRetainingCapacity(@min(hist_len, self.messages.items.len));
- try self.say("[model returned an empty completion — retrying ({d}/{d})]\n", .{ self.empty_completion_retries, max_consecutive });
+ if (shouldRetry(final_text, self.empty_completion_retries)) {
+ self.empty_completion_retries += 1;
+ self.closeCodexWs();
+ self.messages.shrinkRetainingCapacity(@min(hist_len, self.messages.items.len));
+ try self.say("[model returned an empty completion — retrying ({d}/{d})]\n", .{ self.empty_completion_retries, max_consecutive });
+ return true;
+ }
+ if (!shouldBounce(main_mod.unattended, no_local_tools.lean, self.text_only, self.review_mode, self.sub, self.tool_calls_this_turn, self.model_calls_this_turn, final_text))
+ return false;
+ try self.messages.append(try messages.textMessage(self.arena, "user", bounce_note));
+ try self.say("[described a change with no tool call — asking once more]\n", .{});
+ if (self.tracer) |tr| tr.note("fake_done", "lean -p text-only; bounced");
return true;
}
@@ -47,3 +64,20 @@ test "whitespace-only completions are degenerate, real text never is" {
try std.testing.expect(!shouldRetry("done", 0));
try std.testing.expect(!shouldRetry("<|eos|>", 0));
}
+
+test "lean -p text-only first completion bounces once" {
+ try std.testing.expect(shouldBounce(true, true, false, false, false, 0, 1, "I fixed validated.py"));
+ try std.testing.expect(!shouldBounce(true, true, false, false, false, 0, 2, "I fixed validated.py"));
+ try std.testing.expect(!shouldBounce(true, true, false, false, false, 1, 1, "I fixed validated.py"));
+ try std.testing.expect(!shouldBounce(false, true, false, false, false, 0, 1, "I fixed validated.py"));
+ try std.testing.expect(!shouldBounce(true, false, false, false, false, 0, 1, "I fixed validated.py"));
+ try std.testing.expect(!shouldBounce(true, true, true, false, false, 0, 1, "I fixed validated.py"));
+ try std.testing.expect(!shouldBounce(true, true, false, true, false, 0, 1, "I fixed validated.py"));
+ try std.testing.expect(!shouldBounce(true, true, false, false, true, 0, 1, "I fixed validated.py"));
+ try std.testing.expect(!shouldBounce(true, true, false, false, false, 0, 1, " "));
+}
+
+test "bounce note names the file tools" {
+ try std.testing.expect(std.mem.indexOf(u8, bounce_note, "edit_file") != null);
+ try std.testing.expect(std.mem.indexOf(u8, bounce_note, "write_file") != null);
+}
diff --git a/src/agent_gateway_retry.zig b/src/agent_gateway_retry.zig
index a6ab0f04..71eb32ae 100644
--- a/src/agent_gateway_retry.zig
+++ b/src/agent_gateway_retry.zig
@@ -10,6 +10,12 @@
//! history it stays a fail-fast 400, exactly as before.
//! 2. Retry trace notes carry the agent label, so a 5xx can be attributed to
//! the subagent that drew it without ms-arithmetic across api spans.
+//! 3. A short generic `api_error` / "Internal Server Error" / empty envelope
+//! (the DeepSeek flash `-j 6` follow-up flake) is retried bounded. The
+//! same 110-byte / ~450ms follow-up also arrives as `invalid_request_error`
+//! / "Body must be valid JSON" (our stringify just succeeded on call 1).
+//! That phrase is a flake; auth / quota / a real invalid prompt stay
+//! fail-fast.
const std = @import("std");
const Agent = @import("agent.zig").Agent;
@@ -72,14 +78,70 @@ pub fn noteFlake(self: *Agent, state: *GatewayRetryState, err: anyerror) void {
if (err == error.Timeout) state.transport_timeouts += 1;
}
-/// One gate for the envelope-fatal paths: the pre-existing transient
-/// server-overload retry first (unchanged semantics), then the bounded
-/// gateway-artifact retry when this request already endured >=2 timeouts.
+/// One gate for the envelope-fatal paths: overload first, then a short
+/// Codegraff follow-up flake (ADR 0053 DeepSeek `-j 6` 110-byte / ~450ms)
+/// `api_error`), then the timeout-gated body-parse retry.
pub fn afterServerErrorOrParseReject(self: *Agent, etype: []const u8, code: ?[]const u8, msg: []const u8, server_retries: *usize, state: *GatewayRetryState) !bool {
if (try policy.retryTransientServerError(self, etype, code, msg, server_retries)) return true;
+ if (try retryShortGatewayFlake(self, etype, code, msg, server_retries)) return true;
return retryBodyParseAfterTimeouts(self, msg, state);
}
+pub const max_short_flake_retries: usize = 2;
+
+/// Tiny / generic envelopes that are not a real client bug. The DeepSeek
+/// SWE `-j 6` follow-up was ~110 bytes, ~450 ms, `is_error`, no
+/// "overloaded" / "server_error" needle — isolated serial retry passed.
+/// Do not treat invalid_request / auth / quota as a flake.
+pub fn isShortGatewayFlake(etype: []const u8, code: ?[]const u8, msg: []const u8) bool {
+ // Gateway 110-byte follow-up. etype is often invalid_request_error, which
+ // would otherwise hard-fail on the "invalid" needle. Auth/quota still die.
+ if (isBodyParseRejection(msg)) return true;
+ const hard = [_][]const u8{ "invalid", "authentication", "unauthorized", "insufficient", "quota", "permission", "tool_choice", "not found" };
+ for (hard) |n| {
+ if (util.indexOfIgnoreCase(etype, n) != null) return false;
+ if (util.indexOfIgnoreCase(msg, n) != null) return false;
+ if (code) |c| if (util.indexOfIgnoreCase(c, n) != null) return false;
+ }
+ const flakes = [_][]const u8{ "internal", "try again", "temporarily", "unavailable", "bad gateway", "upstream", "capacity", "unknown error", "something went wrong", "an error occurred" };
+ for (flakes) |n| {
+ if (util.indexOfIgnoreCase(etype, n) != null) return true;
+ if (util.indexOfIgnoreCase(msg, n) != null) return true;
+ if (code) |c| if (util.indexOfIgnoreCase(c, n) != null) return true;
+ }
+ const generic = etype.len == 0 or std.mem.eql(u8, etype, "error") or std.mem.eql(u8, etype, "api_error");
+ return generic and std.mem.trim(u8, msg, " \t\r\n").len == 0;
+}
+
+/// Unparseable body that is keep-alive comments or a tiny truncated
+/// payload (the 110-byte follow-up). Bounded. Real JSON error envelopes
+/// do not reach this — they go through `afterServerErrorOrParseReject`.
+pub fn retryDegenerateBody(self: *Agent, body: []const u8, retries: *usize) !bool {
+ const tiny = body.len > 0 and body.len <= 256;
+ if (!policy.sseKeepAliveOnly(body) and !tiny) return false;
+ if (retries.* >= max_short_flake_retries) return false;
+ retries.* += 1;
+ self.partial_text.clearRetainingCapacity();
+ const delay_ms = RetryPlan.delayMs(true, retries.* - 1);
+ const what: []const u8 = if (policy.sseKeepAliveOnly(body)) "keep-alive only, no tokens" else "truncated gateway body";
+ try self.say("[provider queued the request ({s}) — retrying in {d}s ({d}/{d})]\n", .{ what, delay_ms / 1000, retries.*, max_short_flake_retries });
+ if (self.tracer) |tr| tr.note("retry", what);
+ self.sleepInterruptible(delay_ms) catch return error.Interrupted;
+ return true;
+}
+
+fn retryShortGatewayFlake(self: *Agent, etype: []const u8, code: ?[]const u8, msg: []const u8, retries: *usize) !bool {
+ if (!isShortGatewayFlake(etype, code, msg)) return false;
+ if (retries.* >= max_short_flake_retries) return false;
+ retries.* += 1;
+ self.partial_text.clearRetainingCapacity();
+ const delay_ms = RetryPlan.delayMs(true, retries.* - 1);
+ try self.say("[gateway flake — retrying in {d}s ({d}/{d})]\n", .{ delay_ms / 1000, retries.*, max_short_flake_retries });
+ if (self.tracer) |tr| tr.note("retry", "short gateway flake");
+ self.sleepInterruptible(delay_ms) catch return error.Interrupted;
+ return true;
+}
+
/// The gate on the Agent: announce, trace, back off (1·2s — the gateway just
/// answered, give it a beat), clear partial text for a fresh re-stream, and
/// tell the caller to `continue`. Esc during the backoff still propagates.
@@ -117,3 +179,19 @@ test "shouldRetryBodyParseAfterTimeouts (#gateway-artifact): timeout history gat
// an unrelated message never retries, however many timeouts preceded it
try std.testing.expect(!shouldRetryBodyParseAfterTimeouts("quota exceeded", 5, 0));
}
+
+test "isShortGatewayFlake: internal/empty api_error retry; invalid/auth/quota do not" {
+ try std.testing.expect(isShortGatewayFlake("api_error", null, "Internal Server Error"));
+ try std.testing.expect(isShortGatewayFlake("api_error", null, ""));
+ try std.testing.expect(isShortGatewayFlake("error", null, " "));
+ try std.testing.expect(isShortGatewayFlake("", null, "unknown error"));
+ try std.testing.expect(isShortGatewayFlake("", null, "upstream connect error"));
+ try std.testing.expect(!isShortGatewayFlake("invalid_request_error", null, "invalid prompt"));
+ try std.testing.expect(!isShortGatewayFlake("api_error", null, "invalid tool_choice"));
+ try std.testing.expect(!isShortGatewayFlake("authentication_error", null, "invalid api key"));
+ try std.testing.expect(!isShortGatewayFlake("insufficient_quota", null, "You exceeded your current quota"));
+ try std.testing.expect(!isShortGatewayFlake("api_error", null, "model not found"));
+ try std.testing.expect(isShortGatewayFlake("invalid_request_error", null, "Body must be valid JSON"));
+ try std.testing.expect(isShortGatewayFlake("api_error", null, "Malformed JSON in request body"));
+ try std.testing.expect(!isShortGatewayFlake("invalid_request_error", null, "invalid prompt"));
+}
diff --git a/src/agent_request_body.zig b/src/agent_request_body.zig
index de282796..091d837c 100644
--- a/src/agent_request_body.zig
+++ b/src/agent_request_body.zig
@@ -176,7 +176,7 @@ pub fn buildBody(self: *Agent, tools_in: ?[]const u8, force_tool: bool, stream:
try s.objectField("prompt_cache_key");
try s.write(http_headers.requestCacheKey(self.io, self.label, self, self.provider.id, &ckbuf));
// reasoning_effort (codegraff/deepseek/zai) + Z.AI thinking + Vercel reasoning.effort.
- try @import("zai_wire.zig").writeChatExtras(&s, self.provider.id, self.sendReasoningEffort(), @import("effort_route.zig").wireEffort(self.provider.model, @tagName(self.reasoning)));
+ try @import("zai_wire.zig").writeChatExtras(&s, self.provider.id, self.provider.model, self.sendReasoningEffort(), @import("effort_route.zig").wireEffort(self.provider.model, @tagName(self.reasoning)));
// --output-schema: structured outputs (xAI docs' response_format).
// A provider that rejected json_schema (#543, deepseek) degrades
// dsh-style: the tools-off formatting turn carries the schema as a
diff --git a/src/agent_request_scratch.zig b/src/agent_request_scratch.zig
index c1eb1c39..0f0ceb98 100644
--- a/src/agent_request_scratch.zig
+++ b/src/agent_request_scratch.zig
@@ -6,13 +6,8 @@
const std = @import("std");
const Agent = @import("agent.zig").Agent;
-const policy = @import("agent_request_policy.zig");
-const http = @import("http.zig");
-const RetryPlan = http.RetryPlan;
const run_budget_mod = @import("run_budget.zig");
-const max_server_retries: usize = 3;
-
/// Keep the normal request hot path allocation-free while avoiding a permanent
/// RSS high-water mark after one anomalously large stream. Small scratch arenas
/// retain their pages for the next request; large ones return all pages to the
@@ -38,14 +33,7 @@ pub fn showRecoveredTransportRetry(kind: run_budget_mod.CallKind) bool {
/// means the gateway queued us and never produced tokens — back off and re-ask
/// like a 5xx instead of dying on an "unparseable" JSON parse.
pub fn retryKeepAliveOnly(self: *Agent, body: []const u8, retries: *usize) !bool {
- if (!policy.sseKeepAliveOnly(body)) return false;
- if (retries.* >= max_server_retries) return false;
- retries.* += 1;
- self.partial_text.clearRetainingCapacity();
- const delay_ms = RetryPlan.delayMs(true, retries.* - 1); // 1·2·4s
- try self.say("[provider queued the request (keep-alive only, no tokens) — retrying in {d}s ({d}/{d})]\n", .{ delay_ms / 1000, retries.*, max_server_retries });
- self.sleepInterruptible(delay_ms) catch return error.Interrupted;
- return true;
+ return @import("agent_gateway_retry.zig").retryDegenerateBody(self, body, retries);
}
test "recovered recap transport retries stay out of normal REPL output" {
diff --git a/src/cli.zig b/src/cli.zig
index 39bf3d02..0dcb2da9 100644
--- a/src/cli.zig
+++ b/src/cli.zig
@@ -27,6 +27,8 @@ pub const changelog_text =
\\ • request-construction TLS failure rotates a leased HTTP client generation (ADR 0048)
\\ • --resume SOURCE --branch DEST is clone-on-write (ADR 0049)
\\ • MCP HTTP/WSS reuse warmed TLS; catalogs can arrive gzip (ADR 0050)
+ \\ • /teleport + /snapshot gc (ADR 0051); DeepSeek thinking off at low (ADR 0054)
+ \\ • lean -p bounces prose-only done (ADR 0052) and backgrounds bash at 15s (ADR 0055)
\\
\\0.0.281
\\ • -p / --json skip learn auto-init — no 132M graff-pinned copy (ADR 0044)
diff --git a/src/command_catalog.zig b/src/command_catalog.zig
index fbc4b14a..41fb9236 100644
--- a/src/command_catalog.zig
+++ b/src/command_catalog.zig
@@ -59,7 +59,8 @@ pub const commands = [_]Item{
.{ .name = "/btw", .usage = "/btw <question>", .desc = "ask one side question about this conversation — billed, never added, rides the parent cache prefix" },
.{ .name = "/compact", .desc = "compact history into a fresh context (OpenAI server-side when available)" },
.{ .name = "/rewind", .usage = "/rewind [n|<snapshot>]", .desc = "list past prompts; /rewind <n> drops prompt n+after & reverts its file edits; /rewind <snapshot id> restores a sandbox filesystem instead, never the conversation" },
- .{ .name = "/snapshot", .usage = "/snapshot [attach [image]|detach|list]", .desc = "capture the attached sandbox's filesystem under .graff/sessions/<session>/snapshots; attach puts this session in a Docker sandbox, list shows what it has captured" },
+ .{ .name = "/snapshot", .usage = "/snapshot [attach [image]|detach|list|gc [n]]", .desc = "capture the attached sandbox's filesystem under .graff/sessions/<session>/snapshots; attach puts this session in a Docker sandbox, list shows what it has captured, gc keeps the newest n (default 1)" },
+ .{ .name = "/teleport", .usage = "/teleport <id> [docker|container]", .desc = "restore a docker_image_tar snapshot onto a different CLI backend (Apple Container by default); filesystem only, never the conversation" },
.{ .name = "/image", .usage = "/image <path>", .desc = "attach an image to your next message (vision models only)" },
.{ .name = "/images", .desc = "open image URLs from the last response (e.g. issue attachments) in your browser" },
.{ .name = "/paste", .desc = "attach the clipboard image — macOS; also Ctrl-V (⌘V can't be captured)" },
diff --git a/src/commands_sandbox.zig b/src/commands_sandbox.zig
index 04f6a342..a386abcd 100644
--- a/src/commands_sandbox.zig
+++ b/src/commands_sandbox.zig
@@ -1,6 +1,7 @@
//! #554's REPL surface: `/snapshot` captures the active sandbox's filesystem
//! into `.graff/sessions/<session>/snapshots/<id>/`, `/rewind <id>` brings one
-//! back up.
+//! back up, `/teleport <id>` restores the same tar on a different CLI backend,
+//! and `/snapshot gc` drops old snapshot trees.
//!
//! `/rewind` was already taken by the CONVERSATION rewind (commands_model.zig,
//! `/rewind <n>`), and the two are deliberately the same word: they are the
@@ -32,10 +33,11 @@ const sandbox = @import("sandbox.zig");
const sandbox_docker = @import("sandbox_docker.zig");
const util = @import("util.zig");
-/// The process's Docker backend, once `/snapshot attach` has built one. A
-/// live `Handle` points into a Sandbox that points back here, so this outlives
-/// any one command — the same process-wide shape as sandbox.active().
+/// Process-wide CLI backends. A live `Handle` points into a Sandbox that
+/// points back here, so these outlive any one command — the same shape as
+/// sandbox.active(). `g_container` is the Apple Container slot teleport uses.
var g_docker: sandbox_docker.Docker = undefined;
+var g_container: sandbox_docker.Docker = undefined;
/// The sentence every rewind output carries. A user who believed the
/// transcript had moved too would read it as the record of a run that never
@@ -56,15 +58,16 @@ pub fn explain(err: anyerror) []const u8 {
error.SandboxUnavailable => "the sandbox backend is not usable here — `docker` is not on PATH, or the daemon refused the command",
error.SnapshotUnsupported => "this backend cannot capture state (the local backend runs without isolation, so there is nothing to snapshot) — attach a Docker sandbox instead",
error.SnapshotFailed => "the capture failed — `docker commit`/`docker save` did not succeed",
- error.RestoreFailed => "the restore failed — `docker load`/`docker run` did not succeed, and the previous sandbox was already released; nothing is attached now, so `/snapshot attach` starts a fresh one",
+ error.RestoreFailed => "the restore failed — `load`/`run` did not succeed, and the previous sandbox was already released; nothing is attached now, so `/snapshot attach` starts a fresh one",
error.ExecFailed => "the sandbox command could not be run",
else => "the sandbox operation failed",
};
}
/// `/snapshot` (capture), `/snapshot attach [image]`, `/snapshot detach`,
-/// `/snapshot list`, and `/rewind <id>`. Returns false for anything else,
-/// including `/rewind` with a numeric or absent argument.
+/// `/snapshot list`, `/snapshot gc [n]`, `/teleport <id> [backend]`, and
+/// `/rewind <id>`. Returns false for anything else, including `/rewind` with
+/// a numeric or absent argument.
pub fn tryHandle(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {
if (argOf(line, "/snapshot")) |arg| {
if (std.mem.eql(u8, arg, "list") or std.mem.eql(u8, arg, "ls")) {
@@ -73,12 +76,19 @@ pub fn tryHandle(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writ
try attach(root, image, out);
} else if (std.mem.eql(u8, arg, "detach")) {
try detach(out);
+ } else if (argOf(arg, "gc") != null or std.mem.eql(u8, arg, "gc")) {
+ try collect(root, arena, if (argOf(arg, "gc")) |n| n else "", out);
} else {
try capture(root, arena, out);
}
try out.flush();
return true;
}
+ if (argOf(line, "/teleport")) |arg| {
+ try teleport(root, arena, arg, out);
+ try out.flush();
+ return true;
+ }
if (argOf(line, "/rewind")) |arg| {
if (!isSnapshotArg(arg)) return false; // the conversation rewind owns it
try restore(root, arena, arg, out);
@@ -88,6 +98,14 @@ pub fn tryHandle(root: *Agent, arena: Allocator, line: []const u8, out: *Io.Writ
return false;
}
+/// Named CLI backend. `docker` is the default attach; `container` is Apple
+/// Container — same wire, different binary. Unknown names stay null so the
+/// command can explain instead of guessing.
+pub fn backendNamed(name: []const u8) ?[]const u8 {
+ if (std.mem.eql(u8, name, "docker") or std.mem.eql(u8, name, "container")) return name;
+ return null;
+}
+
/// The argument after `cmd`, or null when `line` is a different command.
/// `/rewinds` is not `/rewind`: the next byte has to be a space or the end.
fn argOf(line: []const u8, cmd: []const u8) ?[]const u8 {
@@ -109,11 +127,7 @@ fn attach(root: *Agent, image: []const u8, out: *Io.Writer) !void {
try out.print("a sandbox is already attached ({s}) — /snapshot detach first\n", .{prev.handle.id});
return;
}
- g_docker = .{
- .io = root.io,
- .path_env = main_mod.g_path_env,
- .image = if (image.len > 0) image else sandbox_docker.default_image,
- };
+ g_docker = fillCli(root, "docker", image);
const backend = g_docker.backend();
if (!backend.available()) {
try out.print("docker backend: {s}\n", .{explain(error.SandboxUnavailable)});
@@ -211,6 +225,97 @@ fn restore(root: *Agent, arena: Allocator, id: []const u8, out: *Io.Writer) !voi
try out.print("{s} {s}; processes inside the sandbox were relaunched, not resumed{s}\n", .{ style.dim, log_note, style.reset });
}
+fn fillCli(root: *Agent, bin_name: []const u8, image: []const u8) sandbox_docker.Docker {
+ return .{
+ .io = root.io,
+ .path_env = main_mod.g_path_env,
+ .image = if (image.len > 0) image else sandbox_docker.default_image,
+ .bin_name = bin_name,
+ };
+}
+
+fn slot(bin_name: []const u8) *sandbox_docker.Docker {
+ return if (std.mem.eql(u8, bin_name, "container")) &g_container else &g_docker;
+}
+
+/// `/snapshot gc [n]` — keep the newest n snapshots (default 1). The exo miss
+/// #554 named: leftover tars pile up unless something deletes them.
+fn collect(root: *Agent, arena: Allocator, keep_arg: []const u8, out: *Io.Writer) !void {
+ if (!sandbox.safeName(root.session_name)) {
+ try out.writeAll("this session has no name a snapshot directory could be built from\n");
+ return;
+ }
+ const keep: usize = if (keep_arg.len == 0) 1 else std.fmt.parseInt(usize, keep_arg, 10) catch {
+ try out.print("usage: /snapshot gc [n] — n is how many newest snapshots to keep (default 1)\n", .{});
+ return;
+ };
+ const result = try sandbox.gc(root.io, sandbox.workspace(), arena, root.session_name, keep);
+ if (result.removed == 0) {
+ try out.print("snapshot gc: nothing to drop — {d} kept\n", .{result.kept});
+ return;
+ }
+ try out.print("snapshot gc: dropped {d} ({d} bytes), kept {d}\n", .{ result.removed, result.bytes, result.kept });
+}
+
+/// Restore `id` onto a backend other than the one that captured it. Dest
+/// defaults to `container` when the live backend is docker (or nothing is
+/// attached), and `docker` when the live backend is already container.
+fn teleport(root: *Agent, arena: Allocator, arg: []const u8, out: *Io.Writer) !void {
+ var it = std.mem.tokenizeAny(u8, arg, " \t");
+ const id = it.next() orelse {
+ try out.writeAll("usage: /teleport <id> [docker|container]\n");
+ return;
+ };
+ const dest_arg = it.next() orelse "";
+ const dest = if (dest_arg.len == 0)
+ defaultDest()
+ else
+ backendNamed(dest_arg) orelse {
+ try out.print("unknown backend {s} — teleport dest is docker or container\n", .{dest_arg});
+ return;
+ };
+ try restoreOnto(root, arena, id, dest, out);
+}
+
+fn defaultDest() []const u8 {
+ const act = sandbox.active() orelse return "container";
+ return if (std.mem.eql(u8, act.backend.name(), "container")) "docker" else "container";
+}
+
+fn restoreOnto(root: *Agent, arena: Allocator, id: []const u8, dest_name: []const u8, out: *Io.Writer) !void {
+ const found = sandbox.find(root.io, sandbox.workspace(), arena, root.session_name, id) orelse {
+ try out.print("no snapshot {s} in this session — {s}/snapshot list{s} shows what there is\n", .{ id, style.accent, style.reset });
+ return;
+ };
+ const dest_slot = slot(dest_name);
+ dest_slot.* = fillCli(root, dest_name, "");
+ const dest = dest_slot.backend();
+ if (!dest.available()) {
+ try out.print("{s} backend: {s}\n", .{ dest.name(), explain(error.SandboxUnavailable) });
+ return;
+ }
+ const blob: sandbox.Blob = .{
+ .io = root.io,
+ .dir = sandbox.workspace(),
+ .rel = try sandbox.payloadPath(arena, root.session_name, found.id),
+ };
+ const key = if (sandbox.active()) |act|
+ try arena.dupe(u8, act.handle.key)
+ else
+ try arena.dupe(u8, root.session_name);
+ if (sandbox.active()) |act| {
+ act.handle.release();
+ sandbox.detach();
+ }
+ const fresh = dest.acquireFromSnapshot(root.gpa, key, found.payload(), blob) catch |err| {
+ try out.print("teleport failed — {s}\n", .{explain(err)});
+ return;
+ };
+ sandbox.attach(.{ .backend = dest, .handle = fresh });
+ try out.print("teleported {s}{s}{s} onto {s} ({d} bytes)\n", .{ style.accent, found.id, style.reset, dest.name(), found.len });
+ try out.print("{s} {s}; processes inside the sandbox were relaunched, not resumed{s}\n", .{ style.dim, log_note, style.reset });
+}
+
fn renderList(root: *Agent, arena: Allocator, out: *Io.Writer) !void {
const items = try sandbox.list(root.io, sandbox.workspace(), arena, root.session_name);
if (items.len == 0) {
@@ -221,7 +326,7 @@ fn renderList(root: *Agent, arena: Allocator, out: *Io.Writer) !void {
for (items) |m| {
try out.print(" {s}{s}{s} {s:<8} {d:>10} B {s}\n", .{ style.accent, m.id, style.reset, m.backend, m.len, m.ref });
}
- try out.print("{s}usage: /rewind <id> — restores that filesystem; {s}{s}\n", .{ style.dim, log_note, style.reset });
+ try out.print("{s}usage: /rewind <id> restores here; /teleport <id> [docker|container] restores onto another backend; /snapshot gc drops old tars; {s}{s}\n", .{ style.dim, log_note, style.reset });
}
test "a numeric /rewind argument stays with the conversation rewind" {
@@ -238,6 +343,14 @@ test "argOf claims only the exact command" {
try std.testing.expect(argOf("/snapshots", "/snapshot") == null);
try std.testing.expect(argOf("/rewinds 3", "/rewind") == null);
try std.testing.expectEqualStrings("3", argOf("/rewind 3", "/rewind").?);
+ try std.testing.expectEqualStrings("id container", argOf("/teleport id container", "/teleport").?);
+}
+
+test "teleport dest names are docker or container" {
+ try std.testing.expectEqualStrings("docker", backendNamed("docker").?);
+ try std.testing.expectEqualStrings("container", backendNamed("container").?);
+ try std.testing.expect(backendNamed("daytona") == null);
+ try std.testing.expect(backendNamed("") == null);
}
test "every sandbox failure has an explanation, and rewind never claims the log moved" {
diff --git a/src/effort_route.zig b/src/effort_route.zig
index 48bfa346..336a36b9 100644
--- a/src/effort_route.zig
+++ b/src/effort_route.zig
@@ -61,7 +61,9 @@ pub fn omitsDefaultFlashEffort(model: []const u8) bool {
/// Wire `reasoning_effort` for an effort-capable provider. Flash / Gemini
/// default `medium` becomes `low`: omit still thinks (27 reasoning_tokens
-/// on a `pong`); `low` bills 0. `none` is a 400. `/effort high` unchanged.
+/// on a `pong`); `low` bills 0 on GLM. DeepSeek V4 still thinks at `low`
+/// until `thinking.type=disabled` (ADR 0054). `none` is a 400. `/effort high`
+/// unchanged.
pub fn wireEffort(model: []const u8, requested: []const u8) []const u8 {
if (std.mem.eql(u8, requested, "medium") and omitsDefaultFlashEffort(model)) return "low";
if (std.mem.eql(u8, requested, "ultra")) return "max";
diff --git a/src/exec_bash.zig b/src/exec_bash.zig
index 50486731..d2256c1c 100644
--- a/src/exec_bash.zig
+++ b/src/exec_bash.zig
@@ -27,6 +27,10 @@ const exec_bash_stream = @import("exec_bash_stream.zig");
/// the job registry instead of being killed (xai-org/grok-build BashTool).
pub const root_wait_ms: u64 = 120 * 1000;
+/// Lean `-p` has no human watching a hung test (ADR 0055). DeepSeek flash
+/// SWE sat 120s on `python3 test_json_stream.py`. Interactive stays 120s.
+pub const lean_oneshot_wait_ms: u64 = 15 * 1000;
+
/// Wall-clock ceiling for one *subagent* bash command. Subagents run on pool
/// threads with no TTY, so there is no Esc to kill a runaway command — without
/// this, a codedb refusal that pushes a subagent onto an unfiltered `grep ~/`
@@ -81,9 +85,15 @@ fn startedText(gpa: Allocator, id: u32, cmd: []const u8, ssh: bool, auto_bg: boo
return aw.toOwnedSlice();
}
+fn defaultRootWaitMs() u64 {
+ const main_mod = @import("main.zig");
+ if (main_mod.unattended and @import("no_local_tools.zig").lean) return lean_oneshot_wait_ms;
+ return root_wait_ms;
+}
+
fn rootWaitMs(input: Value) u64 {
- const t = intField(input, "timeout") orelse return root_wait_ms;
- if (t <= 0) return root_wait_ms;
+ const t = intField(input, "timeout") orelse return defaultRootWaitMs();
+ if (t <= 0) return defaultRootWaitMs();
return @min(@as(u64, @intCast(t)), job_wait.wait_cap_ms);
}
@@ -102,6 +112,27 @@ test "rootWaitMs: omitted/zero use 120s; positive values clamp to the 10h cap" {
try std.testing.expectEqual(job_wait.wait_cap_ms, rootWaitMs(huge.value));
}
+test "rootWaitMs: lean unattended oneshot defaults to 15s; timeout still wins" {
+ const main_mod = @import("main.zig");
+ const nlt = @import("no_local_tools.zig");
+ const saved_u = main_mod.unattended;
+ const saved_l = nlt.lean;
+ defer {
+ main_mod.unattended = saved_u;
+ nlt.lean = saved_l;
+ }
+ main_mod.unattended = true;
+ nlt.lean = true;
+ const empty = try std.json.parseFromSlice(Value, std.testing.allocator, "{}", .{});
+ defer empty.deinit();
+ try std.testing.expectEqual(lean_oneshot_wait_ms, rootWaitMs(empty.value));
+ const custom = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":5000}", .{});
+ defer custom.deinit();
+ try std.testing.expectEqual(@as(u64, 5_000), rootWaitMs(custom.value));
+ main_mod.unattended = false;
+ try std.testing.expectEqual(root_wait_ms, rootWaitMs(empty.value));
+}
+
fn formatJobDone(gpa: Allocator, cmd: []const u8, wait: jobs.FgDone) !ToolOutput {
defer gpa.free(wait.output);
var aw: Io.Writer.Allocating = .init(gpa);
diff --git a/src/help.zig b/src/help.zig
index 75dd6d0f..037430ab 100644
--- a/src/help.zig
+++ b/src/help.zig
@@ -28,7 +28,7 @@ const peers_blurb =
;
pub const sections = [_]Section{
- .{ .title = "getting around", .names = &.{ "/new", "/clear", "/resume", "/save", "/sessions", "/workspace", "/experiment", "/rename", "/rewind", "/snapshot" } },
+ .{ .title = "getting around", .names = &.{ "/new", "/clear", "/resume", "/save", "/sessions", "/workspace", "/experiment", "/rename", "/rewind", "/snapshot", "/teleport" } },
.{ .title = "the model", .names = &.{ "/model", "/models", "/effort", "/reasoning", "/fast", "/thinking", "/keepcontext", "/fallback", "/routes" } },
.{ .title = "working autonomously", .names = &.{ "/goal", "/loop", "/schedule", "/review", "/plan", "/todo", "/jobs", "/ultracode", "/strict", "/yolo", "/never" } },
.{ .title = "talking to other graffs", .names = &.{ "/tell", "/peek", "/adapter" }, .blurb = peers_blurb },
diff --git a/src/no_local_tools.zig b/src/no_local_tools.zig
index 071ca8b0..1fcd3dd1 100644
--- a/src/no_local_tools.zig
+++ b/src/no_local_tools.zig
@@ -125,7 +125,7 @@ pub const lean_subagent_desc = "Spawn a sidecar for a self-contained task. Child
/// One-shot tool prose (ADR 0046). Same names and JSON schemas; shorter
/// descriptions so flash models start and finish instead of rereading
/// essays. Do not drop to four tools (ADR 0024).
-pub const lean_bash_desc = "Run /bin/sh -c in cwd. Returns stdout, stderr, exit. Foreground still running after 120s (or timeout ms) backgrounds — bash_output(wait_ms>0) waits; do not poll.";
+pub const lean_bash_desc = "Run /bin/sh -c in cwd. Returns stdout, stderr, exit. Foreground still running after 15s (or timeout ms) backgrounds — bash_output(wait_ms>0) waits; do not poll.";
pub const lean_read_file_desc = "Read a UTF-8 file. Call before editing. contains=exact-key numbered lines; start_line/end_line for a window.";
pub const lean_edit_file_desc = "Replace exact text. Prefer one batched edits[] over many calls. Prefer over write_file for an existing file.";
pub const lean_codedb_desc = "Indexed nav: context <task> · around <name> · callpath A B · list_dir <path> · status. Prefer over bash grep/find/ls.";
diff --git a/src/prompt_snapshot_tests.zig b/src/prompt_snapshot_tests.zig
index 8cabcd94..cdd9ba61 100644
--- a/src/prompt_snapshot_tests.zig
+++ b/src/prompt_snapshot_tests.zig
@@ -572,6 +572,7 @@ test "lean drops the todo/constraint capabilities from the prompt, never the loc
const a = a_state.allocator();
const lean_prompt = try prompts.composeBase(a, lean);
try std.testing.expect(lean_prompt.len < prompts.main_system_prompt.len);
+ try std.testing.expect(std.mem.indexOf(u8, lean_prompt, "described in prose is not done") != null);
}
test "unattended one-shots are told the REAL approval map up front; attended sessions hear nothing" {
diff --git a/src/prompt_text.zig b/src/prompt_text.zig
index 543ec15f..1903da88 100644
--- a/src/prompt_text.zig
+++ b/src/prompt_text.zig
@@ -279,6 +279,7 @@ pub const lean_parallel_note =
pub const lean_intro_note =
\\You are a coding agent. Use the cataloged tools; never invent one.
+ \\A file change described in prose is not done — call edit_file or write_file.
\\Independent reads belong in ONE response, not one per turn.
\\A passing test and attempt_completion belong in ONE response.
;
diff --git a/src/provider_codegraff_tests.zig b/src/provider_codegraff_tests.zig
index 103fb16a..f26a0f2f 100644
--- a/src/provider_codegraff_tests.zig
+++ b/src/provider_codegraff_tests.zig
@@ -127,6 +127,7 @@ test "Codegraff Gemini sends low for default effort; /effort high still sends" {
const ds = try deepseek.buildBody(null, false, true, true);
defer std.testing.allocator.free(ds);
try std.testing.expect(std.mem.indexOf(u8, ds, "\"reasoning_effort\":\"medium\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, ds, "\"thinking\":{\"type\":\"enabled\"}") != null);
}
test "Codegraff glm-5.3-flash sends low for default effort; /effort high still sends" {
@@ -164,3 +165,48 @@ test "Codegraff glm-5.3-flash sends low for default effort; /effort high still s
defer std.testing.allocator.free(high);
try std.testing.expect(std.mem.indexOf(u8, high, "\"reasoning_effort\":\"high\"") != null);
}
+
+test "Codegraff DeepSeek flash disables thinking at default low; /effort high still thinks" {
+ var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var messages = std.json.Array.init(arena);
+ try messages.append(.{ .object = blk: {
+ var obj: std.json.ObjectMap = .empty;
+ try obj.put(arena, "role", .{ .string = "user" });
+ try obj.put(arena, "content", .{ .string = "hello" });
+ break :blk obj;
+ } });
+ var agent: Agent = .{
+ .gpa = std.testing.allocator,
+ .arena = arena,
+ .io = std.testing.io,
+ .client = undefined,
+ .provider = build("deepseek-v4-flash"),
+ .messages = messages,
+ .sub = false,
+ .label = "main",
+ .out = null,
+ .sys_normal = "system",
+ };
+ const low = try agent.buildBody(null, false, true, true);
+ defer std.testing.allocator.free(low);
+ try std.testing.expect(std.mem.indexOf(u8, low, "\"thinking\":{\"type\":\"disabled\"}") != null);
+ try std.testing.expect(std.mem.indexOf(u8, low, "\"reasoning_effort\":\"low\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, low, "\"thinking\":{\"type\":\"enabled\"}") == null);
+
+ agent.reasoning = .high;
+ const high = try agent.buildBody(null, false, true, true);
+ defer std.testing.allocator.free(high);
+ try std.testing.expect(std.mem.indexOf(u8, high, "\"thinking\":{\"type\":\"enabled\"}") != null);
+ try std.testing.expect(std.mem.indexOf(u8, high, "\"reasoning_effort\":\"high\"") != null);
+ try std.testing.expect(std.mem.indexOf(u8, high, "\"thinking\":{\"type\":\"disabled\"}") == null);
+
+ var glm: Agent = agent;
+ glm.provider = build("glm-5.3-flash");
+ glm.reasoning = .medium;
+ const glm_body = try glm.buildBody(null, false, true, true);
+ defer std.testing.allocator.free(glm_body);
+ try std.testing.expect(std.mem.indexOf(u8, glm_body, "\"thinking\":{\"type\":\"disabled\"}") == null);
+ try std.testing.expect(std.mem.indexOf(u8, glm_body, "\"reasoning_effort\":\"low\"") != null);
+}
diff --git a/src/sandbox.zig b/src/sandbox.zig
index 68e3b118..1506af4d 100644
--- a/src/sandbox.zig
+++ b/src/sandbox.zig
@@ -288,6 +288,38 @@ pub fn find(io: Io, dir: Io.Dir, arena: Allocator, session: []const u8, id: []co
return parseManifest(arena, bytes);
}
+/// Delete one snapshot tree (manifest + payload). Missing is success: GC is
+/// idempotent and must not fail a command because a half-written dir vanished.
+pub fn remove(io: Io, dir: Io.Dir, arena: Allocator, session: []const u8, id: []const u8) bool {
+ if (!safeName(session) or !safeName(id)) return false;
+ const path = snapshotDir(arena, session, id) catch return false;
+ dir.access(io, path, .{}) catch return true;
+ dir.deleteTree(io, path) catch return false;
+ return true;
+}
+
+pub const GcResult = struct {
+ kept: usize = 0,
+ removed: usize = 0,
+ bytes: u64 = 0,
+};
+
+/// Keep the newest `keep` snapshots (list is oldest-first); delete the rest.
+/// `keep == 0` deletes every snapshot this session has on disk.
+pub fn gc(io: Io, dir: Io.Dir, arena: Allocator, session: []const u8, keep: usize) Allocator.Error!GcResult {
+ const items = try list(io, dir, arena, session);
+ var result: GcResult = .{ .kept = items.len };
+ if (items.len <= keep) return result;
+ for (items[0 .. items.len - keep]) |m| {
+ if (remove(io, dir, arena, session, m.id)) {
+ result.removed += 1;
+ result.bytes += m.len;
+ result.kept -= 1;
+ }
+ }
+ return result;
+}
+
// ── The active sandbox ─────────────────────────────────────────────────────
// A process-wide pair rather than an Agent field: nothing in the MVP attaches
// a sandbox automatically, so the REPL commands need a seam they can read that
@@ -435,6 +467,45 @@ test "LocalProcess acquires but refuses to snapshot" {
handle.release();
}
+test "snapshot GC keeps the newest N and deletes the rest" {
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ var arena_state: std.heap.ArenaAllocator = .init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var tmp = std.testing.tmpDir(.{ .iterate = true });
+ defer tmp.cleanup();
+
+ inline for (.{
+ .{ .id = "old", .ms = 10, .len = 100 },
+ .{ .id = "mid", .ms = 20, .len = 200 },
+ .{ .id = "new", .ms = 30, .len = 300 },
+ }) |row| {
+ try tmp.dir.createDirPath(io, try snapshotDir(arena, "s", row.id));
+ try tmp.dir.writeFile(io, .{ .sub_path = try payloadPath(arena, "s", row.id), .data = "x" });
+ try writeManifest(io, tmp.dir, arena, "s", .{
+ .id = row.id,
+ .backend = "docker",
+ .kind = "docker_image_tar",
+ .ref = row.id,
+ .len = row.len,
+ .created_ms = row.ms,
+ });
+ }
+ try std.testing.expectEqual(@as(usize, 3), (try list(io, tmp.dir, arena, "s")).len);
+
+ const trimmed = try gc(io, tmp.dir, arena, "s", 1);
+ try std.testing.expectEqual(@as(usize, 2), trimmed.removed);
+ try std.testing.expectEqual(@as(usize, 1), trimmed.kept);
+ try std.testing.expectEqual(@as(u64, 300), trimmed.bytes);
+ const left = try list(io, tmp.dir, arena, "s");
+ try std.testing.expectEqual(@as(usize, 1), left.len);
+ try std.testing.expectEqualStrings("new", left[0].id);
+ try std.testing.expect(find(io, tmp.dir, arena, "s", "old") == null);
+ try std.testing.expect(remove(io, tmp.dir, arena, "s", "missing"));
+ try std.testing.expect(!remove(io, tmp.dir, arena, "s", ".."));
+}
+
test "the active sandbox is empty until something attaches one" {
detach();
try std.testing.expect(active() == null);
diff --git a/src/sandbox_docker.zig b/src/sandbox_docker.zig
index 7ac54554..ef848373 100644
--- a/src/sandbox_docker.zig
+++ b/src/sandbox_docker.zig
@@ -52,12 +52,20 @@ pub const Docker = struct {
/// backend; the wire below is unchanged.
bin_name: []const u8 = "docker",
- const backend_vtable: sandbox.BackendVTable = .{
+ const docker_vtable: sandbox.BackendVTable = .{
.name = "docker",
.available = availableImpl,
.acquire = acquireImpl,
.acquireFromSnapshot = acquireFromSnapshotImpl,
};
+ /// Same CLI wire, different binary — Apple Container (`container`) is the
+ /// second snapshot-capable backend #554's teleport path restores onto.
+ const container_vtable: sandbox.BackendVTable = .{
+ .name = "container",
+ .available = availableImpl,
+ .acquire = acquireImpl,
+ .acquireFromSnapshot = acquireFromSnapshotImpl,
+ };
const handle_vtable: sandbox.HandleVTable = .{
.exec = execImpl,
@@ -66,7 +74,10 @@ pub const Docker = struct {
};
pub fn backend(self: *Docker) sandbox.Backend {
- return .{ .ctx = @ptrCast(self), .vt = &backend_vtable };
+ return .{
+ .ctx = @ptrCast(self),
+ .vt = if (std.mem.eql(u8, self.bin_name, "container")) &container_vtable else &docker_vtable,
+ };
}
/// One live sandbox. Allocated per `acquire` and freed by `release`, so two
@@ -390,6 +401,13 @@ test "a snapshot tag is prefixed and unique" {
try std.testing.expect(!std.mem.eql(u8, a, b));
}
+test "bin_name container names the Apple Container backend" {
+ var docker: Docker = .{ .io = std.testing.io, .path_env = "", .bin_name = "container" };
+ try std.testing.expectEqualStrings("container", docker.backend().name());
+ var plain: Docker = .{ .io = std.testing.io, .path_env = "" };
+ try std.testing.expectEqualStrings("docker", plain.backend().name());
+}
+
test "a missing docker resolves to nothing rather than spawning" {
var buf: [4096]u8 = undefined;
try std.testing.expect(resolveInto(std.testing.io, "", "docker", &buf) == null);
diff --git a/src/sandbox_tests.zig b/src/sandbox_tests.zig
index 0d6fa7bc..a77110e8 100644
--- a/src/sandbox_tests.zig
+++ b/src/sandbox_tests.zig
@@ -387,6 +387,138 @@ test "#554: /snapshot attach drives the seam by hand, and detach gives the sandb
try std.testing.expectEqual(@as(usize, 1), (try sandbox.list(io, shim.tmp.dir, arena, "s")).len);
}
+test "#554: /snapshot gc keeps the newest snapshot and drops the rest" {
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ var arena_state: std.heap.ArenaAllocator = .init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var tmp = std.testing.tmpDir(.{ .iterate = true });
+ defer tmp.cleanup();
+ sandbox.setWorkspace(tmp.dir);
+ defer sandbox.setWorkspace(null);
+
+ inline for (.{
+ .{ .id = "old", .ms = 10 },
+ .{ .id = "new", .ms = 20 },
+ }) |row| {
+ try tmp.dir.createDirPath(io, try sandbox.snapshotDir(arena, "s", row.id));
+ try tmp.dir.writeFile(io, .{ .sub_path = try sandbox.payloadPath(arena, "s", row.id), .data = canned_tar });
+ try sandbox.writeManifest(io, tmp.dir, arena, "s", .{
+ .id = row.id,
+ .backend = "docker",
+ .kind = "docker_image_tar",
+ .ref = row.id,
+ .len = canned_tar.len,
+ .created_ms = row.ms,
+ });
+ }
+
+ var root: Agent = undefined;
+ root.io = io;
+ root.gpa = gpa;
+ root.session_name = "s";
+ var aw: Io.Writer.Allocating = .init(arena);
+ try std.testing.expect(try commands_sandbox.tryHandle(&root, arena, "/snapshot gc", &aw.writer));
+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "dropped 1") != null);
+ const left = try sandbox.list(io, tmp.dir, arena, "s");
+ try std.testing.expectEqual(@as(usize, 1), left.len);
+ try std.testing.expectEqualStrings("new", left[0].id);
+}
+
+test "#554: /teleport restores a docker_image_tar onto the container CLI" {
+ if (skipOnWindows()) return error.SkipZigTest;
+ const io = std.testing.io;
+ const gpa = std.testing.allocator;
+ var arena_state: std.heap.ArenaAllocator = .init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+
+ var shim: Shim = undefined;
+ try shim.init();
+ defer shim.deinit();
+ try shim.tmp.dir.writeFile(io, .{
+ .sub_path = "bin/container",
+ .data = shim_script,
+ .flags = .{ .permissions = .executable_file },
+ });
+ sandbox.setWorkspace(shim.tmp.dir);
+ defer sandbox.setWorkspace(null);
+ defer releaseActive();
+ const saved_path = main_mod.g_path_env;
+ defer main_mod.g_path_env = saved_path;
+ main_mod.g_path_env = shim.bin_dir;
+
+ try shim.tmp.dir.createDirPath(io, try sandbox.snapshotDir(arena, "s", "snap1"));
+ try shim.tmp.dir.writeFile(io, .{
+ .sub_path = try sandbox.payloadPath(arena, "s", "snap1"),
+ .data = canned_tar,
+ });
+ try sandbox.writeManifest(io, shim.tmp.dir, arena, "s", .{
+ .id = "snap1",
+ .backend = "docker",
+ .kind = "docker_image_tar",
+ .ref = "graff-snap-from-manifest",
+ .len = canned_tar.len,
+ .created_ms = 1,
+ });
+ shim.clearLog();
+
+ var root: Agent = undefined;
+ root.io = io;
+ root.gpa = gpa;
+ root.session_name = "s";
+ var aw: Io.Writer.Allocating = .init(arena);
+ try std.testing.expect(try commands_sandbox.tryHandle(&root, arena, "/teleport snap1 container", &aw.writer));
+ const text = aw.writer.buffered();
+ try std.testing.expect(std.mem.indexOf(u8, text, "teleported") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, "onto container") != null);
+ try std.testing.expect(std.mem.indexOf(u8, text, commands_sandbox.log_note) != null);
+ try std.testing.expectEqualStrings("container", sandbox.active().?.backend.name());
+ const log = shim.log(arena);
+ try std.testing.expect(std.mem.indexOf(u8, log, "load") != null);
+ try std.testing.expect(std.mem.indexOf(u8, log, "run -d --name graff-sbx-s " ++ loaded_ref) != null);
+}
+
+test "#554: /teleport with no dest CLI explains instead of failing" {
+ const gpa = std.testing.allocator;
+ var arena_state: std.heap.ArenaAllocator = .init(gpa);
+ defer arena_state.deinit();
+ const arena = arena_state.allocator();
+ var tmp = std.testing.tmpDir(.{ .iterate = true });
+ defer tmp.cleanup();
+ sandbox.setWorkspace(tmp.dir);
+ defer sandbox.setWorkspace(null);
+ sandbox.detach();
+ const saved_path = main_mod.g_path_env;
+ defer main_mod.g_path_env = saved_path;
+ main_mod.g_path_env = "";
+
+ try tmp.dir.createDirPath(std.testing.io, try sandbox.snapshotDir(arena, "s", "snap1"));
+ try sandbox.writeManifest(std.testing.io, tmp.dir, arena, "s", .{
+ .id = "snap1",
+ .backend = "docker",
+ .kind = "docker_image_tar",
+ .ref = "x",
+ .len = 1,
+ .created_ms = 1,
+ });
+
+ var root: Agent = undefined;
+ root.io = std.testing.io;
+ root.gpa = gpa;
+ root.session_name = "s";
+ var aw: Io.Writer.Allocating = .init(arena);
+ try std.testing.expect(try commands_sandbox.tryHandle(&root, arena, "/teleport snap1 container", &aw.writer));
+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "container backend:") != null);
+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), "not on PATH") != null);
+ try std.testing.expect(sandbox.active() == null);
+
+ var usage: Io.Writer.Allocating = .init(arena);
+ try std.testing.expect(try commands_sandbox.tryHandle(&root, arena, "/teleport", &usage.writer));
+ try std.testing.expect(std.mem.indexOf(u8, usage.writer.buffered(), "usage: /teleport") != null);
+}
+
test "#554: /snapshot attach with no docker installed explains instead of failing" {
const gpa = std.testing.allocator;
var arena_state: std.heap.ArenaAllocator = .init(gpa);
diff --git a/src/test_hooks.zig b/src/test_hooks.zig
index 9dd39eed..987e5196 100644
--- a/src/test_hooks.zig
+++ b/src/test_hooks.zig
@@ -222,7 +222,7 @@ const proc_identity = @import("proc_identity.zig");
// (agent_context.zig, subagent.zig) sit at the 600-line cap.
const usage_attribution_tests = @import("usage_attribution_tests.zig");
-// #554: the sandbox seam, its Docker backend, the /snapshot + /rewind <id>
+// #554: the sandbox seam, its Docker backend, /snapshot + /rewind <id> + /teleport + gc
// commands, and the fake-docker orchestration suite. Production reaches
// commands_sandbox.zig from commands_misc.tryHandle and the rest only through
// calls, so without these hooks the whole subsystem's tests compile to nothing.
diff --git a/src/zai_wire.zig b/src/zai_wire.zig
index 3b911a09..7731747b 100644
--- a/src/zai_wire.zig
+++ b/src/zai_wire.zig
@@ -33,14 +33,29 @@ pub fn vercelEffort(requested: []const u8) []const u8 {
return "medium";
}
+/// DeepSeek V4 (native or via codegraff/fireworks): thinking is ON at
+/// high unless `thinking.type` is `disabled`. `reasoning_effort: low`
+/// still emits `reasoning_content` (ADR 0054).
+pub fn isDeepseekFamily(provider_id: []const u8, model: []const u8) bool {
+ if (std.mem.eql(u8, provider_id, "deepseek")) return true;
+ return std.mem.indexOf(u8, model, "deepseek") != null;
+}
+
/// OpenAI-chat extras after `prompt_cache_key`: Z.AI thinking, Vercel
-/// `reasoning.effort`, then the shared `reasoning_effort` hint.
-pub fn writeChatExtras(s: *std.json.Stringify, provider_id: []const u8, send_effort: bool, requested: []const u8) !void {
+/// `reasoning.effort`, DeepSeek thinking on/off, then `reasoning_effort`.
+pub fn writeChatExtras(s: *std.json.Stringify, provider_id: []const u8, model: []const u8, send_effort: bool, requested: []const u8) !void {
const is_zai = std.mem.eql(u8, provider_id, "zai");
const is_vercel = std.mem.eql(u8, provider_id, "vercel");
if (is_zai) {
try s.objectField("thinking");
try s.print("{s}", .{"{\"type\":\"enabled\",\"clear_thinking\":false}"});
+ } else if (isDeepseekFamily(provider_id, model) and send_effort) {
+ // Official off switch. GLM rejects type=disabled; do not send it there.
+ try s.objectField("thinking");
+ try s.print("{s}", .{if (std.mem.eql(u8, requested, "low"))
+ "{\"type\":\"disabled\"}"
+ else
+ "{\"type\":\"enabled\"}"});
}
if (is_vercel and send_effort) {
try s.objectField("reasoning");
@@ -56,6 +71,14 @@ pub fn writeChatExtras(s: *std.json.Stringify, provider_id: []const u8, send_eff
}
}
+test "DeepSeek family is native id or a deepseek model name" {
+ try std.testing.expect(isDeepseekFamily("deepseek", "deepseek-v4-pro"));
+ try std.testing.expect(isDeepseekFamily("codegraff", "deepseek-v4-flash"));
+ try std.testing.expect(isDeepseekFamily("fireworks", "accounts/fireworks/models/deepseek-v4-flash"));
+ try std.testing.expect(!isDeepseekFamily("codegraff", "glm-5.3-flash"));
+ try std.testing.expect(!isDeepseekFamily("zai", "glm-5.3"));
+}
+
test "Z.AI maps graff efforts onto low|high|max" {
try std.testing.expectEqualStrings("low", reasoningEffort("low"));
try std.testing.expectEqualStrings("high", reasoningEffort("medium"));