Skip to content

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

Python

chore: gitignore graff runtime state, untrack stray subagent transcripts

Rach Pradhan885e71783742
diff --git a/.gitignore b/.gitignore
index eebe39f7..ad81a533 100644
--- a/.gitignore
+++ b/.gitignore
@@ -9,7 +9,7 @@ node_modules/
harness.trace.jsonl
harness.trajectory.jsonl
.harness/
-.graff/worktrees/
+.graff/
.claude/scheduled_tasks.lock
*.session.json
.mcp.json
@@ -31,3 +31,6 @@ __pycache__/
# release artifacts
dist/
+
+# surfer lives in its own repo (~/surfer, github.com/justrach/surfer) — never track it here
+surfer/
diff --git a/.graff/subagents/sa-000-286b61f0.md b/.graff/subagents/sa-000-286b61f0.md
deleted file mode 100644
index 54f60b27..00000000
--- a/.graff/subagents/sa-000-286b61f0.md
+++ /dev/null
@@ -1,83 +0,0 @@
-# subagent sa-000-286b61f0
-
-- label: issue 62 contents
-- kind: workflow_task
-- status: ok
-- elapsed_ms: 290103
-- tools: bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash
-
-## task
-
-Inspect GitHub issue https://github.com/justrach/codegraff/issues/62 and summarize the requested/added ultracode functionality. Prefer `gh issue view 62 --repo justrach/codegraff` if available; otherwise use `curl -L` to fetch the issue page/API. Report concrete acceptance criteria/features mentioned. Do not modify files.
-
-## report
-
-## Verified from GitHub issue #62
-
-Issue #62 requests a chat-scoped `/ultracode` slash command because the existing behavior only treated the word `ultracode` inside an individual prompt as a one-turn codeword trigger; users had to repeat it every turn for sustained behavior. Source: issue body, “Problem” section, https://github.com/justrach/codegraff/issues/62.
-
-Requested behavior:
-
-- `/ultracode` toggles persistent ultracode mode for the current chat/conversation. Source: issue body, “Proposed behavior,” https://github.com/justrach/codegraff/issues/62.
-- If currently off, `/ultracode` turns it on; if currently on, `/ultracode` turns it off. Source: issue body, “Proposed behavior,” https://github.com/justrach/codegraff/issues/62.
-- While persistent mode is on, every normal user prompt in that chat should behave as if it included the existing `ultracode` codeword. Source: issue body, “Proposed behavior,” https://github.com/justrach/codegraff/issues/62.
-- Existing per-prompt `ultracode` behavior must remain: a single prompt containing `ultracode` still triggers temporary ultracode when persistent mode is off. Source: issue body, “Proposed behavior” and acceptance criteria, https://github.com/justrach/codegraff/issues/62.
-- Persistent mode plus an explicit `ultracode` codeword in the same prompt must not duplicate augmentation. Source: issue body, “Proposed behavior” and acceptance criteria, https://github.com/justrach/codegraff/issues/62.
-- UI feedback should clearly say enabled/disabled, e.g. “Ultracode mode enabled for this chat.” / “Ultracode mode disabled for this chat.” Source: issue body, “Proposed behavior,” https://github.com/justrach/codegraff/issues/62.
-
-## Concrete acceptance criteria/features mentioned
-
-The issue explicitly lists these criteria:
-
-1. `/ultracode` appears in GUI slash-command autocomplete. Source: issue body, “Acceptance criteria,” https://github.com/justrach/codegraff/issues/62.
-2. Submitting `/ultracode` is intercepted as a slash command, not sent as normal chat text. Source: issue body, “Acceptance criteria,” https://github.com/justrach/codegraff/issues/62.
-3. `/ultracode` toggles persistent ultracode mode scoped to the current chat/conversation. Source: issue body, “Acceptance criteria,” https://github.com/justrach/codegraff/issues/62.
-4. When persistent mode is on, ordinary prompts behave as if they included the `ultracode` codeword. Source: issue body, “Acceptance criteria,” https://github.com/justrach/codegraff/issues/62.
-5. When persistent mode is off, ordinary prompts are unchanged. Source: issue body, “Acceptance criteria,” https://github.com/justrach/codegraff/issues/62.
-6. A single prompt containing `ultracode` still triggers existing temporary per-turn ultracode behavior. Source: issue body, “Acceptance criteria,” https://github.com/justrach/codegraff/issues/62.
-7. Persistent mode and per-prompt codeword behavior must not produce duplicate ultracode augmentation on the same turn. Source: issue body, “Acceptance criteria,” https://github.com/justrach/codegraff/issues/62.
-8. UI shows clear feedback when mode is enabled/disabled. Source: issue body, “Acceptance criteria,” https://github.com/justrach/codegraff/issues/62.
-9. Setting applies to active `graff --json` sessions without restart/new chat, or session-boundary behavior is clearly documented/recreated. Source: issue body, “Acceptance criteria,” https://github.com/justrach/codegraff/issues/62.
-10. Existing `/plan`, model, effort, fast, and normal prompt submission behavior remains unchanged. Source: issue body, “Acceptance criteria,” https://github.com/justrach/codegraff/issues/62.
-
-## Added/implemented functionality reported in the issue comments
-
-The owner comment says implementation landed on `release/0.0.161`:
-
-- Commit `460a400` adds `/ultracode`, `/ultracode on`, `/ultracode off`, JSON control `set_ultracode`, GUI command/autocomplete, and persistent chat-scoped ultracode mode. Source: issue comment, https://github.com/justrach/codegraff/issues/62#issuecomment-4759447949.
-- Commit `7bde8e0` persists ultracode mode in session metadata and improves resume/session behavior around steering commands. Source: issue comment, https://github.com/justrach/codegraff/issues/62#issuecomment-4759447949.
-- The comment identifies branch tip `f3380d6` on `release/0.0.161` as containing the work. Source: issue comment, https://github.com/justrach/codegraff/issues/62#issuecomment-4759447949.
-
-## Code evidence I verified locally
-
-- GUI conversation state gained `ultracode_enabled`, documented as “Persistent ultracode … scoped to this chat.” Evidence: `460a400:gui/src-tauri/src/runtime/simple.rs:45-46`.
-- GUI command catalog includes `ultracode` with usage “Toggle persistent ultracode (multi-agent workflow) mode.” Evidence: `460a400:gui/src-tauri/src/runtime/simple.rs:445-450`.
-- GUI `/ultracode` execution toggles `conversation.ultracode_enabled`, persists conversations, sends live JSON control `{ "type": "set_ultracode", "on": now_on }` if a session exists, and returns enabled/disabled feedback text. Evidence: `460a400:gui/src-tauri/src/runtime/simple.rs:1218-1248`.
-- GUI live-control ack handling recognizes an `ultracode` event. Evidence: `460a400:gui/src-tauri/src/runtime/simple.rs:1023-1025`.
-- On spawning a `graff --json` session, GUI reads the conversation’s `ultracode_enabled` state and sends `set_ultracode` when true. Evidence: `460a400:gui/src-tauri/src/runtime/simple.rs:1103-1116` and `460a400:gui/src-tauri/src/runtime/simple.rs:1149-1155`.
-- GUI persistence serializes/deserializes `ultracode_enabled` in conversation metadata. Evidence: `460a400:gui/src-tauri/src/runtime/simple.rs:1057-1065`, `460a400:gui/src-tauri/src/runtime/simple.rs:2306-2318`, and `460a400:gui/src-tauri/src/runtime/simple.rs:2395-2407`.
-- Core JSON protocol documentation was updated so live-control acks include `ultracode`. Evidence: `460a400:src/main.zig:77-82`.
-- Core JSON input handles `set_ultracode`, sets `root.ultracode_mode`, and emits `{ type: "ultracode", ok: true, on }`. Evidence: `460a400:src/main.zig:4958-4962`.
-- Core prompt augmentation condition is a single branch: it triggers when the prompt contains `ultracode` case-insensitively **or** `root.ultracode_mode` is enabled, which supports deduplication because there is only one augmentation path. Evidence: `460a400:src/main.zig:5054-5076`.
-- Core REPL command list includes `/ultracode`. Evidence: `460a400:src/main.zig:2227`.
-- Core REPL handler accepts `/ultracode`, `/ultracode on`, and `/ultracode off`; it toggles/sets `root.ultracode_mode` and prints current state. Evidence: `460a400:src/main.zig:6166-6170`.
-- Later commit `7bde8e0` persists `ultracode_mode` into saved session metadata and restores it on load. Evidence: `7bde8e0:src/main.zig:7966-7973` and `7bde8e0:src/main.zig:7997-8008`.
-- Later commit `7bde8e0` resets `ultracode_mode` on `/new`, creating a new session boundary. Evidence: `7bde8e0:src/main.zig:5781-5789`.
-
-## Inferred summary
-
-The requested/added ultracode functionality is a two-layer persistence model:
-
-- In the GUI, `/ultracode` is a chat-scoped toggle stored on the conversation and forwarded live to the active `graff --json` engine session.
-- In the core engine, `set_ultracode` and REPL `/ultracode` control a session/root `ultracode_mode` flag.
-- The actual augmentation remains centralized in the existing ultracode codeword branch, now guarded by `prompt contains ultracode OR ultracode_mode`, which is how the implementation avoids duplicate augmentation.
-
-## 3 most load-bearing facts
-
-1. The feature is explicitly chat/conversation-scoped, not global: GUI state has `ultracode_enabled` on `ConversationState`. Evidence: `460a400:gui/src-tauri/src/runtime/simple.rs:45-46`.
-2. Live GUI sessions are updated without restart via JSON control `set_ultracode`. Evidence: `460a400:gui/src-tauri/src/runtime/simple.rs:1230-1235`.
-3. Deduplication is achieved by reusing one core augmentation branch for either the codeword or persistent mode. Evidence: `460a400:src/main.zig:5054-5076`.
-
-## Open question
-
-The issue comment says `/ultracode on` and `/ultracode off` were added, and I verified those in the core REPL handler, but the GUI backend `run_command` path shown here toggles regardless of args; it is unclear whether GUI slash routing exposes `/ultracode on/off` semantics or only `/ultracode` toggle semantics. Evidence: core supports on/off at `460a400:src/main.zig:6166-6170`; GUI toggles at `460a400:gui/src-tauri/src/runtime/simple.rs:1218-1248`.
diff --git a/.graff/subagents/sa-000-305676f1.md b/.graff/subagents/sa-000-305676f1.md
deleted file mode 100644
index e3ed129f..00000000
--- a/.graff/subagents/sa-000-305676f1.md
+++ /dev/null
@@ -1,235 +0,0 @@
-# subagent sa-000-305676f1
-
-- label: Explore Zig core (src/)
-- kind: workflow_task
-- status: ok
-- elapsed_ms: 223726
-- tools: codedb,codedb,read_file,read_file!,codedb,bash,bash,bash,read_file,bash,bash,bash,bash,bash,codedb,bash,bash,webfetch,bash,read_file!,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,read_file!,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,codedb,bash,bash,bash,bash,codedb,bash
-
-## task
-
-You are exploring the Zig core of a codebase. Use the codedb tool (search, symbol, outline, callers, context) to thoroughly understand the following areas. Report back with:
-1. The main entry point and overall architecture of src/main.zig and src/mcp.zig
-2. What the core Zig binary does (is it a server? CLI? what protocol?)
-3. Key functions, data structures, and how mcp.zig relates to the main module
-4. The build.zig configuration (targets, dependencies, notable build steps)
-5. Any interesting protocol, streaming, or stall-watchdog logic (the branch mentions streaming-read stall-watchdog fixes)
-
-Be thorough: read symbols, search for key patterns, and trace the program flow. Return your findings as a structured markdown report.
-
-## report
-
-Here is the structured markdown report based on my thorough exploration of the Zig core.
-
----
-
-# Zig Core Report: `simple-harness` / `graff`
-
-## 1. Main Entry Point and Overall Architecture
-
-### Entry Point
-- **`src/main.zig:3991`**: `pub fn main(init: std.process.Init) !void` is the program entry point.
-- It parses CLI flags, loads API keys from environment, login files, or the macOS keychain, initializes an HTTP client, and then enters one of three modes:
- 1. **One-shot (`-p` / bare positional)**: Runs a single prompt, prints the result, exits.
- 2. **Interactive REPL**: Reads stdin line-by-line, maintains conversation history, and loops through `Agent.runTurn()`.
- 3. **`serve` subcommand**: Binds an HTTP server that spawns `harness --json` children per session.
-
-### Architecture of `src/main.zig`
-The file is a ~12,950-line monolithic Zig module (no sub-files) organized roughly as:
-
-| Layer | Lines | Responsibility |
-|-------|-------|--------------|
-| Top-level constants/schemas | 1–450 | Tool specs, system prompts, model tables, pricing |
-| Provider/key/auth logic | 450–900 | `Provider`, `Keys`, `ProviderSpec`, OAuth loaders |
-| JSON schema / help / version | 900–1400 | `emitSchema`, `schema_protocol_json` |
-| Telemetry / OTLP | 1400–2000 | `Telemetry` struct, OpenTelemetry-style HTTP posting |
-| Skills / hooks / approvals | 2000–2500 | `SkillDef`, `Hook`, `Approvals` |
-| Utility fns | 2500–3800 | Cost tracking, file I/O, `runCapped`, `runSub` |
-| `main()` | 3900–4600 | CLI parsing, session setup, key loading, agent init |
-| REPL / command dispatch | 4600–5600 | `handleCommand`, history, `readLine`, line editor |
-| Agent core | 7400–8700 | `Agent` struct, `runTurn`, `request`, `buildBody` |
-| HTTP POST / streaming | 8700–9100 | `postStream`, `postWatched`, stall-watchdog `Select` arms |
-| Tool execution | 10600–11700 | `execTool`, `execToolInner`, builtins |
-| Subagent / workflow | 11600–12600 | `runSub`, `runWorkflow`, fan-out via `Io.async` |
-| `serve` HTTP bridge | 6600–7200 | `serveMain`, `serveConn`, `serveRequest`, `serveMessage` |
-| Tests | 12500+ | Inline `test` blocks |
-
-### Architecture of `src/mcp.zig`
-- **`src/mcp.zig:1`**: A minimal MCP (Model Context Protocol) client over stdio.
-- **`src/mcp.zig:40`**: `pub const Registry` is the primary data structure. It holds:
- - `servers: []*Server` — spawned child processes
- - `tools: []Tool` — discovered tools qualified as `mcp__<server>__<tool>`
- - `mutex: Io.Mutex` — serializes JSON-RPC per server (one bidirectional pipe)
-- **`src/mcp.zig:56`**: `Registry.init()` reads `.mcp.json`, spawns each server, runs `initialize` → `notifications/initialized` → `tools/list` handshake, and collects discovered tools.
-- **`src/mcp.zig:224`**: `Registry.call()` dispatches a tool call via `tools/call` JSON-RPC, with `oneOf` → `anyOf` schema rewriting for OpenAI compatibility.
-
-### Relationship between `mcp.zig` and `main.zig`
-- `main.zig:37` imports `mcp.zig` as `const mcp = @import("mcp.zig");`
-- The root `Agent` struct (`src/main.zig:7461`) holds `registry: ?*mcp.Registry`.
-- At startup (`main.zig:4350`), `mcp.Registry.init()` is called if the user consents (or `--yolo` is passed). The registry is then threaded into the `Agent`.
-- In `Agent.runTools()` (`src/main.zig:8081`), external tool calls that are not built-in or meta are dispatched via `execTool()` on `Io.async` pool threads. `execTool` passes the registry pointer in `ToolCtx` (`src/main.zig:10695`), and `execToolInner` routes MCP-qualified names (`mcp__*`) to `mcp.Registry.call()` (`src/main.zig:11411` area).
-
----
-
-## 2. What the Core Zig Binary Does
-
-The binary is a **dual-mode AI agent harness**:
-
-### A. CLI / REPL (`--json` or TTY)
-- **Agentic loop**: Reads user input, POSTs to LLM APIs (Anthropic Messages, OpenAI Chat Completions, or OpenAI Responses/Codex), receives tool calls, executes them (in parallel when safe), and feeds results back into the conversation.
-- **Built-in tools**: `bash`, `read_file`, `edit_file`, `write_file`, `webfetch`, `codedb`, plus background bash helpers (`bash_output`, `bash_kill`).
-- **Meta tools**: `todo_write`, `todo_read`, `ask_user`, `attempt_completion` — handled inline by the orchestrator, not on pool threads.
-- **Advanced tools**: `subagent` (spawns isolated child agents) and `workflow` (multi-phase parallel fan-out).
-- **MCP integration**: Dynamically discovers and calls tools from `.mcp.json` servers.
-- **Permission gating**: Bash and MCP tool calls require user approval unless `/yolo` or `--yolo` is set.
-- **Tracing**: Every API call and tool execution is appended to `harness.trace.jsonl`.
-
-### B. HTTP Server (`harness serve`)
-- **`src/main.zig:6694`**: `fn serveMain(...)` binds an HTTP/1.1 server (default `127.0.0.1:8787`).
-- Each session is a **spawned child** of the same binary running `harness --json`.
-- The HTTP bridge speaks **NDJSON** over chunked transfer encoding:
- - `POST /v1/sessions` → spawns child, returns `session_id`.
- - `POST /v1/sessions/{id}` → forwards one JSON protocol line to the child's stdin, streams stdout events back as NDJSON.
- - `DELETE /v1/sessions/{id}` → graceful close.
-- CORS is enabled only when a `--token` bearer token is configured (`src/main.zig:6740`).
-- The serve protocol is documented in `schema_protocol_json` at `src/main.zig:79`.
-
-### C. One-shot (`-p` / bare prompt)
-- Runs a single prompt to completion with no human interaction, outputs final text to stdout, exits.
-
----
-
-## 3. Key Functions and Data Structures
-
-### Core Data Structures
-
-| Struct | File:Line | Role |
-|--------|-----------|------|
-| `Agent` | `src/main.zig:7461` | The orchestrator: holds message history, provider, HTTP client, tools, streaming state, markdown renderer state, and MCP registry pointer. |
-| `ToolCall` | `src/main.zig:7413` | `{id, name, input}` — a model-requested tool invocation. |
-| `ExecResult` | `src/main.zig:7420` | `{text, is_error, ms}` — outcome of a tool run, arena-owned. |
-| `ToolOutput` | `src/main.zig:10687` | `{text, is_error, ms}` — gpa-owned result from `execTool`. |
-| `ToolCtx` | `src/main.zig:10695` | Everything passed to `execTool` on a pool thread: `gpa`, `io`, `client`, `provider`, `registry`, `approvals`, `tracer`, `snapshots`. |
-| `Provider` | `src/main.zig:801` | `{id, kind, auth, url, api_key, model, context}` — wire-format abstraction for Anthropic, OpenAI, and Responses APIs. |
-| `Keys` | `src/main.zig:823` | Holds optional API keys for all providers; resolves `providerFor` and `defaultProvider`. |
-| `mcp.Tool` | `src/mcp.zig:16` | `{server_index, original_name, qualified_name, description, input_schema}` |
-| `mcp.Server` | `src/mcp.zig:40` | `{name, child, stdin_writer, stdout_reader, next_id, protocol_version}` |
-| `mcp.Registry` | `src/mcp.zig:46` | `{gpa, io, arena_state, mutex, servers, tools}` |
-
-### Key Functions
-
-| Function | File:Line | Description |
-|----------|-----------|-------------|
-| `main()` | `src/main.zig:3991` | Entry point: flag parsing, key loading, agent init, mode dispatch. |
-| `Agent.runTurn()` | `src/main.zig:7611` | Main loop: `request()` → `stepAnthropic`/`stepOpenAI`/`stepResponses` → `runTools` → repeat until `attempt_completion` or error. |
-| `Agent.request()` | `src/main.zig:7642` | Builds request body, retries with backoff on transport errors, calls `postStream` (live) or `postWatched` (subagent/non-streaming). |
-| `Agent.postStream()` | `src/main.zig:8760` | Streaming HTTP POST with SSE/NDJSON parsing; races reads against the stall-watchdog. |
-| `Agent.runTools()` | `src/main.zig:8081` | Dispatches tool calls: meta tools inline, external tools via `Io.async` pool. |
-| `execTool()` | `src/main.zig:10953` | Pool-thread entry point; routes to `execToolInner`. |
-| `execToolInner()` | `src/main.zig:11411` | Routes builtins (bash, read, edit, write, webfetch, codedb), meta, subagent, workflow, and MCP tools. |
-| `mcp.Registry.init()` | `src/mcp.zig:56` | Spawns MCP servers from `.mcp.json`, handshakes, collects tools. |
-| `mcp.Registry.call()` | `src/mcp.zig:224` | JSON-RPC `tools/call` over stdio; returns text + error flag. |
-| `serveMain()` | `src/main.zig:6694` | HTTP accept loop; spawns `serveConn` per connection. |
-| `serveMessage()` | `src/main.zig:6920` | Bridges one HTTP POST → child stdin, then streams child stdout NDJSON back via chunked response. |
-
----
-
-## 4. `build.zig` Configuration
-
-- **`src/main.zig`** is both the executable root and the test root (`build.zig:42`, `build.zig:59`).
-- **Executable**: named `graff` (`build.zig:42`).
-- **Version**: baked in at build time via `git describe --tags --always --dirty` (`build.zig:10`). Falls back to `0.1.0-dev`. Can be overridden with `-Dversion=X.Y.Z`.
-- **Telemetry endpoint**: hardcoded default `https://harness-telemetry.rachpradhan.workers.dev` (`build.zig:33`), overridable via `-Dtelemetry-endpoint=...` or disabled with `=""`.
-- **Options module**: `exe.root_module.addOptions("build_options", opts)` (`build.zig:47`) exposes `version` and `telemetry_endpoint` as compile-time constants.
-- **No external dependencies**: The build uses only the Zig standard library (`std`). There are no `build.zig.zon` dependencies.
-- **Build steps**:
- - `zig build run` — builds and runs the harness.
- - `zig build test` — runs inline unit tests (including `mcp.zig` tests).
-
----
-
-## 5. Protocol, Streaming, and Stall-Watchdog Logic
-
-### The Streaming Architecture
-- **Root (live) requests stream**: When `!self.sub and self.out != null and !self.stream_quiet`, `Agent.request()` calls `postStream()` instead of `postWatched()` (`src/main.zig:7664`).
-- **`postStream()`** (`src/main.zig:8760` area):
- 1. Sends the HTTP body via `std.http.Client.Request`.
- 2. Receives the response head, potentially decompressing (gzip, deflate, zstd).
- 3. Reads the SSE/NDJSON response line-by-line in a `while(true)` loop.
- 4. Each line is parsed and printed live via `printDelta()` while also being buffered into `full` for later JSON reassembly.
-
-### The Stall-Watchdog (Key Fix)
-The codebase explicitly guards against **idle-stall dead connections** (half-open sockets where the server accepts but sends no bytes). This is the "streaming-read stall-watchdog" referenced in the branch. It uses `std.Io.Select` to race I/O against a timeout.
-
-#### `WatchdogFired` enum (`src/main.zig:10587`)
-```zig
-const WatchdogFired = enum { esc, deadline };
-```
-
-#### `stream_stall_ms` (`src/main.zig:10598`)
-```zig
-const stream_stall_ms: u64 = 120 * 1000; // 2 minutes idle timeout
-```
-
-#### Guard Points in `postStream()`
-
-1. **Response-head stall guard** (`src/main.zig:8786`):
- ```zig
- var hsel: Io.Select(HeadDone) = .init(self.io, &hd_buf);
- hsel.concurrent(.head, streamHeadTask, .{&req});
- hsel.concurrent(.stall, streamStallTask, .{self.io});
- ```
- If headers don't arrive within `stream_stall_ms`, the connection is poisoned (`conn.closing = true`) and `error.HungRequest` is returned so the retry loop redials.
-
-2. **Per-line stall guard** (`src/main.zig:8846`):
- ```zig
- var rsel: Io.Select(ReadDone) = .init(self.io, &rd_buf);
- rsel.concurrent(.line, streamLineTask, .{ reader, &line.writer });
- rsel.concurrent(.stall, streamStallTask, .{self.io});
- ```
- If no `\n`-delimited SSE line arrives within 120s, the stream is treated as dead. Same for the "is there more?" peek (`streamPeekTask`) at `src/main.zig:8885`.
-
-3. **Non-streaming POST guard** (`postWatched`) (`src/main.zig:10650`):
- `postWatched` also races `postTask` against `postWatchdog` (200ms ticks, 10-minute hard deadline) so a stuck subagent request cannot wedge a workflow forever.
-
-#### Select Arm Wrappers (`src/main.zig:10609–10638`)
-| Task | Role |
-|------|------|
-| `streamLineTask` | `reader.streamDelimiterEnding(w, '\n')` |
-| `streamPeekTask` | `reader.peekByte()` — guards the "more data?" probe |
-| `streamHeadTask` | `req.receiveHead(&.{})` — guards header read |
-| `streamStallTask` | Sleeps 200ms increments; fires at `stream_stall_ms`; also checks `Agent.esc_cancel` for early Esc abort |
-
-#### Esc-Interrupt During Tools
-- `esc_cancel` is an atomic bool (`src/main.zig:8977`).
-- `escWatchTask` polls stdin for a bare Esc keypress in a background `Io.async` future while the root awaits tool results (`src/main.zig:8980`).
-- Subagents check `esc_cancel` between SSE lines and turn iterations, allowing graceful abort even when no HTTP stream is active.
-
----
-
-## Verified vs. Inferred
-
-### Verified
-- `src/main.zig:3991` is the single entry point.
-- The binary is both a **CLI/REPL** and an **HTTP server** (`serveMain`).
-- Tool dispatch goes through `Agent.runTools` → `execTool` → `execToolInner`, with MCP tools routed via `mcp.Registry.call`.
-- `build.zig` has **zero external dependencies**; only standard library.
-- The stall-watchdog uses `Io.Select` with `streamHeadTask`, `streamLineTask`, `streamPeekTask`, and `streamStallTask` at exactly the lines cited above.
-
-### Inferred
-- The "branch mentions streaming-read stall-watchdog fixes" refers to the `postStream` `Io.Select` guards at `stream_stall_ms = 120_000` and the related `postWatched` watchdog. The codebase contains the fixes; they are not on a separate branch in the current working tree.
-- `std.Io` is a custom or experimental Zig async I/O layer (not standard Zig 0.16/0.17 stdlib). The 182 uses mentioned in `docs/zig-0.17-port-plan.md` suggest this is a stable internal abstraction.
-
----
-
-## 3 Most Load-Bearing Facts
-
-1. **The binary is a self-contained AI agent harness with no external Zig dependencies.** It directly implements a full REPL, HTTP serve bridge, multi-provider LLM client, parallel tool executor, subagent/workflow engine, and MCP client—all in ~13k lines of Zig using only `std` and `std.Io`.
-2. **The stall-watchdog is load-bearing for reliability.** Every streaming read (headers, SSE lines, peek-ahead) is raced against a 120-second `Io.Select` deadline. Without it, half-open/dead TLS sockets would hang the agent indefinitely, especially in `--json` / GUI sessions where there is no TTY Esc escape.
-3. **`mcp.zig` is the gateway to external tool ecosystems.** The `Registry` spawns stdio servers, serializes JSON-RPC per server via mutex, rewrites `oneOf` to `anyOf` for OpenAI compatibility, and exposes tools to the orchestrator under qualified names (`mcp__<server>__<tool>`).
-
----
-
-## 1 Open Question
-
-**What is `std.Io` and where is it maintained?** It is referenced 182+ times (`Io.Select`, `Io.Future`, `Io.Group`, `Io.Mutex`, `Io.File.Reader/Writer`, `io.sleep`, `io.async`, etc.), but it is not part of the Zig standard library as of 0.16. It appears to be a custom async runtime layer. Is it a private fork of Zig, a vendored library, or a patched stdlib? Its stability is explicitly called out as the critical dependency for any future Zig 0.17 port.
diff --git a/.graff/subagents/sa-000-f57b1da8.md b/.graff/subagents/sa-000-f57b1da8.md
deleted file mode 100644
index 0cc909d5..00000000
--- a/.graff/subagents/sa-000-f57b1da8.md
+++ /dev/null
@@ -1,159 +0,0 @@
-# subagent sa-000-f57b1da8
-
-- label: risk hotspots
-- kind: workflow_task
-- status: ok
-- elapsed_ms: 245698
-- tools: codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,read_file,codedb,codedb,codedb,codedb,codedb,codedb,bash,bash,bash,read_file,codedb,codedb,codedb,codedb
-
-## task
-
-Review the current repository for complexity hotspots, likely bugs, TODOs, security/performance concerns, and areas needing tests or cleanup. Use codedb first (tree, context, search, outline, callers) before bash grep/find. Do not edit files; report findings with file paths and rationale.
-
-## report
-
-## Defensible findings
-
-### 1) Unauthenticated localhost debug bridge can execute arbitrary JS in the Tauri webview
-**File:** `gui/src-tauri/src/debug_bridge.rs:91`, `gui/src-tauri/src/debug_bridge.rs:137`, `gui/src-tauri/src/debug_bridge.rs:188`, `gui/src-tauri/src/debug_bridge.rs:291`
-**Rationale:** In debug builds, the app starts an HTTP server on `127.0.0.1:9233` with no token/origin check. `POST /eval` accepts arbitrary `code`, interpolates it raw into a JS snippet, and evaluates it in the main Tauri webview. Responses include `Access-Control-Allow-Origin: *`.
-
-**Breaking sequence:**
-1. Developer runs a debug build of the GUI.
-2. Attacker-controlled web page or local process sends `POST http://127.0.0.1:9233/eval` with body like `{"code":"window.__TAURI_INTERNALS__.invoke('open_external_url',{url:'https://attacker.example'})"}` or code that drives privileged app APIs exposed to the webview.
-3. `handle_eval` embeds the supplied code at line 188 and calls `window.eval` at line 200.
-4. The attacker’s code runs inside the desktop app context.
-
-**Impact:** Localhost RCE-equivalent inside the debug app context. Debug-only reduces production risk, but it is still dangerous for developers because a browser page can target localhost services.
-
----
-
-### 2) MCP requests can hang forever on a silent/broken server
-**File:** `src/mcp.zig:410`–`src/mcp.zig:428`
-**Rationale:** `request()` writes a JSON-RPC request, then loops on `takeDelimiter('\n')` until it sees a matching `id`. There is no timeout, cancellation, or child liveness check beyond EOF.
-
-**Breaking sequence:**
-1. Workspace contains `.mcp.json` with a server like:
- ```json
- {
- "mcpServers": {
- "bad": { "command": "sleep", "args": ["999999"] }
- }
- }
- ```
-2. Registry startup calls `startServer()`.
-3. `startServer()` calls `request(..., "initialize")` at `src/mcp.zig:286`.
-4. `request()` blocks forever at `src/mcp.zig:422` because the process never writes a newline-delimited response.
-5. Startup or `/mcp trust` never completes.
-
-**Impact:** A malformed or hostile workspace MCP config can wedge the harness/GUI integration. This needs a request timeout and process cleanup path.
-
----
-
-### 3) Malformed `.mcp.json` can crash instead of failing closed
-**File:** `src/mcp.zig:103`, `src/mcp.zig:111`, `src/mcp.zig:250`
-**Rationale:** Several JSON values are accessed as `.object` or `.string` without checking the active union tag.
-
-**Breaking sequences:**
-- If `.mcp.json` contains:
- ```json
- { "mcpServers": [] }
- ```
- then `parsed.object.get("mcpServers").object` at `src/mcp.zig:103` accesses `.object` on an array value.
-
-- If `.mcp.json` contains:
- ```json
- { "mcpServers": { "x": [] } }
- ```
- then `entry.value_ptr.*.object` at `src/mcp.zig:111` accesses `.object` on an array value.
-
-- If `.mcp.json` contains:
- ```json
- {
- "mcpServers": {
- "x": {
- "command": "node",
- "env": { "TOKEN": 123 }
- }
- }
- }
- ```
- then `e.value_ptr.*.string` at `src/mcp.zig:250` accesses `.string` on an integer value.
-
-**Impact:** In safe builds this is a runtime panic; in unsafe/optimized contexts it risks undefined behavior. Workspace config is user-/repo-controlled, so this should be validated defensively and covered by malformed-config tests.
-
----
-
-### 4) Predictable temp-file writes can follow attacker-created symlinks
-**File:** `gui/src-tauri/src/commands.rs:264`–`gui/src-tauri/src/commands.rs:267`
-**Rationale:** `save_pasted_image` writes to a predictable path under the shared temp directory: `codegraff-pasted/paste-<pid>-<counter>.<ext>`. It uses `std::fs::write`, which follows symlinks.
-
-**Breaking sequence:**
-1. Local attacker creates `/tmp/codegraff-pasted` if it does not already exist and makes it writable.
-2. Attacker predicts or observes the GUI PID and creates a symlink such as:
- ```sh
- ln -s "$HOME/.zshrc" "/tmp/codegraff-pasted/paste-12345-0.png"
- ```
-3. User pastes an image into the GUI.
-4. `save_pasted_image` writes bytes to the symlink target at line 267.
-
-**Impact:** Local same-user or same-machine file clobber. Use a private `tempfile`/`NamedTempFile`-style creation with `O_EXCL` and a per-user 0700 directory.
-
----
-
-### 5) The debug screenshot endpoint uses a fixed temp filename
-**File:** `gui/src-tauri/src/debug_bridge.rs:249`–`gui/src-tauri/src/debug_bridge.rs:259`
-**Rationale:** `capture_screenshot` always writes the full-screen capture to `std::env::temp_dir().join("cg_debug_full.png")`.
-
-**Breaking sequence:**
-1. A local attacker pre-creates `/tmp/cg_debug_full.png` as a symlink to another writable user file.
-2. Developer calls `GET http://127.0.0.1:9233/screenshot` while running a debug build.
-3. `screencapture -x /tmp/cg_debug_full.png` writes through the symlink or overwrites the predictable file.
-
-**Impact:** Local file clobber in debug builds, plus stale/racy screenshots when multiple app instances or requests run. Use a securely created unique temp file and delete it.
-
----
-
-## Complexity hotspots / likely maintenance risks
-
-- **`gui/src-tauri/src/runtime/simple.rs` — 4,499 lines.** This file owns runtime state, provider auth, model selection, MCP config, persistence, child-process sessions, git commands, and tests. The most failure-prone areas are:
- - session lifecycle / queued prompts: `send_prompt`, `stream_turn`, `send_control`, `acquire_session_io`;
- - provider credential detection and env bootstrapping;
- - persistence with best-effort ignored errors.
-- **`gui/src/app/sessionStore.ts` — 924 lines.** Central client-side state with selection, drafts, attachments, request timing, view caching, and async request de-duplication. Race-prone; needs broad regression coverage.
-- **`gui/src-tauri/src/commands.rs` — 959 lines.** Large Tauri command surface; security-sensitive functions live next to ordinary UI glue.
-- **`gui/src/services/desktop/client.ts` — 802 lines.** Contains both real Tauri client and QA mock mode. Risk: mock drift from generated contracts.
-- **`gui/src/components/providers-settings/ProviderSetupDialog.tsx` — 697 lines.** Complex provider auth state machine; likely needs more integration tests around failure/retry/cancel.
-- **`src/mcp.zig` — MCP stdio client.** Small enough to reason about but currently has the most concrete robustness issues: no timeout and unsafe JSON shape assumptions.
-
----
-
-## TODOs / stubs / cleanup
-
-- `grep` did not find meaningful source TODO/FIXME comments beyond test fixtures and identifiers.
-- There are explicit MVP/stub/no-op areas:
- - `gui/src-tauri/src/runtime/simple.rs:1442`–`1488`: workflow sync/query/draft paths are placeholders.
- - `gui/src-tauri/src/runtime/simple.rs:1634`–`1649`: MCP OAuth login/logout explicitly unsupported.
- - `gui/src-tauri/src/lib.rs:12`–`15`, `18`–`22`: copied bridge/persistence modules retained for future parity.
-- Working tree has ignored runtime artifacts (`session-*.json`, `harness.trace.jsonl`, `harness.trajectory.jsonl`, `codedb.snapshot`, etc.) and untracked `.graff/` plus `apps/ios/build/...`. These are cleanup hazards even if ignored.
-
----
-
-## Areas needing tests
-
-1. **MCP malformed config tests** for non-object `mcpServers`, non-object server entries, non-string env values.
-2. **MCP timeout tests** with a server that never responds or emits only notifications.
-3. **Debug bridge security tests** asserting either disabled-by-default behavior or required auth token.
-4. **Temp file safety tests** for pasted images: no symlink following, private directory permissions, unique paths.
-5. **Runtime session lifecycle tests** around:
- - queued prompt order;
- - stop while streaming;
- - control messages during active runs;
- - dropped child and retry behavior.
-6. **Provider auth retry/cancel tests** for the large settings dialog + runtime provider code.
-
----
-
-## Verdict
-
-**Most dangerous defect:** the unauthenticated debug bridge at `gui/src-tauri/src/debug_bridge.rs:91`/`137`/`188`, because any local process or reachable browser context can drive arbitrary JS execution inside a debug Tauri app with no shared secret or origin validation.
diff --git a/.graff/subagents/sa-001-546805fc.md b/.graff/subagents/sa-001-546805fc.md
deleted file mode 100644
index 2c3044e5..00000000
--- a/.graff/subagents/sa-001-546805fc.md
+++ /dev/null
@@ -1,180 +0,0 @@
-# subagent sa-001-546805fc
-
-- label: feature inventory
-- kind: workflow_task
-- status: ok
-- elapsed_ms: 240385
-- tools: codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,bash!,bash!,bash!,bash!,bash!,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb
-
-## task
-
-Inventory the main product features/user-facing flows in this repository. Use codedb first (tree, search, outline, symbol, callers, context) before bash grep/find. Identify important components/services/routes/APIs and how they connect. Do not edit files.
-
-## report
-
-## Verified inventory of main product features / user-facing flows
-
-### 1. Core product: `graff` agent harness (CLI/REPL + one-shot + JSON protocol)
-- The repository’s primary CLI is `graff`, described as a minimal agentic coding harness that talks to Anthropic, OpenAI-compatible endpoints, and ChatGPT/Codex subscription credentials. `README.md:1-6`
-- The harness loop sends user text to a model, executes model-requested tools in parallel, feeds results back, and repeats until the model stops. `README.md:17-28`
-- User-facing install/run flows include `graff`, `graff --model ...`, `graff -p "prompt"` one-shot mode, login/key management, `--schema`, and JSON protocol mode. `README.md:279-300`
-- The REPL exposes slash commands such as `/model`, `/plan`, `/key`, `/reasoning`, `/compact`, `/save`, `/resume`, `/todo`, `/mcp`, and `/help`. `README.md:317-346`
-- The harness supports permission-gated tools (`bash`, file reads/writes/edits, MCP tools), plus modes such as `yolo`, `plan`, and `strict`. `README.md:364-398`
-- The harness supports subagents and workflow fan-out, including an “ultracode” codeword that steers work into multi-agent workflow mode. `README.md:541-560`
-
-### 2. Desktop GUI / Codegraff app shell
-- The desktop app is a Tauri GUI over the `graff` agent CLI; README says the macOS desktop app installs a `codegraff` launcher and runs whatever `graff` is on `PATH`. `README.md:46-51`
-- The React app boots through `SessionProvider`, `DragDropProvider`, and `AppShell`; `/success` is a special route for provider OAuth success UI. `gui/src/app/App.tsx:385-395`
-- `AppShell` renders a resizable sidebar + content area, global theme toggle, sidebar toggle, new-chat trigger, settings panes, and the main `WorkspaceBoard`. `gui/src/app/App.tsx:265-379`
-- The global Cmd/Ctrl+N shortcut calls the same `NewChatTrigger` flow as the button. `gui/src/app/App.tsx:235-250`
-- The content switches between settings (`ProvidersSettingsPane`, `McpSettingsPane`, `GeneralSettingsPane`) and the workspace/chat board. `gui/src/app/App.tsx:359-375`
-
-### 3. Session bootstrap, state, and live updates
-- `SessionProvider` calls `useSessionBootstrap`, persists the latest active workspace path in local storage, and exposes session actions through context. `gui/src/app/SessionProvider.tsx:89-103`, `gui/src/app/SessionProvider.tsx:651-655`
-- `useSessionBootstrap` subscribes to backend session-update events, gets an initial snapshot, tries to reopen the latest workspace, then falls back to creating a managed chat. `gui/src/hooks/useSessionBootstrap.ts:28-88`
-- Cold-start and single-instance `codegraff <path>` flows are wired through `drainPendingOpen` and `open-workspace-path`; `SessionProvider` opens either pending or forwarded paths. `gui/src/app/SessionProvider.tsx:151-178`
-- The Tauri backend stores cold-start CLI args in `PendingOpen`, emits `open-workspace-path` for second instances, and focuses the main window. `gui/src-tauri/src/lib.rs:53-63`, `gui/src-tauri/src/lib.rs:86-89`, `gui/src-tauri/src/lib.rs:197-200`
-
-### 4. Sidebar flows: saved workspaces, managed chats, projects, settings
-- `ProjectSidebar` has sections for saved “Workspaces”, standalone “Chats” / managed chats, and “Projects”. `gui/src/components/ProjectSidebar.tsx:244-423`
-- Sidebar actions include opening a project folder, selecting chats, opening saved workspaces, starting new chats, archiving conversations/workspaces, and renaming/deleting saved workspaces. `gui/src/components/ProjectSidebar.tsx:74-85`, `gui/src/components/ProjectSidebar.tsx:103-148`
-- In settings mode, the sidebar becomes a settings navigator with General, Providers, and MCP sections. `gui/src/components/ProjectSidebar.tsx:150-225`
-
-### 5. New chat / onboarding / project setup
-- `NewChatScreen` is the empty or draft conversation surface; it wires onboarding, provider setup, clone-repository dialog, quick-start project dialog, launch actions, and a prompt section. `gui/src/components/new-chat-screen/NewChatScreen.tsx:81-143`, `gui/src/components/new-chat-screen/NewChatScreen.tsx:259-303`
-- The onboarding panel appears when there are no command results and setup is incomplete, based on provider/workspace state. `gui/src/components/new-chat-screen/NewChatScreen.tsx:192-200`
-- Project setup supports “open folder”, “clone repository”, and “quick start” flows; the controller calls `pickDirectory`, `cloneRepository`, `quickStartProject`, and `openProject`. `gui/src/components/new-chat-screen/hooks/useNewChatScreenController.ts:149-190`, `gui/src/components/new-chat-screen/hooks/useNewChatScreenController.ts:197-251`
-- Backend clone runs `git clone`; backend quick-start runs `gh repo create --clone --add-readme`, validates names, and returns the created directory path. `gui/src-tauri/src/commands.rs:839-884`, `gui/src-tauri/src/commands.rs:913-936`
-
-### 6. Conversation/chat flow
-- `ConversationPanel` chooses between `NewChatScreen`, a loading spinner, or the active chat thread + prompt composer. `gui/src/components/ConversationPanel.tsx:65-79`, `gui/src/components/ConversationPanel.tsx:93-127`
-- The chat display uses `ChatThread` for messages and local command results, while `PromptComposer` handles followups, goal chips, plan/interrupt prompts, todos, and the prompt input. `gui/src/components/ConversationPanel.tsx:112-126`, `gui/src/components/PromptComposer.tsx:167-234`
-- Existing chats and bound chat tiles submit prompts through `useConversationActions`; it appends file/image attachments into the prompt, supports Ultra mode injection, clears composer state, calls `desktopClient.sendPrompt`, and applies the returned snapshot. `gui/src/hooks/useConversationActions.ts:91-135`
-- Draft/new-chat submission in `SessionProvider` does the same first-message flow, selecting agent `muse` for planning mode or `forge` otherwise. `gui/src/app/SessionProvider.tsx:563-627`
-
-### 7. Prompt composer capabilities
-- The prompt card supports slash-command autocomplete, model picker, reasoning-effort picker, Plan mode, Fast mode, Ultra mode, stop/send behavior, prompt history navigation, drag-drop attachments, and pasted image attachments. `gui/src/components/PromptInputCard.tsx:93-181`, `gui/src/components/PromptInputCard.tsx:199-327`, `gui/src/components/PromptInputCard.tsx:329-621`
-- Pasted images are persisted through the Tauri `save_pasted_image` command, then classified as attachments. `gui/src/components/PromptInputCard.tsx:298-325`, `gui/src-tauri/src/commands.rs:252-269`
-- Image thumbnails are generated by a backend `image_thumbnail` command that decodes/downscales/re-encodes images as JPEG data URLs. `gui/src-tauri/src/commands.rs:271-292`
-
-### 8. Slash command flow
-- The prompt composer first tries to route a draft as a slash command before sending it as a normal prompt. `gui/src/components/PromptComposer.tsx:73-78`
-- `useCommandRouter` parses `/command args`, handles local UI commands such as plan/act, new chat, provider settings, MCP settings, delete/archive, compact, and routes other commands to `desktopClient.runSlashCommand`. `gui/src/hooks/useCommandRouter.ts:36-47`, `gui/src/hooks/useCommandRouter.ts:89-117`, `gui/src/hooks/useCommandRouter.ts:120-181`
-- Commands needing free-form arguments are completed into the draft instead of immediately run. `gui/src/hooks/useCommandRouter.ts:15-25`, `gui/src/hooks/useCommandRouter.ts:184-217`
-- Backend command inventory currently includes `/help`, `/agent`, `/goal`, `/loop`, `/bash`, `/compact`, `/workspace-status`, and `/ultracode`. `gui/src-tauri/src/runtime/simple.rs:450-465`
-- Backend command execution handles agent status, persistent ultracode toggle, goal get/set/clear, autonomous `/loop`, conversation compaction, shell `/bash`, and workspace git status payloads. `gui/src-tauri/src/runtime/simple.rs:1236-1428`
-
-### 9. Backend prompt execution / streaming
-- Tauri command `send_prompt` forwards frontend prompt submissions to `DesktopState.manager.send_prompt`. `gui/src-tauri/src/commands.rs:155-165`
-- `RuntimeManager.send_prompt` creates or selects a conversation, appends the user message, queues prompts if a request is already active, emits a snapshot, optionally auto-generates a title, and then streams the turn. `gui/src-tauri/src/runtime/simple.rs:470-688`
-- `stream_turn` writes a JSON user line into a long-lived `graff` session, then maps streamed events into GUI message types: assistant text, reasoning, tool starts/results, followup requests, errors, and turn completion. `gui/src-tauri/src/runtime/simple.rs:692-1005`
-- Runtime snapshots include active workspace/conversation, visible messages, active request IDs, todos, goal, followup, all conversation views, registered workspaces, and saved workspaces. `gui/src-tauri/src/runtime/simple.rs:2093-2215`
-
-### 10. Workspace board / multi-chat layout
-- `WorkspaceBoard` is a Dockview-based board that renders empty state, workspace draft, single chat, or saved-workspace multi-chat layouts. `gui/src/components/workspace-board/WorkspaceBoard.tsx:51-104`, `gui/src/components/workspace-board/WorkspaceBoard.tsx:538-586`
-- Dragging/adding a second chat converts a single-chat selection into a saved workspace by serializing Dockview layout and calling `createSavedWorkspace`. `gui/src/components/workspace-board/WorkspaceBoard.tsx:313-388`
-- Saved workspace layouts are restored from saved JSON and persisted on layout changes. `gui/src/components/workspace-board/WorkspaceBoard.tsx:63-83`, `gui/src/components/workspace-board/WorkspaceBoard.tsx:238-302`, `gui/src/components/workspace-board/WorkspaceBoard.tsx:439-481`
-- `ChatTile` is the inner Dockview layout for one chat; it hosts the conversation pane plus auxiliary preview, terminal, and changes panes. `gui/src/components/workspace-board/ChatTile.tsx:495-540`, `gui/src/components/workspace-board/ChatTile.tsx:729-781`
-- Per-conversation layout is saved and restored with `saveConversationLayout` / `getConversationLayout`. `gui/src/components/workspace-board/ChatTile.tsx:147-162`, `gui/src/components/workspace-board/ChatTile.tsx:572-608`
-
-### 11. Changes/diff/git flow
-- The Changes pane derives file changes from conversation messages, resolves renderable diffs, shows additions/deletions, lets files open in an editor, and shows commit/push actions when git actions are available. `gui/src/components/workspace-board/ChangesPane.tsx:199-246`, `gui/src/components/workspace-board/ChangesPane.tsx:248-349`
-- Git actions in session context include checkout branch, create branch, commit, push, and open workspace in a target app. `gui/src/app/SessionProvider.tsx:180-228`, `gui/src/app/SessionProvider.tsx:376-385`
-- Backend git commands route through `RuntimeManager` for checkout/create/commit/push. `gui/src-tauri/src/commands.rs:536-582`
-
-### 12. Terminal pane flow
-- `ChatTile` can open/close terminal panes, add terminal tabs, restart terminals, and confirm destructive closing of multiple terminals. `gui/src/components/workspace-board/ChatTile.tsx:343-385`, `gui/src/components/workspace-board/ChatTile.tsx:451-481`, `gui/src/components/workspace-board/ChatTile.tsx:746-779`
-- `useTerminalSession` creates a `WTerm`, subscribes to backend terminal output/exit/error events, opens a backend terminal, writes user input, resizes backend PTY size, and closes the backend terminal on cleanup. `gui/src/components/workspace-board/hooks/useTerminalSession.ts:148-235`, `gui/src/components/workspace-board/hooks/useTerminalSession.ts:253-272`
-- Tauri terminal API commands route to `state.terminal_manager.open/write/resize/close`. `gui/src-tauri/src/commands.rs:781-827`
-
-### 13. Provider setup/settings flow
-- Providers settings lists/searches providers, shows configured/unconfigured state, opens setup dialogs, removes configured providers, and refreshes prompt settings after changes. `gui/src/components/providers-settings/ProvidersSettingsPane.tsx:62-132`, `gui/src/components/providers-settings/ProvidersSettingsPane.tsx:134-328`
-- Provider setup supports multiple auth kinds: API key, device code, CLI login, and OAuth authorization code. `gui/src/components/providers-settings/ProviderSetupDialog.tsx:416-572`
-- Provider setup starts auth through `startProviderAuth`, completes through `completeProviderAuth`, listens for OAuth callbacks, and auto-polls CLI login completion via `listProviders`. `gui/src/components/providers-settings/ProviderSetupDialog.tsx:128-165`, `gui/src/components/providers-settings/ProviderSetupDialog.tsx:167-207`, `gui/src/components/providers-settings/ProviderSetupDialog.tsx:209-276`, `gui/src/components/providers-settings/ProviderSetupDialog.tsx:304-330`
-- Backend provider APIs are registered in Tauri and route to `RuntimeManager` methods. `gui/src-tauri/src/lib.rs:116-144`, `gui/src-tauri/src/commands.rs:95-141`
-
-### 14. MCP settings flow
-- MCP settings lists servers, reloads, imports JSON config, removes servers, and triggers login/logout when auth status is present. `gui/src/components/mcp-settings/McpSettingsPane.tsx:35-94`, `gui/src/components/mcp-settings/McpSettingsPane.tsx:96-275`
-- MCP backend commands are exposed through the desktop client (`listMcpServers`, `importMcpConfig`, `removeMcpServer`, `reloadMcpServers`, `loginMcpServer`, `logoutMcpServer`). `gui/src/services/desktop/client.ts:529-567`
-- Tauri routes these MCP commands to `RuntimeManager` methods. `gui/src-tauri/src/commands.rs:307-377`
-
-### 15. General settings / theme flow
-- General settings currently covers appearance mode and theme preset selection, persisted through `themeStore`. `gui/src/components/general-settings/GeneralSettingsPane.tsx:18-82`
-- The app-level theme toggle is also exposed in the shell. `gui/src/app/App.tsx:51-77`, `gui/src/app/App.tsx:269-272`
-
-### 16. Desktop API boundary / route map
-- The frontend desktop API boundary is `gui/src/services/desktop/client.ts`; all production calls go through `invokeCommand`, with QA mock mode swapping Tauri invocations for deterministic browser fixtures. `gui/src/services/desktop/client.ts:56-60`, `gui/src/services/desktop/client.ts:266-319`
-- Frontend API functions map directly to Tauri command names for workspace/session/chat, slash commands, prompt settings, providers, MCP, git, external open/read-file, layouts, saved workspaces, and terminal operations. `gui/src/services/desktop/client.ts:338-802`
-- Tauri registers the command surface with `tauri::generate_handler!`, covering the same product areas. `gui/src-tauri/src/lib.rs:108-174`
-- Most Tauri command handlers are thin adapters that call `DesktopState.manager`; terminal handlers call `DesktopState.terminal_manager`; clone/quick-start and file/image helpers are implemented directly in `commands.rs`. `gui/src-tauri/src/commands.rs:48-827`
-
-### 17. SDK / remote API product surface
-- The repo includes generated TypeScript and Python SDKs over `graff --json`; README says `graff --schema` is the machine-readable interface used to generate SDKs. `README.md:402-411`
-- SDK examples include Python `Harness` and TypeScript `Harness` / `runAgent`, with streamed event handling. `README.md:413-437`
-- Remote clients exist for `graff serve`, including `@graff-new/sdk/remote` and Python `RemoteHarness`. `README.md:439-443`
-- The `serve` mode exposes the same protocol over HTTP for clients that cannot spawn a local process, with NDJSON streaming and bearer-token support for non-loopback use. `README.md:735-746`
-
-## Important components/services/routes and how they connect
-
-```text
-React UI
- App.tsx
- -> SessionProvider
- -> useSessionBootstrap
- -> desktopClient.listenSessionUpdates / getSessionSnapshot / createManagedChat
- -> ProjectSidebar
- -> useSessionActions
- -> desktopClient workspace/chat/saved-workspace APIs
- -> WorkspaceBoard
- -> Dockview layouts
- -> ChatTile
- -> ConversationPanel
- -> ChatThread + PromptComposer
- -> PromptInputCard
- -> useCommandRouter / useConversationActions
- -> desktopClient.sendPrompt / runSlashCommand / stopPrompt / settings APIs
- -> ChangesPane
- -> readWorkspaceFile/openPathInTarget/git actions
- -> TerminalPane/useTerminalSession
- -> terminal_open/write/resize/close + terminal events
- -> Settings panes
- -> ProvidersSettingsPane / ProviderSetupDialog
- -> McpSettingsPane
- -> GeneralSettingsPane
-
-desktopClient.ts
- -> Tauri invoke(command_name)
- -> Tauri event listen(session-updated, provider OAuth callback, terminal output/exit/error)
-
-Tauri Rust
- lib.rs generate_handler![...]
- -> commands.rs thin adapters
- -> runtime/simple.rs RuntimeManager for sessions, prompts, commands, providers, MCP, git, saved layouts
- -> terminal_manager for PTY sessions
- -> direct helpers for clone, quick-start, image/file helpers
-
-graff runtime
- RuntimeManager.spawn/acquire session
- -> JSON stdin/stdout protocol with graff child
- -> streams text/tool/followup/error events into SessionSnapshot
-```
-
-Evidence for the frontend-to-backend boundary: `desktopClient.invokeCommand` wraps Tauri `invoke`, and all exported client functions call named backend commands. `gui/src/services/desktop/client.ts:311-319`, `gui/src/services/desktop/client.ts:338-802`
-Evidence for Tauri route registration: `generate_handler!` registers the desktop command surface. `gui/src-tauri/src/lib.rs:108-174`
-Evidence for session/prompt backend routing: `commands.rs` forwards `send_prompt`, `run_slash_command`, and many app actions to `state.manager`. `gui/src-tauri/src/commands.rs:155-180`, `gui/src-tauri/src/commands.rs:415-582`
-
-## Inferred, but strongly supported
-
-- The GUI is the main user-facing desktop product layer, while the Zig `graff` harness remains the core agent engine; this is inferred from README’s statement that the desktop app runs `graff` from `PATH` and from the Tauri runtime streaming through a `graff` session. `README.md:46-51`, `gui/src-tauri/src/runtime/simple.rs:692-707`
-- Saved workspaces are a GUI construct for arranging multiple chat panels, not a core CLI concept; this is inferred from Dockview layout serialization and `ProjectStore` saved-workspace APIs being used by the GUI/Tauri layer. `gui/src/components/workspace-board/WorkspaceBoard.tsx:365-384`, `gui/src-tauri/src/runtime/simple.rs:2178-2188`
-- The product’s “agent workbench” direction combines chat, code changes, terminals, git, providers, MCP, and multi-agent workflows into one desktop surface; this is inferred from the connected GUI panes and backend APIs rather than from a single product statement. `gui/src/components/workspace-board/ChatTile.tsx:495-540`, `gui/src/components/workspace-board/ChangesPane.tsx:279-349`, `gui/src/components/workspace-board/hooks/useTerminalSession.ts:148-235`, `gui/src/components/providers-settings/ProvidersSettingsPane.tsx:134-328`, `gui/src/components/mcp-settings/McpSettingsPane.tsx:96-275`
-
-## 3 most load-bearing facts
-
-1. **All desktop user flows cross one typed bridge:** `desktopClient.ts` exports the frontend API and maps directly to Tauri command names, while `lib.rs` registers the matching backend handlers. `gui/src/services/desktop/client.ts:338-802`, `gui/src-tauri/src/lib.rs:108-174`
-2. **Conversation state is snapshot/event driven:** frontend bootstraps via `getSessionSnapshot` and `listenSessionUpdates`, while backend `RuntimeManager.snapshot` materializes workspaces, conversations, messages, todos, goals, followups, and saved workspaces. `gui/src/hooks/useSessionBootstrap.ts:28-88`, `gui/src-tauri/src/runtime/simple.rs:2093-2215`
-3. **The main GUI product flow is chat-centric but workspace-aware:** `WorkspaceBoard` organizes one or many `ChatTile`s, each tile embeds conversation, changes, terminal, and layout persistence. `gui/src/components/workspace-board/WorkspaceBoard.tsx:51-104`, `gui/src/components/workspace-board/WorkspaceBoard.tsx:313-388`, `gui/src/components/workspace-board/ChatTile.tsx:495-540`
-
-## Open question
-
-- Which layer should be considered the canonical “product” for roadmap/inventory purposes: the Zig CLI/SDK harness, the Tauri desktop app, or both as one combined Codegraff product? The README foregrounds the CLI harness while also documenting the desktop app as a major install path. `README.md:1-6`, `README.md:46-51`
diff --git a/.graff/subagents/sa-001-59aa643c.md b/.graff/subagents/sa-001-59aa643c.md
deleted file mode 100644
index 6bdb9e76..00000000
--- a/.graff/subagents/sa-001-59aa643c.md
+++ /dev/null
@@ -1,234 +0,0 @@
-# subagent sa-001-59aa643c
-
-- label: Explore GUI frontend
-- kind: workflow_task
-- status: ok
-- elapsed_ms: 65697
-- tools: codedb,codedb,codedb,read_file,read_file,read_file,read_file,codedb,codedb,codedb,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file
-
-## task
-
-You are exploring the React/TypeScript frontend in gui/src/. Use the codedb tool (search, symbol, outline, callers, context) to thoroughly understand:
-1. The main app entry point (App.tsx, main.tsx) and overall architecture
-2. How sessions work (sessionStore, SessionProvider, useSession, sessionClientActions)
-3. How chat/activities are rendered (ChatThread, ChatActivityRow, activity results, file diffs)
-4. The workspace board layout (WorkspaceBoard, dockview, chat tiles, terminal panes)
-5. How settings and provider setup work (providers-settings, mcp-settings, general-settings)
-6. Key state management patterns and any bridge/communication to the Tauri backend
-
-Be thorough: read key symbols and trace data flow. Return a structured markdown report.
-
-## report
-
-# React/TypeScript Frontend Architecture Report (`gui/src/`)
-
-## 1. Main App Entry Point & Overall Architecture
-
-**Entry point:** `gui/src/main.tsx:1`
-- Renders `<App />` inside `StrictMode`.
-- Imports global styles: `dockview-react` CSS, `@codegraff/diffs` CSS, and local `index.css` / `diffs.css`.
-
-**App shell:** `gui/src/app/App.tsx:1`
-- `App` wraps `SessionProvider` → `DragDropProvider` → `AppShell`.
-- `AppShell` is the root layout: a resizable horizontal panel group (`ResizablePanelGroup`) with:
- - **Left:** `ProjectSidebar` (collapsible, animated width transitions).
- - **Right:** `WorkspaceBoard` (when no settings view), or one of `ProvidersSettingsPane` / `McpSettingsPane` / `GeneralSettingsPane`.
-- Global chrome includes:
- - Theme toggle (`AppThemeToggle`) using `useThemeStore` (`gui/src/app/themeStore.ts:1`).
- - Sidebar visibility control (`AppSidebarControl`).
- - A captured `NewChatTrigger` ref for global `Cmd/Ctrl+N` shortcut.
-- Fullscreen state is synced from Tauri’s `getCurrentWindow().isFullscreen()` via `onResized` / `onFocusChanged` listeners (`App.tsx:65`).
-
-**Verified:** The app bootstraps in `SessionProvider`, shows a spinner until `isSessionBootstrapped` is true, then renders the full shell.
-
----
-
-## 2. Sessions (`sessionStore`, `SessionProvider`, `useSession`, `sessionClientActions`)
-
-### 2.1 Store (`gui/src/app/sessionStore.ts:1`)
-- Built on **Zustand vanilla** (`createStore`), not React context, for performance.
-- Core state shape (`SessionStoreState`):
- - `selection: WorkspaceBoardSelection` — what the board shows (`empty`, `single-chat`, `workspace-draft`, `saved-workspace`).
- - `workspaces`, `workspacesByPath`, `conversationSummariesByKey`, `conversationViewsByKey`.
- - `promptDraftsByKey`, `attachmentsByKey`, `workspaceMetaByKey` (runtime status + prompt settings).
- - `requestTimingsByConversationId` — tracks start/completion times per request.
-- `applySessionSnapshot(snapshot)` is the primary reducer: it rebuilds `conversationViewsByKey`, `conversationSummariesByKey`, updates `selection`, and computes request timings by diffing `activeRequestIds` (`sessionStore.ts:315`).
-- Memoized helper selectors (`getUiActiveWorkspacePath`, `getUiActiveConversationId`, `getUiActiveBinding`) respect the `selection` override vs. the snapshot’s `activeWorkspacePath`/`activeConversationId`.
-
-### 2.2 `SessionProvider` (`gui/src/app/SessionProvider.tsx:1`)
-- Wraps children in `SessionActionsContext.Provider` with a memoized `actionState` object containing ~20 async actions.
-- Key actions:
- - `openWorkspaceByPath` — calls `desktopClient.openWorkspace`, then `applySessionSnapshot` + `syncBoardSelectionFromSnapshot`.
- - `selectConversation` — optimistic UI update (`setBoardSelection`), then fetches snapshot via `desktopClient.selectConversation`, with revert on failure.
- - `startNewChat` — reuses a “managed chat” draft if available, otherwise creates a new one.
- - `submitPrompt` — reads the draft from `sessionStore`, appends attachments, clears draft, calls `desktopClient.sendPrompt`, then migrates the draft/attachments to the new conversation key.
-- Bootstrapping: `useSessionBootstrap` (`gui/src/hooks/useSessionBootstrap.ts:1`) is used inside `SessionProvider`:
- - Listens to `SESSION_UPDATED_EVENT_NAME` (`codegraff://session-updated`).
- - Fetches `getSessionSnapshot`; if no active workspace, restores the latest from `localStorage` (`LATEST_WORKSPACE_STORAGE_KEY`), or falls back to `createManagedChat`.
-
-### 2.3 `useSession` hook (`gui/src/hooks/useSession.ts:1`)
-- Thin Zustand selectors over `sessionStore`.
-- `useConversationSession(binding?)` returns:
- - `messages`, `activeRequestIds`, `requestTimingsById`, `followupRequest`, `todos`, `workspacePath`, `isConversationLoading`, `activeWorkspaceConfigured`, etc.
-- `usePromptDraft(binding?)` returns draft state + `canCompose` (blocked by unconfigured workspace, pending followup, pending draft, or running conversation).
-- `useWorkspaceMeta(workspacePath)` auto-fetches `runtimeStatus` and `promptSettings` on mount via `ensureWorkspaceRuntimeStatusLoaded` / `ensureWorkspacePromptSettingsLoaded`.
-
-### 2.4 Client actions (`gui/src/app/sessionClientActions.ts:1`)
-- Thin async wrappers around `desktopClient` calls that also update `sessionStore` after success.
-- Examples: `runWorkspaceRuntimeStatusAction`, `updateWorkspacePromptSettings`, `submitFollowupResponse`, `openWorkspaceInTarget`.
-
----
-
-## 3. Chat / Activities Rendering
-
-### 3.1 `ChatThread` (`gui/src/components/chat/ChatThread.tsx:1`)
-- Uses `@legendapp/list/react` (`LegendList`) for virtualized rendering of `ChatThreadItem[]`.
-- **Auto-scroll logic:** tracks `isFollowingRef` / `userWantsFollowRef`. Locks to bottom while `isFollowing` is true; user scroll-up breaks the lock and shows a “Scroll to latest” pill with `pendingCount` of new items.
-- Items are built by `buildChatThreadItems(messages, activeRequestIds)` (`gui/src/components/chat/utils/chatThread.ts:1`).
-
-### 3.2 Thread item builder (`gui/src/components/chat/utils/chatThread.ts:1`)
-- Walks `TranscriptMessage[]` and groups tool calls into `ActivityItem` groups scoped by `requestId` + scope index.
-- Message kinds handled:
- - `user` / `context_compacted` → message item + starts a new scope.
- - `assistant` / `error` → message item.
- - `reasoning` → merged into a “Thinking” activity group.
- - `tool_start` → operation pushed into current group.
- - `status_output` → appended to the latest open operation’s `outputText`.
- - `tool_end` → marks operation completed, sets `isError`, `summary`, `resultDetail`.
- - `status` → displayed as standalone message (unless decorative debug).
-- Final pass inserts `request_work` items after their anchor message.
-
-### 3.3 `ChatActivityRow` (`gui/src/components/chat/ChatActivityRow.tsx:1`)
-- Renders each `ActivityItem` inside a `Collapsible`.
-- If `isThinking`, shows a “Thinking” label with optional reasoning text rendered as `ChatMarkdown`.
-- Otherwise shows a summary label (e.g., “Explored 3 files”, “Ran 2 commands”) and a list of `ActivityOperationRow`.
-- Auto-opens on running→idle transition if error; preserves user-open state otherwise.
-
-### 3.4 `ActivityOperationRow` (`gui/src/components/chat/ChatActivityRow.tsx:115`)
-- Maps `operation.detail.kind` to icons (`file_read`, `file_update`, `shell`, `search`, `fetch`, `plan`, `skill`, `task`, `todo_*`, `unknown`).
-- Expandable rows show `ActivityResultRenderer` inside `CollapsibleContent`.
-
-### 3.5 Activity results (`gui/src/components/chat/activity-results/ActivityResultRenderer.tsx:1`)
-- Two result types:
- - **`file_diff`** → `FileDiffResult` (`gui/src/components/chat/activity-results/FileDiffResult.tsx:1`):
- - Uses `useRenderableFileDiff` to parse the patch; if the patch is missing, reads the workspace file via `read_workspace_file` Tauri command to synthesize a full-file diff.
- - Renders via `@codegraff/diffs/react` `PatchDiff`.
- - Shows `+additions` / `-deletions` stats.
- - If `canOpenInEditor`, clicking the filename opens it via `openWorkspacePathInTarget` (uses `resolvedPreferredAppId`, e.g., VS Code).
- - **`content`** → `ContentResult` (plain text/card).
-
----
-
-## 4. Workspace Board Layout (`WorkspaceBoard`, `dockview`, tiles, panes)
-
-### 4.1 Outer board (`WorkspaceBoard.tsx:1`)
-- Uses `dockview-react` (`DockviewReact`) as the outer layout engine.
-- Selection kinds drive the board:
- - `empty` → `NewChatScreen`.
- - `workspace-draft` → `ConversationPanel` (single pane, no dockview).
- - `single-chat` → builds a default outer layout with one chat panel.
- - `saved-workspace` → restores layout from `layoutJson` via `applySavedWorkspaceLayout`; on failure falls back to bindings list.
-- **Chat panels:** Each panel id is `chat:<workspacePath>::<conversationId>`. Component = `OUTER_CHAT_COMPONENT` which renders `ChatTile`.
-- **Drag & drop:** Supports dragging chats between outer panels (custom MIME type `application/x-codegraff-chat-binding`). Dropping a chat on the board creates/activates it.
-- **Persistence:** Layout changes are persisted via `desktopClient.updateSavedWorkspaceLayout` for saved workspaces.
-
-### 4.2 Chat tile (`ChatTile.tsx:1`)
-- Each chat tile contains its **inner** `DockviewReact` with:
- - `INNER_CHAT_COMPONENT` → `ConversationPanel` (the actual chat + composer).
- - `INNER_PLACEHOLDER_COMPONENT` → auxiliary panes: `ChangesPane`, `TerminalPane`, or generic `PlaceholderPane`.
-- **Auxiliary panes:**
- - `changes` (right of chat) — shows workspace file changes.
- - `terminal` (bottom, spanning full width) — opens a PTY via Tauri `terminal_open`; supports multiple tabs; each tab has its own `terminalKey` and PTY session.
- - `preview` (right of chat).
-- **Header actions:** `ConversationDockviewHeaderActions` when chat is active; terminal-specific actions (new tab, restart, close) when a terminal tab is active.
-- **Constraints:** `applyChatTileLayoutConstraints` locks group headers; `autoCloseUndersizedSidePanes` closes side panes dragged below 180px.
-- **Programmatic mutation guard:** Prevents auto-close during programmatic pane open/add.
-
-### 4.3 Layout utilities (`gui/src/components/workspace-board/layout.ts:1`, `chatTileLayout.ts:1`)
-- `serializeDockviewLayout` / `parseDockviewLayoutJson` convert to/from JSON.
-- `extractBindingsFromSerializedLayout` extracts `ChatBinding[]` from persisted layouts.
-- Terminal ids are namespaced: `terminal:<workspacePath>::<conversationId>::<terminalKey>`.
-- Custom events (`PANE_CLOSE_REQUEST_EVENT_NAME`, `TERMINAL_RESTART_EVENT_NAME`) decouple close/restart requests from the UI tree.
-
----
-
-## 5. Settings & Provider Setup
-
-### 5.1 General settings (`gui/src/components/general-settings/GeneralSettingsPane.tsx:1`)
-- `themeStore` (`gui/src/app/themeStore.ts:1`) persists `mode` (light/dark) and `preset` (e.g., `warm-graphite`, `slate`) to `localStorage`.
-- `applyTheme` runs at module import (before React) to prevent flash.
-
-### 5.2 Providers settings (`gui/src/components/providers-settings/ProvidersSettingsPane.tsx:1`)
-- Uses `useProviderSetup` hook (not fully read, but it calls `listProviders`, `startProviderAuth`, etc.).
-- Lists providers from `desktopClient.listProviders(workspacePath)`.
-- Each row shows: name, configured status, auth methods, env override hint.
-- **Auth methods:**
- - `ApiKey` → dialog with key input; calls `completeProviderAuth` which runs `graff key set <provider> <key>`.
- - `CodegraffDevice` / `CodexDevice` / `KimiDevice` → launches Terminal with `graff login [target]` via a temp `.command` script (`runtime/simple.rs:1666`).
-- **Remove provider:** deletes keychain / JSON fallback / login files; surfaces an error if an env var still overrides it (`commands.rs:375`).
-
-### 5.3 MCP settings (`gui/src/components/mcp-settings/McpSettingsPane.tsx:1`)
-- Calls `listMcpServers`, `reloadMcpServers`, `removeMcpServer`, `importMcpConfig`.
-- Servers are read from workspace `.mcp.json`.
-- Supports `user` vs `local` scope import (writes to workspace `.mcp.json`).
-- `login/logout` buttons exist but are no-ops in the MVP adapter because graff only runs stdio MCP servers.
-
----
-
-## 6. State Management Patterns & Tauri Backend Bridge
-
-### 6.1 Frontend → Backend
-- **Single service file:** `gui/src/services/desktop/client.ts:1` wraps every Tauri command.
-- Uses `invoke<T>(command, args)` from `@tauri-apps/api/core`.
-- **QA mock mode:** When `import.meta.env.VITE_CODEGRAFF_QA_MOCK === "1"`, `client.ts` short-circuits to deterministic mock snapshots/responses so the UI can be tested in a browser without Tauri.
-
-### 6.2 Backend → Frontend (events)
-- `listenSessionUpdates` listens to `codegraff://session-updated` (`emitter.rs:1`).
-- `listenTerminalOutput` / `listenTerminalExit` / `listenTerminalErrors` listen to terminal-specific events.
-- `TauriEventEmitter` (`emitter.rs:20`) implements `UiEventEmitter` and pushes `SessionSnapshotDto`, `TerminalOutputEventDto`, etc. into the webview via `tauri::Emitter`.
-
-### 6.3 Backend runtime (`gui/src-tauri/src/runtime/simple.rs:1`)
-- `RuntimeManager` coordinates the GUI with a persistent `graff --json` child process per conversation.
-- **Session lifecycle:** `acquire_session_io` spawns `graff --json --yolo` (with login-shell env injection for macOS); reuses the child across turns; drops it on `stop_prompt` or error.
-- **Streaming protocol:** `stream_turn` reads JSONL events from `graff` stdout:
- - `text` → `Assistant` message (appended live).
- - `reasoning` → `Reasoning` message.
- - `tool_call` / `tool_result` → `ToolStart` / `ToolEnd`.
- - `ask_user` → creates a `FollowupRequestDto` and stores it in `pending_followups`; UI renders via `followup` in conversation view.
- - `error` / `turn` → ends the turn.
-- After each event, `emit()` calls `snapshot()` and pushes the full `SessionSnapshotDto` to the frontend, which then `applySessionSnapshot`s it.
-
-### 6.4 Persistence (backend)
-- Conversations are persisted to `~/.codegraff-gui/conversations.json` (`simple.rs:1582`).
-- Prompt settings (model/effort/fast) persisted to `~/.codegraff-gui/prompt-settings.json`.
-- Saved workspace layouts and conversation layouts stored via `ProjectStore` (`project_store.rs`).
-
----
-
-## Verified vs. Inferred
-
-| Claim | Status | Evidence |
-|-------|--------|----------|
-| Zustand vanilla store is the single source of truth | **Verified** | `sessionStore.ts:1` creates store with `createStore`; `useSession.ts:134` uses `useStore(sessionStore, selector)`. |
-| `graff --json` is spawned per conversation and reused | **Verified** | `runtime/simple.rs:1057` `spawn_graff_session`; `acquire_session_io` reuses existing sessions; `drop_session` kills on error. |
-| Session snapshots are emitted after every JSONL event | **Verified** | `simple.rs:1181` `self.emit().await?` inside the `text`, `reasoning`, `tool_call`, `tool_result`, `ask_user` branches. |
-| `login_shell_env` is used to fix macOS env isolation | **Verified** | `simple.rs:1548` `login_shell_env()` runs `env` via the user’s login shell and injects the map into the graff child. |
-| Dockview is used for both outer board and inner chat tile | **Verified** | `WorkspaceBoard.tsx:226` outer `DockviewReact`; `ChatTile.tsx:319` inner `DockviewReact`. |
-| MCP login/logout are no-ops in the current adapter | **Verified** | `simple.rs:1448` `login_mcp_server` and `logout_mcp_server` bail with “graff runs stdio MCP servers only”. |
-| `read_workspace_file` has a sandbox containment check | **Verified** | `commands.rs:539` canonicalizes workspace + path, checks `starts_with`, caps size at 512KB, rejects non-files. |
-
----
-
-## 3 Load-Bearing Facts
-
-1. **The entire frontend state is reconciled from backend-issued `SessionSnapshot` DTOs.** The `sessionStore` does not optimistically update messages; it only updates `promptDrafts` and `selection` locally. Every streaming token arrives via Tauri event → `applySessionSnapshot`, which rebuilds `conversationViewsByKey` and timing maps (`sessionStore.ts:315`). This means the frontend is essentially a reactive projection of the backend `RuntimeManager` state.
-
-2. **`WorkspaceBoard` selection state determines the Dockview outer layout, not the other way around.** The board reacts to `selection` (empty / single-chat / saved-workspace) by resetting or restoring the outer Dockview. When the user drags a chat panel in a saved workspace, the layout JSON is serialized and sent back to Tauri (`desktopClient.updateSavedWorkspaceLayout`), and the active chat binding is updated in the store (`WorkspaceBoard.tsx:127`).
-
-3. **The backend spawns a persistent `graff --json` child per conversation and streams JSONL events into `SessionSnapshotDto`s that are pushed to the frontend.** This is the primary bridge: commands are RPC via `invoke`, and live updates are events via `emit_session_updated`. The frontend has no WebSocket or SSE; it relies entirely on Tauri’s `invoke` + `listen` abstraction.
-
----
-
-## 1 Open Question
-
-- **How does the frontend handle backpressure or out-of-order `session-updated` events?** The `useSessionBootstrap` hook sets `receivedSessionUpdateRef` to avoid overwriting a newer event with an older snapshot during bootstrap, but there is no explicit sequence numbering or debouncing in `sessionStore.applySessionSnapshot`. If two events arrive close together, the Zustand store will apply both in order, but React components may re-render with intermediate states. Is this acceptable because the backend only emits snapshots sequentially from a single `RuntimeManager` mutex, or should the frontend add a generation/version counter to drop stale snapshots?
diff --git a/.graff/subagents/sa-002-0e4162b9.md b/.graff/subagents/sa-002-0e4162b9.md
deleted file mode 100644
index 2e40b992..00000000
--- a/.graff/subagents/sa-002-0e4162b9.md
+++ /dev/null
@@ -1,262 +0,0 @@
-# subagent sa-002-0e4162b9
-
-- label: Explore Tauri Rust backend
-- kind: workflow_task
-- status: ok
-- elapsed_ms: 77038
-- tools: codedb,codedb,codedb,read_file,read_file,read_file,read_file,read_file,read_file!,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,codedb,codedb
-
-## task
-
-You are exploring the Rust Tauri backend in gui/src-tauri/src/. Use the codedb tool (search, symbol, outline, callers, context) to thoroughly understand:
-1. The main lib.rs and main.rs entry points
-2. The commands.rs (Tauri commands exposed to the frontend) — what capabilities are exposed
-3. The runtime module (runtime/simple.rs) — what does it do, how does it manage sessions/processes
-4. The bridge modules (bridge/*, desktop_open.rs, debug_bridge.rs) — how does the frontend talk to the Zig core or OS
-5. DTOs (dto/*) — what data types are exchanged between frontend and backend
-6. Persistence and terminal handling
-
-Be thorough: read key symbols and trace data flow. Return a structured markdown report.
-
-## report
-
-# Rust Tauri Backend Report — `gui/src-tauri/src/`
-
-## 1. Entry Points (`lib.rs` & `main.rs`)
-
-**`main.rs`** is a minimal 7-line launcher that prevents a console window on Windows in release builds and delegates to `codegraff_gui_lib::run()` (`gui/src-tauri/src/main.rs:4`).
-
-**`lib.rs`** is the real bootstrap (`gui/src-tauri/src/lib.rs`):
-
-- **Plugin registration** (`L50`):
- - `tauri_plugin_single_instance` — handles `codegraff <path>` cold-start so a second invocation opens the path in the running window and focuses it.
- - `tauri_plugin_dialog` — native file dialogs.
- - `tauri_plugin_log` — dev-only logging.
-- **State setup** (`L65–L88`):
- - Creates `TauriEventEmitter` (wraps `tauri::AppHandle` for typed events).
- - Initializes `forge_config_home` (copies global Forge config into the app data dir once, then sets `FORGE_CONFIG`).
- - Opens `ProjectStore` SQLite DB at `app_data_dir/projects.db` and managed-chats folder.
- - Manages `DesktopState` (the runtime + terminal manager) and `PendingOpen` (stashes CLI argv for the frontend to drain on mount).
- - In debug builds, starts `DebugBridge` (localhost HTTP server on port 9233).
-- **Invoke handler** (`L93–L180`) — registers ~45 Tauri commands from `commands.rs` plus `cg_debug_eval_result`.
-- **Window event hook** (`L89–L92`) — on `Destroyed`, cancels pending follow-ups.
-
----
-
-## 2. Commands (`commands.rs`)
-
-All commands are thin `#[tauri::command]` async wrappers that delegate to `DesktopState` (`manager` or `terminal_manager`). They transform `anyhow::Error` into a flat string via `format_error_chain`.
-
-**Categories of exposed capabilities** (`gui/src-tauri/src/commands.rs`):
-
-| Category | Key Commands |
-|----------|--------------|
-| **Workspace / Project** | `pick_workspace`, `pick_directory`, `open_workspace`, `clone_repository`, `quick_start_project`, `rename_workspace`, `archive_workspace` |
-| **Session / Chat** | `start_new_chat`, `create_managed_chat`, `select_conversation`, `ensure_conversation_view`, `send_prompt`, `stop_prompt`, `compact_conversation`, `handoff_chat`, `respond_followup`, `archive_conversation` |
-| **Prompt / Agent** | `get_prompt_settings`, `update_prompt_settings`, `set_active_agent`, `set_effort`, `set_fast`, `list_providers`, `start_provider_auth`, `complete_provider_auth`, `remove_provider` |
-| **Commands / Slash** | `list_commands`, `run_slash_command` |
-| **Workspace Search** | `workspace_sync`, `workspace_query` |
-| **Git** | `checkout_git_branch`, `create_git_branch`, `commit_git_changes`, `push_git_branch` |
-| **MCP** | `list_mcp_servers`, `import_mcp_config`, `remove_mcp_server`, `reload_mcp_servers`, `login_mcp_server`, `logout_mcp_server` |
-| **File / OS** | `read_workspace_file`, `open_path_default`, `open_path_for_edit`, `open_external_url`, `open_in_target`, `open_path_in_target` |
-| **Layout / Persistence** | `save_conversation_layout`, `get_conversation_layout`, `create_saved_workspace`, `update_saved_workspace_layout`, `get_saved_workspace`, `rename_saved_workspace`, `delete_saved_workspace` |
-| **Image** | `save_pasted_image`, `image_thumbnail` |
-| **Terminal** | `terminal_open`, `terminal_write`, `terminal_resize`, `terminal_close` |
-| **Cold start** | `drain_pending_open` |
-
-**Notable implementation details:**
-- `read_workspace_file` (`L414`) runs in `tokio::task::spawn_blocking` and performs a strict sandbox check: it canonicalizes both the workspace root and the target path, rejects empty workspace roots, verifies `starts_with`, checks `is_file`, and caps reads at 512 KiB.
-- `save_pasted_image` (`L258`) writes to a temp file under `codegraff-pasted` and returns the path.
-- `image_thumbnail` (`L275`) spawns a blocking task that opens the image, downscales it, re-encodes as JPEG quality 70, and returns a base64 data URL.
-- `clone_repository` / `quick_start_project` directly invoke `git clone` and `gh repo create` via `std::process::Command`.
-
----
-
-## 3. Runtime (`runtime/simple.rs`)
-
-This is the core orchestrator. It bridges the Tauri frontend to the Zig-native `graff` CLI by spawning persistent `graff --json` child processes per conversation.
-
-**Key structures** (`gui/src-tauri/src/runtime/simple.rs`):
-
-- **`RuntimeManager`** (`L108`) — cloneable, holds:
- - `emitter: Arc<dyn UiEventEmitter>` — pushes `SessionSnapshotDto` to the frontend.
- - `projects: Arc<ProjectStore>` — SQLite registry.
- - `state: Arc<Mutex<RuntimeState>>` — in-memory conversations, workspace list, model selection, pending follow-ups.
- - `sessions: Arc<Mutex<HashMap<String, GraffSession>>>` — live child processes keyed by `conversation_id`.
-
-- **`RuntimeState`** (`L62`) — tracks:
- - `active_workspace_path`, `active_conversation_id`
- - `conversations: HashMap<String, ConversationState>` — messages, titles, request IDs, agent IDs, plan mode, goal.
- - `selected_provider`, `selected_model`, `selected_effort`, `fast_enabled`
- - `model_catalog` — cached result of `graff --schema`
- - `pending_followups` — live `ask_user` prompts awaiting GUI answer.
-
-- **`GraffSession`** (`L97`) — a persistent `graff --json` child:
- - `child: tokio::process::Child`
- - `stdin: Arc<Mutex<ChildStdin>>` — shared so follow-up answers can be injected while a turn is streaming.
- - `reader: Option<Lines<BufReader<ChildStdout>>>` — taken during a turn and returned after.
-
-**Session lifecycle & protocol flow:**
-
-1. **`send_prompt`** (`L416`) — creates a `request_id`, appends a `User` message to `ConversationState`, then calls `stream_turn`.
-2. **`stream_turn`** (`L562`) — acquires session IO via `acquire_session_io`:
- - If no session exists, spawns `graff --json --yolo` (with model/agent/mode/effort/fast controls injected) via `spawn_graff_session` (`L1403`).
- - Writes a JSON line `{"type":"user","text":...}` to stdin.
- - Reads JSONL lines from stdout and maps them to DTOs:
- - `text` → `SessionMessageDto::Assistant` (appended incrementally)
- - `reasoning` → `SessionMessageDto::Reasoning`
- - `tool_call` → `SessionMessageDto::ToolStart`
- - `ask_user` → `SessionMessageDto::ToolStart` + stores `FollowupRequestDto` in `pending_followups`
- - `tool_result` → `SessionMessageDto::ToolEnd`
- - `turn` → ends the loop cleanly
- - `error` → pushes `SessionMessageDto::Error` and breaks
- - After each event, calls `emit()` which snapshots state and fires `codegraff://session-updated`.
-3. **`send_control`** (`L696`) — sends non-user controls (`set_model`, `set_mode`, `compact`, `set_agent`, `set_effort`, `set_fast`) and waits for an ack JSON line.
-4. **`respond_followup`** (`L943`) — writes the structured answer JSON to the session’s stdin, unblocking the streaming loop.
-5. **`stop_prompt`** (`L1036`) — kills the session child (`drop_session`), which causes `stream_turn` to hit EOF and finish.
-6. **Title generation** (`L355`) — first-turn titles are generated by a fire-and-forget one-shot `graff -p "<title prompt>" --yolo` call.
-
-**Model/provider machinery:**
-- `codegraff_binary()` (`L1506`) resolves the engine via a 5-step fallback: `CODEGRAFF_GUI_BINARY` env var → bundled sidecar next to exe → dev build `../../zig-out/bin/graff` → standard install paths (`~/bin/graff`, `/opt/homebrew/bin/graff`, etc.) → bare `graff` on PATH.
-- `login_shell_env()` (`L1351`) — on macOS, captures the user’s login shell environment (`env` from `zsh -il`) so `OPENAI_API_KEY` etc. are visible to the GUI-spawned binary.
-- `codegraff_schema_models()` (`L1427`) parses `graff --schema` JSON to populate the model picker dynamically.
-- Provider auth is handled by mapping to `graff key set`, `graff login`, or direct env var detection. Credentials are deleted from macOS Keychain, `~/.simple-harness-keys.json`, and provider-specific files (`~/.codex/auth.json`, `~/.kimi/credentials/graff-oauth.json`).
-
-**Persistence:**
-- Conversations are persisted to `~/.codegraff-gui/conversations.json` (`PersistedConversation`) at turn boundaries (`persist_conversations`, `L783`).
-- Prompt settings (provider, model, effort, fast) are persisted to `~/.codegraff-gui/prompt-settings.json` (`persist_prompt_settings`, `L375`).
-
----
-
-## 4. Bridge Modules (`bridge/*`, `desktop_open.rs`, `debug_bridge.rs`)
-
-**`bridge/emitter.rs`** (`gui/src-tauri/src/bridge/emitter.rs`) — Defines the event contract:
-
-- `UiEventEmitter` trait (`L12`) with methods:
- - `emit_session_updated(SessionSnapshotDto)`
- - `emit_terminal_output(TerminalOutputEventDto)`
- - `emit_terminal_exit(TerminalExitEventDto)`
- - `emit_terminal_error(TerminalErrorEventDto)`
- - `emit_provider_oauth_callback(...)` (unused by simple adapter)
-- `TauriEventEmitter` implements this by calling `app.emit(...)` with event names like `codegraff://session-updated`.
-
-**`bridge/followup.rs`** (`gui/src-tauri/src/bridge/followup.rs`) — A `FollowupBridge` that uses `tokio::sync::mpsc` and `oneshot` channels to turn `ask_user` prompts into async Rust futures. It stores pending resolutions by `followup_id` and maps `select_one`/`select_many`/`prompt_question` to `FollowupRequestDto`/`FollowupResponseDto`. `with_followup_context` sets a task-local context so the bridge knows the workspace/conversation/request IDs.
-
-**`bridge/desktop_infra/`** (`gui/src-tauri/src/bridge/desktop_infra/mod.rs`) — A wrapper around `forge_infra::ForgeInfra` that implements `CommandInfra`, `EnvironmentInfra`, `FileReaderInfra`, `FileWriterInfra`, `HttpInfra`, `McpServerInfra`, `UserInfra`, etc. The comments note this is “copied scaffolding; unused by the simple adapter (graff has no follow-up tool). Retained for future parity.”
-
-**`desktop_open.rs`** (`gui/src-tauri/src/desktop_open.rs`) — OS-native file/URL opening:
-- `open_external_url` → `open` (macOS) / `start` (Windows) / `xdg-open` (Linux).
-- `open_path_default` → same OS commands.
-- `open_path_for_edit` → `open -t` (macOS text editor) / `notepad` / `xdg-open`.
-- `open_path_in_target` (unused) supports IDE targets: Cursor, Zed, Xcode, Terminal, Ghostty, Warp, Android Studio.
-- `detect_available_open_targets` probes which apps are installed.
-
-**`debug_bridge.rs`** (`gui/src-tauri/src/debug_bridge.rs`) — Dev-only localhost HTTP server on `127.0.0.1:9233`:
-- `POST /eval` — injects JS into the Tauri webview via `window.eval()`, returns the result via `__TAURI_INTERNALS__.invoke('cg_debug_eval_result', ...)`.
-- `GET /screenshot` — focuses the window, runs `screencapture`, crops to window bounds.
-- `POST /eval-result` — external endpoint to resolve a pending eval.
-- Only compiled/started in `cfg(debug_assertions)`; the Tauri command is always registered but harmless in release.
-
----
-
-## 5. DTOs (`dto/*`)
-
-All data types are in `dto/` and derive `Serialize`, `Deserialize`, `PartialEq`, `Eq`, and `ts_rs::TS` for automatic TypeScript generation (`gui/src-tauri/src/dto/mod.rs`).
-
-**`dto/session.rs`** — Core conversation model:
-- `SessionMessageDto` (`L12`) — tagged enum for `User`, `Assistant`, `Reasoning`, `Status`, `ToolStart`, `ToolEnd`, `Error`, `ContextCompacted`.
-- `ConversationViewSnapshotDto` — a full conversation view (messages + active requests + followup).
-- `SessionSnapshotDto` — the root payload emitted to the frontend: active workspace, visible messages, conversation list, workspaces, saved workspaces.
-
-**`dto/activity.rs`** — Tool call / result shapes:
-- `ToolCallDetailDto` (`L22`) — `FileRead`, `FileUpdate`, `Shell`, `Search`, `CodebaseSearch`, `Fetch`, `Followup`, `Plan`, `Skill`, `Task`, `TodoWrite`, `TodoRead`, `Unknown`.
-- `ToolResultDetailDto` — `FileDiff`, `ShellOutput`, `Text`.
-- `OutputPreviewDto` — supports truncated head/tail previews.
-
-**`dto/chat.rs`** — `ChatEventKind` / `ChatEventDto` — a parallel event representation (used by the copied infrastructure, not the simple adapter’s streaming).
-
-**`dto/command.rs`** — Command system DTOs:
-- `CommandDescriptorDto`, `CommandRunResultDto`, `CommandPayloadDto`
-- `AgentsPayloadDto`, `AgentSummaryDto`
-- `WorkspaceSearchResultDto`, `WorkspaceSyncPayloadDto`, `WorkspaceStatusPayloadDto`
-- `McpServerSummaryDto`, `McpSettingsPayloadDto`, `McpImportInput`
-- `WorkflowDraftPayloadDto`, `WorkflowNodeDto`
-
-**`dto/runtime.rs`** — Settings & auth:
-- `PromptSettingsDto`, `PromptModelOptionDto`
-- `ProviderSummaryDto`, `ProviderAuthMethodDto`, `ProviderAuthSessionDto`
-- `SendPromptInput`, `CloneRepositoryInput`, `QuickStartProjectInput`, `CreateSavedWorkspaceInput`
-- `RuntimeStatusDto` — git repo/branch/workspace kind detection
-
-**`dto/followup.rs`** — Interactive prompts:
-- `FollowupKind` (`Text`, `Single`, `Multi`)
-- `FollowupRequestDto`, `FollowupResponseDto`
-
-**`dto/terminal.rs`** — Terminal DTOs:
-- `TerminalOpenInput`, `TerminalWriteInput`, `TerminalResizeInput`, `TerminalCloseInput`
-- `TerminalSessionDto`, `TerminalOutputEventDto`, `TerminalExitEventDto`, `TerminalErrorEventDto`
-
----
-
-## 6. Persistence & Terminal Handling
-
-**Persistence (`persistence/project_store.rs`)** (`gui/src-tauri/src/persistence/project_store.rs`):
-
-- Uses **SQLite** via `diesel` with `SqliteConnection`.
-- Tables managed:
- - `opened_projects` — path, last_opened_at, display_name
- - `managed_chat_workspaces` — auto-created chat folders
- - `conversation_layouts` — layout JSON per conversation_id
- - `saved_workspaces` / `saved_workspace_layouts` — user-saved workspace layouts
-- All operations are serialized through a `Mutex` (`connection_lock`) to prevent concurrent SQLite writes.
-- `add_project`, `create_managed_chat_workspace`, `list_workspaces`, `archive_workspace`, `save_conversation_layout`, `create_saved_workspace`, etc.
-- `ProjectStore` is initialized in `lib.rs` and stored as `Arc<ProjectStore>` inside `DesktopState`.
-
-**Additional file-based persistence** (in `runtime/simple.rs`):
-- `~/.codegraff-gui/conversations.json` — serialized `Vec<PersistedConversation>` so chats survive restarts.
-- `~/.codegraff-gui/prompt-settings.json` — `PersistedPromptSettings` (model, effort, fast).
-
-**Terminal Handling (`terminal.rs`)** (`gui/src-tauri/src/terminal.rs`):
-
-- Uses `portable_pty` (`native_pty_system()`) to spawn real PTY sessions.
-- `TerminalManager` (`L22`) holds a `HashMap<String, Arc<TerminalSession>>`.
-- `TerminalSession` (`L100`) wraps:
- - `master: StdMutex<Box<dyn MasterPty>>` — PTY master fd/handle
- - `writer: StdMutex<Box<dyn Write>>` — write end
- - `killer: StdMutex<Box<dyn ChildKiller>>` — process killer
- - `exit_status: StdMutex<bool>`
-- **Spawn flow** (`spawn_terminal_session`, `L172`):
- - Opens a PTY with default 80×24 or supplied cols/rows.
- - Spawns the user’s shell (`$SHELL`, default `/bin/sh`; on Windows `cmd.exe`).
- - Sets `TERM=xterm-256color`, `COLORTERM=truecolor`, `TERM_PROGRAM=codegraff-gui`.
- - For `zsh`, passes `-o NO_PROMPT_SP -o NO_PROMPT_CR` to prevent prompt spacing issues.
- - Sets `cwd` to the workspace path.
-- **Reader thread** (`spawn_reader_thread`, `L216`) — reads from the PTY master in a blocking loop, batches into ~4KB chunks, converts to string via `bstr`, and emits `codegraff://terminal-output`.
-- **Wait thread** (`spawn_wait_thread`, `L261`) — waits on the child process, then emits `codegraff://terminal-exit` with exit code / signal.
-- Commands exposed: `terminal_open`, `terminal_write`, `terminal_resize`, `terminal_close`.
-
----
-
-## Verified vs. Inferred
-
-- **Verified:** The runtime spawns `graff --json` as a persistent child and speaks a line-delimited JSON protocol (`runtime/simple.rs:1403`, `stream_turn:562`).
-- **Verified:** The `ProjectStore` uses SQLite with `diesel` and the schema includes `opened_projects`, `managed_chat_workspaces`, `conversation_layouts`, `saved_workspaces` (`project_store.rs:23–30`).
-- **Verified:** The `bridge/desktop_infra` module is explicitly marked as unused by the simple adapter and retained for future parity (`bridge/desktop_infra/mod.rs:13` comment, `lib.rs:10–15` comment).
-- **Verified:** The terminal uses `portable_pty` with separate reader and wait threads emitting Tauri events (`terminal.rs:172–299`).
-- **Inferred:** The frontend consumes the `SessionSnapshotDto` emitted on `codegraff://session-updated` to re-render the entire conversation state (inferred from the emitter pattern and the DTO structure; the frontend code was not inspected).
-
----
-
-## 3 Most Load-Bearing Facts
-
-1. **Conversation engine is a persistent `graff --json` child process.** The backend does not embed the Zig core; it shells out to the `graff` CLI, keeps one `tokio::process::Child` per conversation, and streams JSONL events over stdin/stdout. This is the central data flow for all chat (`runtime/simple.rs:1403`, `stream_turn:562`).
-
-2. **All UI state is pushed via `TauriEventEmitter` emitting `SessionSnapshotDto`.** The frontend does not poll; the backend continuously snapshots the full `RuntimeState` (conversations, workspaces, follow-ups, active requests) and pushes it through the `codegraff://session-updated` event. Commands return the same DTO to the caller, but live streaming depends on events (`bridge/emitter.rs:12`, `runtime/simple.rs:783`).
-
-3. **Terminal I/O is real PTY I/O via `portable_pty` with dedicated OS threads.** Each `terminal_id` gets a `spawn_terminal_session` that creates a PTY pair, spawns the shell, and runs two blocking threads (reader + process waiter) that emit output/exit events into the Tauri event bus. This is entirely separate from the `graff` child process system (`terminal.rs:172–299`).
-
----
-
-## 1 Open Question
-
-- **How does the frontend resume a persisted conversation after restart?** The backend loads `conversations.json` into `RuntimeState` on startup, but the comments state that “live `graff` sessions are not restored — continuing a loaded chat starts a fresh session without the model's prior context.” It is unclear whether the frontend replays the loaded messages for display only, or if there is a plan to serialize/resume the actual `graff` process state (context/KV cache) in the future.
diff --git a/.graff/subagents/sa-002-c0e18dfe.md b/.graff/subagents/sa-002-c0e18dfe.md
deleted file mode 100644
index ff0e97ca..00000000
--- a/.graff/subagents/sa-002-c0e18dfe.md
+++ /dev/null
@@ -1,193 +0,0 @@
-# subagent sa-002-c0e18dfe
-
-- label: workflow progress mapping
-- kind: workflow_task
-- status: ok
-- elapsed_ms: 535819
-- tools: codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,bash!,bash!,bash!,bash!,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb
-
-## task
-
-Inspect whether the repo has structured workflow/ultracode progress events similar to a mappable task UI/progress card. Use codedb first. Search for workflow events, task progress, ChatWorkRow, activity/work rows, NDJSON events, and serve/json protocol handling. Report whether ultracode workflow progress is represented as structured events or only as tool calls/text/logs. Include file references. Do not modify files.
-
-## report
-
-## Bottom line
-
-**Verified:** the repo has UI concepts that *could* display task/progress cards, but the actual `graff --json` / `graff serve` event protocol does **not** expose structured workflow/ultracode progress events such as phases, tasks, per-subagent lifecycle, or a live agent tree. Workflow/ultracode progress is represented primarily as:
-
-1. generic `tool_call` / `tool_result` events,
-2. assistant text / reasoning,
-3. TUI/stderr/log/trace/telemetry documentation,
-4. GUI-derived generic “work rows” grouped from tool start/end messages.
-
-So: **not a first-class structured workflow progress stream suitable for directly mapping to a rich task UI/progress card.**
-
----
-
-## What I verified
-
-### 1. The SDK / serve event protocol is generic, not workflow-progress structured
-
-The TypeScript SDK defines the full event union as `text`, `tool_call`, `ask_user`, `tool_result`, `turn`, `system_prompt`, `score`, and `error`; there is no `workflow_started`, `workflow_phase`, `task_started`, `task_completed`, `subagent_started`, or similar event type. `workflow` exists only as a tool name in the tool list, not as a distinct event model. `sdk/ts/harness.ts:14`, `sdk/ts/harness.ts:17-31`
-
-The remote HTTP client uses the same contract: it says serve streams the same `--json` contract as NDJSON, and its event union is the same generic set. `sdk/ts/remote.ts:3-8`, `sdk/ts/remote.ts:16-28`
-
-The remote client parses each NDJSON line as an `Event`, and a chat terminates only on `turn` or `error`; unknown events pass through but are not modeled. `sdk/ts/remote.ts:69-89`, `sdk/ts/remote.ts:149-157`
-
-The Python SDK README also summarizes the protocol as JSONL events: `text`, `tool_call`, `ask_user`, `tool_result`, `turn`, and `error`; no workflow-progress event types are documented. `sdk/README.md:101-107`
-
-`graff serve` is documented as putting the same protocol on HTTP: each session is a `graff --json` child, one non-answer POST is one protocol request, and the response streams NDJSON events until the terminal event. `README.md:739-744`
-
-**Conclusion:** serve/NDJSON protocol handling is structured at the generic agent-event level, but **not at workflow/ultracode progress-card granularity**.
-
----
-
-### 2. `ultracode` is documented as prompt steering + trace/logging, not a structured event stream
-
-The README describes `ultracode` as a codeword: if present in a message, the harness prints a banner, records an `ultracode` trace event, and asks the model to fan work out through the `workflow` tool. `README.md:550-556`
-
-Architecture docs say the same thing more explicitly: `main()` scans user input for `ultracode`, prints a banner, emits an `ultracode` trace note, and appends steering text telling the model to use `workflow`; it is “pure prompt-augmentation” with “no new control flow.” `architecture.md:356-363`
-
-**Conclusion:** ultracode is not represented as a dedicated protocol event in the SDK/serve contract; it is a per-turn prompt augmentation plus trace/log signal.
-
----
-
-### 3. Workflow exists as a tool, not as structured progress events
-
-The README’s tools table lists `workflow` as a built-in tool: “phases of parallel subagents; `{{prev}}` carries results forward.” `README.md:465-467`
-
-The workflow docs describe the model calling the `workflow` tool with a JSON plan: up to five sequential phases, each with up to eight parallel tasks, with previous phase results carried into later tasks. `README.md:558-564`
-
-The architecture docs describe `workflow` as a built-in tool executed through the same tool machinery as other built-ins. `architecture.md:160-168`
-
-In the GUI adapter’s protocol mapping, a `tool_call` named `"workflow"` is converted into a generic `ToolCallDetailDto::Task` with `label: "workflow"` and empty `agent_id`; no phases/tasks/progress fields are extracted. `gui/src-tauri/src/runtime/simple.rs:2736-2743`
-
-**Conclusion:** the repo knows about the workflow tool, but the GUI mapping collapses it to a generic “task/tool” row rather than a structured workflow graph/progress model.
-
----
-
-### 4. The Tauri GUI has generic work/activity rows, but they are built from transcript tool messages
-
-The chat thread model has a `request_work` item with `activities`, `isRunning`, `hasError`, and `failedStepCount`. `gui/src/components/chat/types/chatThread.ts:44-58`
-
-Each activity has `summary`, `operations`, `isRunning`, `isThinking`, `hasError`, and optional reasoning text. `gui/src/components/chat/types/chatThread.ts:21-31`
-
-`buildChatThreadItems` constructs these work rows from transcript messages by grouping `reasoning`, `tool_start`, `status`, `status_output`, and `tool_end` messages. `gui/src/components/chat/utils/chatThread.ts:164-294`
-
-The resulting work item is only created when there are activities or an active request, and its failure/running state is derived from grouped activity rows. `gui/src/components/chat/utils/chatThread.ts:313-331`
-
-`ChatWorkRow` renders a collapsible work group with a spinner if running and a failed-step count via its label logic. `gui/src/components/chat/ChatWorkRow.tsx:14-33`, `gui/src/components/chat/ChatWorkRow.tsx:37-75`
-
-`ChatActivityRow` renders each grouped activity with icons for generic operation kinds including file reads, shell commands, search, fetch, task, todo, etc. `gui/src/components/chat/ChatActivityRow.tsx:66-98`, `gui/src/components/chat/ChatActivityRow.tsx:180-260`
-
-The summary builder counts operations and reports broad categories such as “N subagents,” “Explored N files,” “Ran N commands,” etc.; it does not model workflow phases or node dependencies. `gui/src/components/chat/utils/chatThread.ts:546-605`
-
-**Conclusion:** the GUI has a **generic mappable activity/work-row UI**, but it is reconstructed from generic transcript messages, not from dedicated workflow progress events.
-
----
-
-### 5. Tauri backend translates JSONL events into generic transcript messages only
-
-The Tauri runtime sends a user line to the persistent `graff --json` session as `{"type":"user","text":prompt}`. `gui/src-tauri/src/runtime/simple.rs:572-586`
-
-It reads stdout line by line, parses JSON, and matches on `event.type`. `gui/src-tauri/src/runtime/simple.rs:595-621`
-
-Handled event types include `text`, `reasoning`, `tool_call`, `ask_user`, `tool_result`, `turn`, and `error`. `gui/src-tauri/src/runtime/simple.rs:621-855`
-
-For `tool_call`, it creates a `SessionMessageDto::ToolStart` with a `ToolCallDetailDto`. `gui/src-tauri/src/runtime/simple.rs:704-758`
-
-For `tool_result`, it creates a `SessionMessageDto::ToolEnd` with optional text result detail. `gui/src-tauri/src/runtime/simple.rs:796-832`
-
-For unrecognized events and `system_prompt` / `score` acks, it ignores them. `gui/src-tauri/src/runtime/simple.rs:853-854`
-
-The session message enum itself has only generic variants: user, assistant, reasoning, status, status output, tool start, tool end, and error. `gui/src-tauri/src/dto/session.rs:13-79`
-
-**Conclusion:** the desktop GUI backend would currently ignore any unknown future workflow-specific event unless explicitly added, and today it only translates workflow into generic tool start/end messages.
-
----
-
-### 6. There is a task/todo UI shape, but it is not wired to live workflow progress in the Tauri backend
-
-The session DTO includes todo types: `SessionTodoStatusDto` with `Pending`, `InProgress`, `Completed`, and `Cancelled`, and `SessionTodoDto` with `id`, `content`, and `status`. `gui/src-tauri/src/dto/session.rs:81-98`
-
-The snapshot DTO includes `visible_todos`, and each conversation view includes `todos`. `gui/src-tauri/src/dto/session.rs:120-131`, `gui/src-tauri/src/dto/session.rs:173-188`
-
-However, the runtime snapshot currently sets `visible_todos: vec![]`. `gui/src-tauri/src/runtime/simple.rs:1935-1948`
-
-Each conversation view also sets `todos: vec![]`. `gui/src-tauri/src/runtime/simple.rs:2265-2276`
-
-The React `SessionTodoDock` can render a task-plan card, with active/busy state, completed counts, and todo status icons. `gui/src/components/conversation-panel/SessionTodoDock.tsx:36-56`, `gui/src/components/conversation-panel/SessionTodoDock.tsx:79-118`, `gui/src/components/conversation-panel/SessionTodoDock.tsx:124-150`
-
-But its summary is derived from supplied todos, and the backend currently supplies none. `gui/src/components/conversation-panel/utils/sessionTodo.ts:5-29`, `gui/src-tauri/src/runtime/simple.rs:1947`, `gui/src-tauri/src/runtime/simple.rs:2275`
-
-**Conclusion:** the GUI has a task-plan card component, but live Tauri snapshots do not populate it from workflow/todo events.
-
----
-
-### 7. The iOS app has a visible “Task progress” card, but it is app-state/static, not driven by structured workflow events
-
-The iOS `ChatView` always renders `TaskProgressCard(session:)` above messages. `apps/ios/Graff/Sources/ChatView.swift:13-17`
-
-`TaskProgressCard` displays `session.progress.done/total` and iterates `session.todos`, with in-progress pulse animation. `apps/ios/Graff/Sources/ChatView.swift:106-133`
-
-The iOS serve client decodes NDJSON into `GraffEvent` cases: `reasoning`, `text`, `toolCall(name:)`, `turn`, `error`, and `other`; no workflow phase/task progress cases exist. `apps/ios/Graff/Sources/GraffServeClient.swift:3-11`, `apps/ios/Graff/Sources/GraffServeClient.swift:82-95`
-
-During streaming, iOS appends reasoning/text and final turn text; it explicitly ignores `.toolCall` and `.other`. `apps/ios/Graff/Sources/ChatView.swift:83-95`
-
-**Conclusion:** iOS has a progress-card UI, but serve events do not drive it; tool calls are ignored in the current live stream handler.
-
----
-
-### 8. Workflow draft/review is structured, but that is a slash-command modal, not runtime progress
-
-The command DTO has a structured `WorkflowDraftPayloadDto` with `goal`, `summary`, `nodes`, `export_text`, `approved_prompt`, and `trace`. `gui/src-tauri/src/dto/command.rs:279-296`
-
-The command result payload enum includes `WorkflowDraft`. `gui/src-tauri/src/dto/command.rs:352-373`
-
-The command dialog renders workflow draft nodes as cards and provides an approve button. `gui/src/components/CommandResultDialog.tsx:33-36`, `gui/src/components/CommandResultDialog.tsx:64-73`, `gui/src/components/CommandResultDialog.tsx:131-150`
-
-But the Tauri runtime’s `build_workflow_draft` is a placeholder returning empty nodes and a stub summary. `gui/src-tauri/src/runtime/simple.rs:1251-1263`
-
-**Conclusion:** there is structured workflow-*draft* UI data, but it is not live ultracode/workflow execution progress.
-
----
-
-## What I infer
-
-1. **A progress-card UI could be built on top of the existing generic ChatWorkRow/ChatActivityRow system**, because it already groups tool calls, reasoning, running state, and errors. But today that grouping is lossy for workflow: `workflow` becomes a generic `task` operation with label `"workflow"`, not a phase/task tree. Evidence: generic grouping in `buildChatThreadItems`; workflow mapping to `ToolCallDetailDto::Task`. `gui/src/components/chat/utils/chatThread.ts:164-331`, `gui/src-tauri/src/runtime/simple.rs:2740-2743`
-
-2. **To support a mappable ultracode/workflow progress card, the protocol would need new structured events or richer `tool_call`/`tool_result` payload conventions** for workflow phase/task lifecycle. Today the protocol event union has no such events. `sdk/ts/harness.ts:23-31`, `sdk/ts/remote.ts:20-28`
-
-3. **The intended source of truth appears to be the TUI harness / `graff --json` protocol, not separate GUI-only state.** AGENTS.md says the TUI harness is the source of truth and the GUI/app should consume the same events. `AGENTS.md:26-36`
-
----
-
-## Answer to the core question
-
-**Does the repo have structured workflow/ultracode progress events similar to a mappable task UI/progress card?**
-
-**No, not in the current verified protocol/GUI path.**
-
-It has:
-
-- generic `tool_call` / `tool_result` / `text` / `reasoning` events, not workflow-specific progress events. `sdk/ts/harness.ts:23-31`, `sdk/ts/remote.ts:20-28`
-- a `workflow` tool name and documentation for multi-agent phases/tasks, but not a structured event model for those phases/tasks. `README.md:558-564`, `architecture.md:160-168`
-- generic GUI work/activity rows reconstructed from transcript messages. `gui/src/components/chat/utils/chatThread.ts:164-331`
-- a task/todo dock component and iOS progress card UI, but Tauri snapshots currently provide empty todos and iOS ignores live tool calls. `gui/src-tauri/src/runtime/simple.rs:1947`, `gui/src-tauri/src/runtime/simple.rs:2275`, `apps/ios/Graff/Sources/ChatView.swift:83-95`
-
-So workflow/ultracode progress is currently represented as **tool calls, text/reasoning, logs/trace/telemetry**, and generic activity rows — **not as first-class structured progress events**.
-
----
-
-## 3 most load-bearing facts
-
-1. The event protocol union has no workflow/task-progress event types; it only defines generic events like `text`, `tool_call`, `tool_result`, `turn`, and `error. `sdk/ts/harness.ts:23-31`
-
-2. The Tauri runtime converts JSONL `tool_call` / `tool_result` into generic `ToolStart` / `ToolEnd` transcript messages and ignores unrecognized event types. `gui/src-tauri/src/runtime/simple.rs:704-758`, `gui/src-tauri/src/runtime/simple.rs:796-854`
-
-3. The GUI’s todo/task-plan data path is present but currently unpopulated by the runtime: `visible_todos` and conversation `todos` are both `vec![]`. `gui/src-tauri/src/runtime/simple.rs:1935-1948`, `gui/src-tauri/src/runtime/simple.rs:2265-2276`
-
-## Open question
-
-The docs reference `src/main.zig` as the harness source of truth and mention per-subagent TUI rendering, but the indexed repo tree only shows `src/mcp.zig`; the current checked/indexed contents do not let me verify whether `src/main.zig` already emits richer workflow/subagent events on another branch or in an unindexed/missing file.
diff --git a/.graff/subagents/sa-002-e9970bea.md b/.graff/subagents/sa-002-e9970bea.md
deleted file mode 100644
index 9abe331b..00000000
--- a/.graff/subagents/sa-002-e9970bea.md
+++ /dev/null
@@ -1,321 +0,0 @@
-# subagent sa-002-e9970bea
-
-- label: build test config
-- kind: workflow_task
-- status: ok
-- elapsed_ms: 252326
-- tools: codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,bash,bash,bash,codedb,codedb,codedb,codedb,codedb,codedb,bash,bash,codedb,codedb,codedb,bash!,codedb,codedb,codedb,codedb,bash
-
-## task
-
-Explore how this repository is built, run, tested, linted, and configured. Use codedb first where useful (tree/search/read/outline) before bash. Inspect package/build/config files and scripts. Report exact commands and important environment/config assumptions. Do not edit files.
-
-## report
-
-## Verified repository build/run/test/lint/config map
-
-### 1) Top-level project structure and package manager
-
-- The repository is a mixed Zig CLI + Bun workspace + Tauri/Rust desktop app + SDKs repo. The root `package.json` is private, pins `[email protected]`, and declares workspaces `gui` and `packages/*`; it has no root `scripts` block. (`package.json:1-9`)
-- The main Zig build creates a single executable named `graff` from `src/main.zig`. (`build.zig:42-51`)
-- The GUI is a separate Bun workspace package named `codegraff-gui`, also pinned to `[email protected]`. (`gui/package.json:1-7`)
-- The reusable diff renderer is a workspace package named `@codegraff/diffs`. (`packages/diffs/package.json:1-7`)
-
-### 2) CLI / Zig build and run
-
-**Build:**
-
-```sh
-zig build
-```
-
-- CI runs exactly `zig build`. (`.github/workflows/ci.yml:39-40`)
-- The Zig build installs the `graff` artifact via `b.installArtifact(exe)`. (`build.zig:42-51`)
-
-**Run from source:**
-
-```sh
-zig build run
-# or
-./zig-out/bin/graff
-```
-
-- `build.zig` defines a `run` step that runs the built executable. (`build.zig:53-56`)
-- README documents `zig build run` and `./zig-out/bin/graff` as in-place alternatives. (`README.md:692-699`)
-
-**Release/cross-compile:**
-
-```sh
-zig build -Doptimize=ReleaseSafe -Dtarget="$target" -Dversion="$VERSION" -Dtelemetry-endpoint="$TELEMETRY_ENDPOINT"
-```
-
-- Release CI runs that command for `aarch64-macos`, `x86_64-macos`, `x86_64-linux`, and `aarch64-linux`. (`.github/workflows/release.yml:24-33`)
-- Release artifacts are tarballs containing `graff`, `README.md`, and `LICENSE`, plus `SHA256SUMS`. (`.github/workflows/release.yml:34-40`)
-- Release is triggered by tags matching `v*`. (`.github/workflows/release.yml:6-8`)
-
-**Versioning / build options:**
-
-- `-Dversion=...` overrides the version string; otherwise `build.zig` derives it from `git describe --tags --always --dirty`, falling back to `0.1.0-dev`. (`build.zig:7-25`)
-- `-Dtelemetry-endpoint=...` sets a baked-in default OTLP endpoint; passing `-Dtelemetry-endpoint=""` disables it. (`build.zig:26-37`)
-
-### 3) CLI tests, formatting, and CI checks
-
-**Unit tests:**
-
-```sh
-zig build test
-zig build test --summary all
-```
-
-- `build.zig` defines a `test` step using `src/main.zig` as the test root. (`build.zig:58-69`)
-- CI runs `zig build test --summary all`. (`.github/workflows/ci.yml:45-46`)
-- README documents `zig build test` as the test suite. (`README.md:697-699`)
-
-**Formatting/lint-equivalent for Zig:**
-
-```sh
-zig fmt --check src/main.zig src/mcp.zig build.zig
-```
-
-- CI enforces that exact `zig fmt --check` command. (`.github/workflows/ci.yml:42-43`)
-
-**Protocol/JSON control test:**
-
-```sh
-python3 scripts/test-json-controls.py zig-out/bin/graff
-```
-
-- CI runs that exact command after building `graff`. (`.github/workflows/ci.yml:48-49`)
-
-**SDK drift check:**
-
-```sh
-python3 sdk/generate.py --harness ./zig-out/bin/graff
-git diff --exit-code sdk/
-```
-
-- CI regenerates SDKs with the built binary and fails if `sdk/` changes. (`.github/workflows/ci.yml:51-55`)
-
-**CI toolchain assumption:**
-
-- CI pins Zig to `0.16.0`. (`.github/workflows/ci.yml:34-37`)
-- The installer also says the harness needs Zig 0.16 and warns on other versions. (`install.sh:41-51`)
-
-### 4) CLI install flow and environment overrides
-
-**Install latest release / fallback to source:**
-
-```sh
-curl -fsSL https://github.com/justrach/codegraff/releases/latest/download/install.sh | sh
-# or from checkout:
-./install.sh
-```
-
-- README documents the release installer command. (`README.md:56-64`)
-- README says from a checkout run `./install.sh`, installing to `~/bin` by default, overridable by `HARNESS_DIR`. (`README.md:66-67`)
-- `install.sh` defaults `HARNESS_REPO` to `https://github.com/justrach/codegraff`, `HARNESS_DIR` to `$HOME/bin`, and binary name to `graff`. (`install.sh:11-16`)
-- `HARNESS_BUILD=source` skips release download and forces source build. (`install.sh:11-12`, `install.sh:171-175`)
-- Source install runs:
-
-```sh
-zig build -Doptimize=ReleaseFast
-```
-
- (`install.sh:149-152`)
-
-- The installer creates a compatibility symlink from `harness` to `graff`. (`install.sh:179-181`)
-- Optional companion suite install can be skipped with `HARNESS_NO_GRAFF=1`; optional `kuri` install is enabled with `HARNESS_WITH_KURI=1`. (`install.sh:183-207`, `install.sh:209-224`)
-
-### 5) CLI runtime credentials/config assumptions
-
-- API keys can be supplied by login, key storage, or environment variables; examples include `graff login`, `graff key set deepseek sk-...`, and `export DEEPSEEK_API_KEY=sk-...`. (`README.md:74-82`)
-- Provider environment variables documented include `ANTHROPIC_API_KEY`, `CODEGRAFF_API_KEY`, `DEEPSEEK_API_KEY`, `OPENAI_API_KEY`, `MINIMAX_API_KEY`, `XIAOMI_API_KEY`, `KIMI_API_KEY`, `XAI_API_KEY`, and `ZAI_API_KEY`; Codex uses `~/.codex/auth.json`. (`README.md:219-228`)
-- Stored keys live in macOS Keychain using service `simple-harness`; elsewhere in `0600` `~/.simple-harness-keys.json`; environment variables win. (`README.md:712-716`)
-- `graff login` writes the Codegraff device-flow key to `~/.simple-harness-codegraff.json`; `graff login codex` writes `~/.codex/auth.json`. (`README.md:721-727`)
-
-### 6) Telemetry/tracing assumptions
-
-- The CLI writes `harness.trace.jsonl` in the current working directory when tracing is enabled, truncating it at startup for the current session. (`README.md:644-650`)
-- Release telemetry can be opted out with `--no-telemetry` or `GRAFF_NO_TELEMETRY=1`; env endpoints `OTEL_EXPORTER_OTLP_ENDPOINT` or `GRAFF_OTEL_ENDPOINT` override the default. (`README.md:652-659`)
-- **Important verified discrepancy:** `build.zig` currently bakes the telemetry endpoint by default for “release, source-install, and dev” builds unless `-Dtelemetry-endpoint=""` is passed. (`build.zig:26-37`) README says “Builds from source have no endpoint baked in” unless an env endpoint is set. (`README.md:656-659`) Those two statements conflict.
-
-### 7) GUI / frontend build, dev, test, lint
-
-The GUI package scripts are:
-
-```sh
-cd gui
-bun run dev
-bun run build
-bun run lint
-bun run preview
-bun run tauri
-bun test
-```
-
-- `dev` runs `bun run build:deps && vite`. (`gui/package.json:8-10`)
-- `build:deps` runs `bun run --filter '@codegraff/diffs' build`. (`gui/package.json:10-12`)
-- `build` runs `bun run build:deps && bun run gen:desktop-contracts && tsc -b && vite build`. (`gui/package.json:12`)
-- `lint` runs `bun run build:deps && bun run gen:desktop-contracts && eslint .`. (`gui/package.json:13`)
-- `test` runs `bun test`. (`gui/package.json:16`)
-- `preview` runs `vite preview`; `tauri` delegates to the Tauri CLI. (`gui/package.json:14-15`)
-
-**Desktop contract generation:**
-
-```sh
-cd gui
-bun run gen:desktop-contracts
-```
-
-- This runs:
-
-```sh
-cargo run --quiet --manifest-path src-tauri/Cargo.toml --example generate_desktop_contracts
-```
-
- (`gui/package.json:10`)
-
-**Vite config:**
-
-- Vite uses Tailwind, React, and Babel with React Compiler preset. (`gui/vite.config.ts:8-15`)
-- Vite aliases `@` to `gui/src`. (`gui/vite.config.ts:16-20`)
-
-**TypeScript config:**
-
-- `tsc -b` builds references to `tsconfig.app.json` and `tsconfig.node.json`. (`gui/tsconfig.json:9-13`)
-- App TS target is `es2023`, module `esnext`, bundler resolution, React JSX, `noEmit`, `noUnusedLocals`, `noUnusedParameters`, `erasableSyntaxOnly`, and `noFallthroughCasesInSwitch`. (`gui/tsconfig.app.json:2-29`)
-- Node TS config includes only `vite.config.ts`. (`gui/tsconfig.node.json:17-23`)
-
-**ESLint config:**
-
-- ESLint ignores `dist`, `vendor/**`, `src-tauri/gen/**`, and `src-tauri/target/**`. (`gui/eslint.config.js:8-14`)
-- It applies to `**/*.{ts,tsx}` and extends JS recommended, TypeScript recommended, React Hooks latest, and React Refresh Vite configs. (`gui/eslint.config.js:15-22`)
-- It enforces `react-refresh/only-export-components`, allowing constant exports and `useSidebar`. (`gui/eslint.config.js:27-34`)
-
-### 8) GUI / Tauri run and package flow
-
-Likely commands:
-
-```sh
-cd gui
-bun run tauri dev
-bun run tauri build
-```
-
-Evidence:
-
-- `gui/package.json` exposes `"tauri": "tauri"`. (`gui/package.json:14-15`)
-- Tauri config says dev uses `devUrl` `http://localhost:5173`, and `beforeDevCommand` is `bun run dev`. (`gui/src-tauri/tauri.conf.json:6-10`)
-- Tauri config says packaged frontend is `../dist`, and `beforeBuildCommand` is `bun run build`. (`gui/src-tauri/tauri.conf.json:6-10`)
-- The bundle includes external binary `binaries/graff`, targets all bundle formats, and has macOS signing identity `Developer ID Application: Rachit Pradhan (WWP9DLJ27P)` with hardened runtime enabled. (`gui/src-tauri/tauri.conf.json:35-49`)
-
-**Tauri/Rust assumptions:**
-
-- The Rust crate is its own workspace root; the empty `[workspace]` prevents Cargo from walking up to a parent workspace. (`gui/src-tauri/Cargo.toml:1-5`)
-- Rust package is `codegraff-gui` version `0.0.13`, edition `2024`, and requires Rust `1.92`. (`gui/src-tauri/Cargo.toml:7-16`)
-- It uses Tauri `2.10.3` with `macos-private-api`. (`gui/src-tauri/Cargo.toml:39`)
-- Tauri app identifier is `dev.codegraff.gui`; product name is `Codegraff`. (`gui/src-tauri/tauri.conf.json:1-5`)
-
-**GUI runtime engine discovery:**
-
-- The GUI spawns `graff --json --yolo --resume <conversation_id>`, optionally `--model <model>`, in the workspace directory. (`gui/src-tauri/src/runtime/simple.rs:2626-2649`)
-- The GUI passes a login-shell environment into the spawned `graff`, explicitly to make shell-exported provider keys visible to GUI launches. (`gui/src-tauri/src/runtime/simple.rs:2641-2647`)
-- That login-shell env is collected by running `$SHELL -ilc env`, defaulting `SHELL` to `/bin/zsh`, with a 4-second timeout. (`gui/src-tauri/src/runtime/simple.rs:2588-2613`)
-- The GUI binary lookup order is: `CODEGRAFF_GUI_BINARY`, bundled sidecar next to current executable, `../../zig-out/bin/graff`, known install locations like `~/bin/graff`, `/opt/homebrew/bin/graff`, `/usr/local/bin/graff`, then bare `graff` on inherited `PATH`. (`gui/src-tauri/src/runtime/simple.rs:3240-3300`)
-- If spawning fails, the GUI error tells the user to install the CLI or set `CODEGRAFF_GUI_BINARY`. (`gui/src-tauri/src/runtime/simple.rs:2652-2657`)
-
-**Tauri debug bridge:**
-
-- In debug builds only, the app starts `debug_bridge::DebugBridge`. (`gui/src-tauri/src/lib.rs:92-97`)
-- The `scripts/tdev` helper talks to that dev-only bridge at `http://127.0.0.1:9233`. (`scripts/tdev:1-7`, `scripts/tdev:26`)
-- `scripts/tdev` supports `health`, `eval`, `shot`, `click`, `type`, and `key`. (`scripts/tdev:9-15`, `scripts/tdev:37-75`)
-
-### 9) Rust/Tauri tests
-
-Verified but not wired into package scripts/CI:
-
-- `gui/src-tauri/src/runtime/simple.rs` contains Rust `#[test]` declarations under a tests module. (`gui/src-tauri/src/runtime/simple.rs:4001-4259`)
-- `gui/src-tauri/Cargo.toml` has `pretty_assertions` as a dev dependency. (`gui/src-tauri/Cargo.toml:54-56`)
-
-**Inferred exact command:**
-
-```sh
-cargo test --manifest-path gui/src-tauri/Cargo.toml
-```
-
-This command is not found in CI or package scripts; it is inferred from the Cargo manifest and Rust tests.
-
-### 10) Shared diff package build/test
-
-```sh
-cd packages/diffs
-bun run build
-bun test
-```
-
-- `@codegraff/diffs` build script is `tsc -p tsconfig.build.json`. (`packages/diffs/package.json:23-25`)
-- Its test script is `bun test`. (`packages/diffs/package.json:23-26`)
-- Its build emits declarations, declaration maps, source maps, and JS into `dist` from `src`, excluding `test`. (`packages/diffs/tsconfig.build.json:1-14`)
-- Its TS config is strict, targets ES2022, uses bundler module resolution, React JSX, and `bun-types`. (`packages/diffs/tsconfig.json:2-16`)
-
-### 11) SDK generation, validation, and publishing
-
-**Regenerate SDKs locally:**
-
-```sh
-python3 sdk/generate.py --harness ./zig-out/bin/graff
-# or
-graff --schema | python3 sdk/generate.py
-```
-
-- SDK README documents both commands. (`sdk/README.md:13-18`)
-- `sdk/generate.py` accepts `--schema`, `--harness`, or stdin; `--harness` runs `<binary> --schema`. (`sdk/generate.py:22-32`)
-- SDKs are auto-generated and should not be hand-edited. (`sdk/README.md:1-5`)
-
-**CI SDK validation:**
-
-- Python smoke test imports `sdk/py/harness_sdk.py` and asserts `MODELS` and `TOOLS`. (`.github/workflows/ci.yml:15-16`)
-- TS validation parses `sdk/ts/package.json` and uses Node’s experimental type stripping to import `sdk/ts/harness.ts`, checking `Harness`, `runAgent`, and `MODELS`. (`.github/workflows/ci.yml:18-25`)
-
-**SDK package metadata:**
-
-- Python SDK package is `codegraff`, version `0.3.1`, requires Python `>=3.8`, and uses setuptools. (`sdk/py/pyproject.toml:1-20`)
-- TypeScript SDK package is `@codegraff/sdk`, version `0.3.1`, exports `harness.ts` and `remote.ts`, and requires Node `>=18`. (`sdk/ts/package.json:1-31`)
-
-**Publish flow:**
-
-- SDK publishing triggers on tags matching `sdk-v*`. (`.github/workflows/sdk.yml:6-8`)
-- PyPI build uses Python `3.12`, rewrites `pyproject.toml` version from the tag, installs `build`, and runs `python3 -m build`. (`.github/workflows/sdk.yml:20-30`)
-- npm publish uses Node `24`, updates package version from the tag, and runs `npm publish --access public`. (`.github/workflows/sdk.yml:35-44`)
-
-### 12) Remote / edge example
-
-**Local edge-worker smoke flow:**
-
-```sh
-harness serve --port 8926 --token edge-test
-npx wrangler dev --port 8970
-curl http://127.0.0.1:8970
-curl -N 'http://127.0.0.1:8970/?q=run:%20echo%20hi'
-```
-
-- The edge-worker README documents those commands. (`examples/edge-worker/README.md:8-13`)
-- `wrangler.toml` also documents the bridge and `wrangler dev` local check. (`examples/edge-worker/wrangler.toml:1-5`)
-- Worker config sets `name = "harness-edge-worker"`, `main = "src/index.ts"`, compatibility date `2026-04-01`, and `BRIDGE_URL = "http://127.0.0.1:8926"`. (`examples/edge-worker/wrangler.toml:8-14`)
-- For real deploy, the docs say front the bridge with TLS and store the token using `npx wrangler secret put BRIDGE_TOKEN`. (`examples/edge-worker/README.md:20-22`)
-
-## Inferred / not directly wired
-
-- `cd gui && bun run tauri dev` and `cd gui && bun run tauri build` are the likely desktop dev/package commands because the GUI exposes `"tauri": "tauri"` and Tauri config defines `beforeDevCommand`/`beforeBuildCommand`; I did not find these exact commands in CI. (`gui/package.json:14-15`, `gui/src-tauri/tauri.conf.json:6-10`)
-- `cargo test --manifest-path gui/src-tauri/Cargo.toml` is the likely Rust/Tauri unit-test command because Rust tests and dev-dependencies exist, but it is not wired into the package scripts or GitHub Actions I inspected. (`gui/src-tauri/src/runtime/simple.rs:4001-4259`, `gui/src-tauri/Cargo.toml:54-56`)
-- Dependency install is likely `bun install` at the repo root because the root package declares Bun workspaces and pins Bun, but there is no explicit install script. (`package.json:1-9`)
-
-## 3 most load-bearing facts
-
-1. **The authoritative CI path for the CLI is Zig 0.16.0 with `zig build`, `zig fmt --check src/main.zig src/mcp.zig build.zig`, `zig build test --summary all`, JSON protocol test, and SDK drift check.** (`.github/workflows/ci.yml:27-55`)
-2. **The GUI build pipeline is `bun run build:deps && bun run gen:desktop-contracts && tsc -b && vite build`; lint runs the same presteps then `eslint .`; tests are `bun test`.** (`gui/package.json:8-17`)
-3. **The desktop app depends on finding a usable `graff` binary, with `CODEGRAFF_GUI_BINARY` as the first override and bundled/installed/dev locations as fallbacks.** (`gui/src-tauri/src/runtime/simple.rs:3240-3300`)
-
-## Open question
-
-- **Which telemetry behavior is intended for source/dev builds?** `build.zig` says every build gets the default endpoint unless disabled with `-Dtelemetry-endpoint=""`, while README says source builds have no endpoint baked in unless env vars are set. (`build.zig:26-37`, `README.md:656-659`)
diff --git a/.graff/subagents/sa-003-995d48a9.md b/.graff/subagents/sa-003-995d48a9.md
deleted file mode 100644
index da4a84ae..00000000
--- a/.graff/subagents/sa-003-995d48a9.md
+++ /dev/null
@@ -1,106 +0,0 @@
-# subagent sa-003-995d48a9
-
-- label: architecture map
-- kind: workflow_task
-- status: ok
-- elapsed_ms: 206857
-- tools: codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb,bash,bash,bash!,bash!,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb!,codedb,bash,bash,bash,bash,bash,bash,codedb,codedb,codedb,codedb,codedb,codedb,codedb,codedb
-
-## task
-
-Explore the current repository and produce a concise architecture map. Use codedb first (tree, context, outline, search, symbol, callers) before bash grep/find. Identify the tech stack, top-level directories, main entry points, core modules, and data/control flow. Do not edit files.
-
-## report
-
-## Verified architecture map
-
-### Tech stack
-- **Core CLI/agent:** Zig 0.16, built as a single `graff` executable; `build.zig` names the executable `graff` and points its root source at `src/main.zig` (`build.zig:42-49`). README describes it as “a minimal agentic coding harness in Zig 0.16,” using `std.http.Client`, `std.json`, and `std.Io` for HTTPS, JSON, and parallel tool/subagent execution (`README.md:4-5`, `README.md:25-28`).
-- **Desktop GUI:** Tauri 2 + Rust backend + React/TypeScript/Vite frontend. The GUI package depends on React 19, Tauri API/plugin packages, Vite, TypeScript, Zustand, dockview, etc. (`gui/package.json:18-40`, `gui/package.json:42-60`); the Rust crate is `codegraff-gui`, edition 2024, with Tauri, Tokio, Diesel/SQLite, serde, reqwest/rustls, and portable-pty dependencies (`gui/src-tauri/Cargo.toml:7-20`, `gui/src-tauri/Cargo.toml:25-52`).
-- **Monorepo/tooling:** root package is a Bun workspace covering `gui` and `packages/*` (`package.json:1-8`).
-- **Reusable UI package:** `@codegraff/diffs` is a TypeScript package for lightweight diff/file-change rendering, exported for plain and React use (`packages/diffs/package.json:1-24`).
-
-### Top-level directories / major areas
-- **`src/`**: Zig CLI/agent implementation; `build.zig` compiles `src/main.zig` as `graff` (`build.zig:42-49`), and `src/mcp.zig` is a stdio MCP client (`src/mcp.zig:1-12`).
-- **`gui/`**: Tauri desktop app with React frontend and Rust backend; frontend entry renders `App` (`gui/src/main.tsx:1-13`), Rust entry calls `codegraff_gui_lib::run()` (`gui/src-tauri/src/main.rs:4-6`).
-- **`packages/diffs/`**: shared diff-rendering library consumed by the GUI via workspace dependency (`gui/package.json:18-21`, `packages/diffs/package.json:12-24`).
-- **`sdk/` and `examples/`**: SDK/example support exists in the repo tree; README advertises “SDKs — TypeScript & Python” in the docs navigation (`README.md:30-41`). I did not deep-read these because the main runtime/GUI paths were more load-bearing.
-- **`docs/`, `plans/`, `.github/`**: documentation, planning notes, and CI/release workflows observed in the repository tree (`codedb tree`, this run).
-
-### Main entry points
-- **CLI build/runtime entry:** `build.zig` configures build options, version stamping, telemetry endpoint, and installs the `graff` executable from `src/main.zig` (`build.zig:7-40`, `build.zig:42-51`). `src/main.zig` has `pub fn main(init: std.process.Init) !void` and parses CLI flags including `--yolo`, `--json`, `--schema`, `--model`, `--resume`, etc. (`src/main.zig:4307-4385`).
-- **CLI protocol surfaces:** `src/main.zig` embeds a JSON stdio protocol for `--json`, including user/control requests and streamed event types like `text`, `reasoning`, `tool_call`, `tool_result`, `turn`, and `error` (`src/main.zig:79-111`). It also embeds an HTTP bridge schema for `graff serve` with `/healthz`, `/v1/schema`, session create/message/delete endpoints (`src/main.zig:114-128`).
-- **GUI frontend entry:** `gui/src/main.tsx` imports styles and renders `<App />` inside React `StrictMode` (`gui/src/main.tsx:1-13`).
-- **GUI Rust entry:** `gui/src-tauri/src/main.rs` calls `codegraff_gui_lib::run()` (`gui/src-tauri/src/main.rs:4-6`); `run()` builds the Tauri app, installs plugins, initializes app data/project store, manages `DesktopState`, registers invoke commands, and runs the Tauri context (`gui/src-tauri/src/lib.rs:49-85`, `gui/src-tauri/src/lib.rs:108-176`).
-
-### Core modules
-- **Zig agent loop (`src/main.zig`)**
- - `Agent` owns allocator/arena, shared HTTP client, provider, message history, MCP registry, approval/tracing state, system prompts, tool JSON variants, todo state, and runtime options (`src/main.zig:8163-8224`).
- - `Agent.runTurn()` repeatedly sends a model request, dispatches provider-specific response parsing for Anthropic/OpenAI/Responses, and returns once a final text is produced (`src/main.zig:8316-8335`).
- - `Agent.request()` builds provider body, optionally streams root requests, retries flaky HTTP failures, and emits JSON events for GUI/SDK clients (`src/main.zig:8337-8365`).
- - `Agent.runTools()` separates meta tools from external tools, gates/rejects tools, and runs external calls in parallel via `io.async(execTool, ...)`, then joins all futures (`src/main.zig:8807-8870`).
- - `execTool()` applies codedb/companion/hook gates, calls `execToolInner`, records tracing/telemetry/tool-use, and returns structured tool output (`src/main.zig:11809-11831`).
- - `execSubagent()` prevents nested subagents, validates prompt input, and delegates to `runSub()` (`src/main.zig:12484-12494`); `runSub()` creates a fresh `Agent` with fresh history but shared client/provider and runs it to completion (`src/main.zig:12512-12537`, `src/main.zig:12549-12587`).
- - `execWorkflow()` models workflows as sequential phases of parallel subagent tasks, capped at 5 phases and 8 tasks per phase, carrying previous phase results via `{{prev}}` or appended text (`src/main.zig:12594-12600`, `src/main.zig:12601-12617`, `src/main.zig:12635-12672`, `src/main.zig:12675-12698`).
-
-- **MCP client (`src/mcp.zig`)**
- - `src/mcp.zig` is a minimal MCP client over stdio JSON-RPC: it spawns servers from `.mcp.json`, runs `initialize → initialized → tools/list`, exposes namespaced tools, and routes `tools/call` back to the server (`src/mcp.zig:1-12`, `src/mcp.zig:84-120`, `src/mcp.zig:229-323`, `src/mcp.zig:334-404`).
- - MCP access is serialized with a registry mutex because each server has one bidirectional stdio pipe (`src/mcp.zig:8-11`, `src/mcp.zig:355-360`).
-
-- **GUI app shell/state**
- - `App` wraps the UI in `SessionProvider` and `DragDropProvider`, then renders `AppShell` (`gui/src/app/App.tsx:385-396`).
- - `AppShell` composes theme/sidebar/settings state, `ProjectSidebar`, settings panes, and `WorkspaceBoard` inside resizable panels (`gui/src/app/App.tsx:123-170`, `gui/src/app/App.tsx:265-379`).
- - `SessionProvider` is the main frontend orchestrator: it applies snapshots into `sessionStore`, bootstraps via `useSessionBootstrap`, opens workspace paths forwarded from the launcher, and exposes action methods through `SessionActionsContext` (`gui/src/app/SessionProvider.tsx:55-92`, `gui/src/app/SessionProvider.tsx:127-178`, `gui/src/app/SessionProvider.tsx:651-655`).
- - Prompt submission reads active workspace/conversation, appends attachments, clears draft/attachments, calls `desktopClient.sendPrompt`, then applies the returned snapshot (`gui/src/app/SessionProvider.tsx:563-619`).
-
-- **Frontend desktop boundary (`gui/src/services/desktop/client.ts`)**
- - `desktop/client.ts` wraps Tauri `invoke` and `listen`, with a QA mock mode that replaces Tauri calls with deterministic fixtures (`gui/src/services/desktop/client.ts:1-10`, `gui/src/services/desktop/client.ts:56-60`, `gui/src/services/desktop/client.ts:266-319`, `gui/src/services/desktop/client.ts:321-336`).
- - It exports typed functions for workspace/session/prompt/provider/MCP/git/layout/terminal commands; e.g. `openWorkspace`, `getSessionSnapshot`, `sendPrompt`, `runSlashCommand`, MCP functions, provider auth, saved workspaces, and terminal event listeners (`gui/src/services/desktop/client.ts:338-457`, `gui/src/services/desktop/client.ts:529-590`, `gui/src/services/desktop/client.ts:691-800`).
-
-- **Tauri command layer (`gui/src-tauri/src/commands.rs`)**
- - Commands are thin Tauri adapters that map frontend invocations to `DesktopState.manager` methods and convert errors with `format_error_chain` (`gui/src-tauri/src/commands.rs:20-22`, `gui/src-tauri/src/commands.rs:48-80`, `gui/src-tauri/src/commands.rs:155-180`).
- - The command layer also owns some local desktop/file/git helpers: file pickers, pasted image persistence/thumbnailing, workspace-confined file reads, `git clone`, GitHub project creation, and terminal commands (`gui/src-tauri/src/commands.rs:24-46`, `gui/src-tauri/src/commands.rs:252-292`, `gui/src-tauri/src/commands.rs:626-694`, `gui/src-tauri/src/commands.rs:839-958`, `gui/src-tauri/src/commands.rs:781-827`).
-
-- **Desktop runtime adapter (`gui/src-tauri/src/runtime/simple.rs`)**
- - `RuntimeManager` coordinates GUI state, project registry, active `graff --json` sessions, and UI event emission (`gui/src-tauri/src/runtime/simple.rs:104-130`).
- - It maintains `RuntimeState` containing active workspace/conversation, conversations, model/provider selections, pending followups, and model catalog (`gui/src-tauri/src/runtime/simple.rs:51-73`).
- - Each conversation can own a persistent `GraffSession` child process, preserving context and KV cache across turns (`gui/src-tauri/src/runtime/simple.rs:85-97`).
- - `send_prompt()` creates/updates conversation state, queues concurrent prompts, emits snapshots, optionally generates a title, and drives `stream_turn()` (`gui/src-tauri/src/runtime/simple.rs:467-688`).
- - `stream_turn()` writes `{type:"user", text: prompt}` to the child, reads JSONL events, translates them into GUI messages/followups/tool rows/errors, emits snapshots during streaming, and releases session IO at turn end (`gui/src-tauri/src/runtime/simple.rs:690-1005`).
- - `acquire_session_io()` spawns a `graff --json` child on first use and sends live controls for agent, plan mode, effort, fast mode, and ultracode (`gui/src-tauri/src/runtime/simple.rs:1126-1203`).
-
-- **Persistence (`gui/src-tauri/src/persistence/project_store.rs`)**
- - `ProjectStore` uses Diesel with SQLite, with a mutex around connections (`gui/src-tauri/src/persistence/project_store.rs:1-10`, `gui/src-tauri/src/persistence/project_store.rs:31-36`, `gui/src-tauri/src/persistence/project_store.rs:534-544`).
- - It stores opened projects, managed chat workspaces, conversation layouts, saved workspaces, and saved workspace layouts; tables are created/migrated in `init()` (`gui/src-tauri/src/persistence/project_store.rs:460-514`).
- - It supports project registration/listing, managed chat workspace creation, conversation layout save/load, and saved workspace CRUD (`gui/src-tauri/src/persistence/project_store.rs:71-148`, `gui/src-tauri/src/persistence/project_store.rs:286-323`, `gui/src-tauri/src/persistence/project_store.rs:325-458`).
-
-## Data/control flow
-
-### CLI flow
-1. User runs `graff`; `build.zig` builds `src/main.zig` as the `graff` executable (`build.zig:42-51`), and `main()` parses CLI/session/model/protocol flags (`src/main.zig:4307-4385`).
-2. A root `Agent` holds provider, messages, tools, registry, approvals, tracing, and state (`src/main.zig:8163-8224`).
-3. `Agent.runTurn()` loops: build/post request → provider-specific step parsing → if model requests tools, execute them → continue until final text (`src/main.zig:8316-8335`).
-4. External tools run concurrently via `io.async`; meta tools are handled inline, gated tools can be denied, and all futures are joined before result processing (`src/main.zig:8807-8870`).
-5. Subagents/workflows are just tool execution paths that instantiate isolated child `Agent` loops or phase/task fan-outs (`src/main.zig:12484-12587`, `src/main.zig:12597-12698`).
-6. MCP tools are discovered from `.mcp.json`, namespaced as `mcp__<server>__<tool>`, and invoked via JSON-RPC `tools/call` over server stdio (`src/mcp.zig:84-120`, `src/mcp.zig:298-323`, `src/mcp.zig:334-404`).
-
-### Desktop GUI flow
-1. React renders `App`, which mounts `SessionProvider`, drag/drop context, and `AppShell` (`gui/src/main.tsx:9-13`, `gui/src/app/App.tsx:385-396`).
-2. `AppShell` displays sidebar/settings/workspace board and waits for session bootstrap before showing the main shell (`gui/src/app/App.tsx:253-263`, `gui/src/app/App.tsx:265-379`).
-3. `SessionProvider` exposes UI actions and calls `desktopClient` methods; opening a workspace calls `desktopClient.openWorkspace`, applies the returned snapshot, and loads runtime/prompt metadata (`gui/src/app/SessionProvider.tsx:127-149`).
-4. `desktopClient` converts frontend calls into Tauri invokes/listens, or mock responses under `VITE_CODEGRAFF_QA_MOCK=1` (`gui/src/services/desktop/client.ts:311-319`, `gui/src/services/desktop/client.ts:321-336`).
-5. Tauri `commands.rs` maps invokes to `DesktopState.manager` methods (`gui/src-tauri/src/commands.rs:48-80`, `gui/src-tauri/src/commands.rs:155-180`).
-6. `RuntimeManager.send_prompt()` updates conversation state, emits snapshots, then `stream_turn()` writes a JSON user event to the persistent `graff --json` child and translates streamed JSONL events back into GUI messages (`gui/src-tauri/src/runtime/simple.rs:467-688`, `gui/src-tauri/src/runtime/simple.rs:690-1005`).
-7. UI receives live session updates through the Tauri emitter; `emit()` builds a snapshot and calls `emit_session_updated` (`gui/src-tauri/src/runtime/simple.rs:1074-1079`), while frontend listens via `listenSessionUpdates` (`gui/src/services/desktop/client.ts:752-756`).
-
-## Inferred architecture
-- The repo is effectively **two runtimes sharing one agent core**: terminal users talk directly to the Zig `graff` REPL/JSON/HTTP surfaces, while desktop users talk to a Tauri/Rust adapter that keeps long-lived `graff --json` child processes per conversation. This is inferred by combining the CLI `--json` schema (`src/main.zig:79-111`) with `RuntimeManager`’s persistent `GraffSession` design (`gui/src-tauri/src/runtime/simple.rs:85-97`) and child-session streaming (`gui/src-tauri/src/runtime/simple.rs:690-1005`).
-- The GUI Rust layer is intentionally a **thin adapter**, not a replacement agent runtime: comments describe it as coordinating the copied desktop GUI with the Zig-native binary (`gui/src-tauri/src/runtime/simple.rs:104-105`), and many commands simply delegate to `state.manager` (`gui/src-tauri/src/commands.rs:48-80`, `gui/src-tauri/src/commands.rs:155-180`).
-
-## 3 most load-bearing facts
-1. The **agent core is `src/main.zig`**, compiled into `graff`, and it owns provider requests, tool execution, subagents, workflows, and JSON/HTTP protocols (`build.zig:42-49`, `src/main.zig:8316-8365`, `src/main.zig:8807-8870`).
-2. The **desktop app does not reimplement the agent loop**; it spawns and streams from persistent `graff --json` child processes per conversation (`gui/src-tauri/src/runtime/simple.rs:85-97`, `gui/src-tauri/src/runtime/simple.rs:1126-1203`).
-3. The **main UI state transition unit is a `SessionSnapshot`**: frontend actions call `desktopClient`, Tauri commands delegate to `RuntimeManager`, runtime emits snapshots, and frontend applies snapshots into `sessionStore` (`gui/src/app/SessionProvider.tsx:61-65`, `gui/src/services/desktop/client.ts:371-432`, `gui/src-tauri/src/runtime/simple.rs:1074-1079`).
-
-## Open question
-- `src/main.zig` is central and very large, but it was not indexed by `codedb` during this run; why is it absent from the codedb index despite being the root CLI source referenced by `build.zig`?
diff --git a/.graff/subagents/sa-003-ca4e54cc.md b/.graff/subagents/sa-003-ca4e54cc.md
deleted file mode 100644
index 3db03473..00000000
--- a/.graff/subagents/sa-003-ca4e54cc.md
+++ /dev/null
@@ -1,167 +0,0 @@
-# subagent sa-003-ca4e54cc
-
-- label: Explore SDK packages
-- kind: workflow_task
-- status: ok
-- elapsed_ms: 60452
-- tools: codedb,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,codedb,codedb,read_file,read_file,codedb,codedb,codedb,read_file,read_file,read_file
-
-## task
-
-You are exploring the SDK packages in sdk/. Use the codedb tool (search, symbol, outline, callers, context) to thoroughly understand:
-1. The Python SDK (sdk/py/harness_sdk.py, demo.py) — what it does, its API, how it communicates with the harness
-2. The TypeScript SDK (sdk/ts/harness.ts, remote.ts) — what it does, its API, how it communicates
-3. The SDK generation script (sdk/generate.py) — what does it generate and from what
-4. How the SDKs relate to the broader project (are they clients for the core Zig server?)
-
-Be thorough and return a structured markdown report.
-
-## report
-
-# SDK Analysis Report — `sdk/` directory
-
-## 1. Python SDK (`sdk/py/`)
-
-### What it does
-The Python SDK provides two transport variants for driving the harness agent:
-
-- **`Harness`** — spawns a local `graff --json` (or `harness --json`) subprocess and speaks the JSONL stdio protocol directly.
-- **`RemoteHarness`** — connects to a remote `harness serve` bridge over HTTP and exposes the same method surface (`sdk/py/harness_sdk.py:306-432`).
-
-Both classes are context managers (`__enter__`/`__exit__`) and support multi-turn stateful conversations, system-prompt mutation, evaluation scoring for the DGM loop, and OTLP telemetry reporting.
-
-### API surface
-| Method | Purpose | File:Line |
-|--------|---------|-----------|
-| `Harness(...)` | Spawn subprocess with `--json`, optional `--yolo`, `--model`, `--system-prompt`, `--append-system-prompt` | `sdk/py/harness_sdk.py:148-180` |
-| `Harness.chat(text)` | Send a user turn; yield NDJSON events (`text`, `tool_call`, `tool_result`, `turn`, `error`) until terminal | `sdk/py/harness_sdk.py:182-207` |
-| `Harness.ask(text)` | One-shot: run a turn and return just the final assistant text | `sdk/py/harness_sdk.py:209-217` |
-| `Harness.answer(...)` | Reply to an in-flight `ask_user` tool call while consuming `chat()` | `sdk/py/harness_sdk.py:219-228` |
-| `Harness.set_system_prompt(text, append=False)` | Replace or extend the system prompt between turns; blocks on harness ack | `sdk/py/harness_sdk.py:230-255` |
-| `Harness.append_system_prompt(text)` | Convenience wrapper for `set_system_prompt(..., append=True)` | `sdk/py/harness_sdk.py:257-259` |
-| `Harness.score(...)` | Write a DGM evaluation record into `harness.trajectory.jsonl` with optional HMAC provenance | `sdk/py/harness_sdk.py:261-298` |
-| `Harness.pull_elites(...)` | GET `/v1/elites` from the telemetry collector (not the subprocess) | `sdk/py/harness_sdk.py:300-323` |
-| `Harness.close()` | Close stdin, wait up to 15 s for graceful exit, then terminate | `sdk/py/harness_sdk.py:325-336` |
-| `RemoteHarness(...)` | Create or attach to a remote session via `POST /v1/sessions` | `sdk/py/harness_sdk.py:343-360` |
-| `RemoteHarness.chat(text)` | Stream NDJSON events from the bridge | `sdk/py/harness_sdk.py:380-393` |
-| `RemoteHarness.ask(text)` | One-shot remote turn | `sdk/py/harness_sdk.py:395-403` |
-| `RemoteHarness.answer(...)` | POST an answer to the bridge | `sdk/py/harness_sdk.py:405-413` |
-| `RemoteHarness.set_system_prompt(...)` | Mutate prompt remotely | `sdk/py/harness_sdk.py:415-427` |
-| `RemoteHarness.score(...)` | Write score remotely | `sdk/py/harness_sdk.py:429-445` |
-| `RemoteHarness.close()` | DELETE the remote session | `sdk/py/harness_sdk.py:452-457` |
-
-Free functions:
-- `prompt_fingerprint(text)` → SHA-256 first 8 bytes hex (`sdk/py/harness_sdk.py:103-107`)
-- `score_signature(key, ...)` → HMAC of a score record (`sdk/py/harness_sdk.py:109-122`)
-- `verify_score(key, rec)` → boolean validity check (`sdk/py/harness_sdk.py:124-137`)
-
-### How it communicates
-**Local (`Harness`):** Uses `subprocess.Popen` with `stdin=subprocess.PIPE, stdout=subprocess.PIPE` (`sdk/py/harness_sdk.py:175`). The parent writes one JSON object per line to stdin (`{"type":"user","text":"..."}`) and reads NDJSON events from stdout. If the process exits mid-turn without emitting `turn` or `error`, the SDK reports an error to OTLP telemetry and raises `RuntimeError` (`sdk/py/harness_sdk.py:205-207`).
-
-**Remote (`RemoteHarness`):** Uses stdlib `urllib.request` only—no external dependencies. It POSTs to `/v1/sessions` to create a session, then POSTs subsequent requests to `/v1/sessions/{session_id}` and yields NDJSON lines from the response body (`sdk/py/harness_sdk.py:362-378`). Authentication is via an optional `Authorization: Bearer <token>` header (`sdk/py/harness_sdk.py:365-367`).
-
-**Demo:** `sdk/py/demo.py` demonstrates one-shot `ask()`, streamed `chat()` with live tool use, multi-turn persistence, custom prompts via `AGENTS.md` in `cwd`, and full `system_prompt=` replacement (`sdk/py/demo.py:1-110`).
-
----
-
-## 2. TypeScript SDK (`sdk/ts/`)
-
-### What it does
-The TypeScript SDK mirrors the Python SDK but splits into two entry points:
-
-- **`harness.ts`** — Node.js-only client using `node:child_process` and `node:readline` to spawn the local binary.
-- **`remote.ts`** — Edge-runtime client using only `fetch` + Web Streams (no `node:` imports), runnable on Cloudflare Workers, Deno, Bun, browsers, and Node ≥ 18 (`sdk/ts/remote.ts:1-10`).
-
-Both expose identical event types (`Event` union), `ModelName`, `ToolName`, and `ProviderId` unions, plus `promptFingerprint`, `fleetSignal`, and `pullElites` helpers.
-
-### API surface
-| Export | Kind | Purpose | File:Line |
-|--------|------|---------|-----------|
-| `Harness` | class | Node stdio subprocess client | `sdk/ts/harness.ts:157-267` |
-| `Harness.init(opts)` | static | Factory alias for `new Harness(opts)` | `sdk/ts/harness.ts:172` |
-| `Harness.chat(input)` | async generator | Stream events until `turn`/`error` | `sdk/ts/harness.ts:189-205` |
-| `Harness.ask(input)` | async | Return final assistant text | `sdk/ts/harness.ts:207-215` |
-| `Harness.answer(input)` | method | Write answer to stdin for `ask_user` | `sdk/ts/harness.ts:217-223` |
-| `Harness.setSystemPrompt(text, append)` | async | Replace/extend prompt; resolves on ack | `sdk/ts/harness.ts:225-238` |
-| `Harness.score(...)` | async | Write DGM score record | `sdk/ts/harness.ts:248-261` |
-| `Harness.pullElites(...)` | async | GET `/v1/elites` from collector | `sdk/ts/harness.ts:263-281` |
-| `Harness.session()` | method | Return `HarnessSession` wrapper | `sdk/ts/harness.ts:287` |
-| `HarnessSession` | class | Thin wrapper over `Harness` for parity with codegraff’s `GraffSession` | `sdk/ts/harness.ts:291-301` |
-| `runAgent(opts)` | async generator | One-shot: spawn, chat, close | `sdk/ts/harness.ts:305-312` |
-| `RemoteHarness` | class | Fetch-based remote bridge client | `sdk/ts/remote.ts:73-181` |
-| `RemoteHarness.init(opts)` | static | Factory | `sdk/ts/remote.ts:85` |
-| `RemoteHarness.chat(input)` | async generator | Stream NDJSON from bridge | `sdk/ts/remote.ts:127-140` |
-| `RemoteHarness.ask(input)` | async | One-shot remote | `sdk/ts/remote.ts:142-150` |
-| `RemoteHarness.answer(...)` | async | POST answer to bridge | `sdk/ts/remote.ts:152-163` |
-| `RemoteHarness.setSystemPrompt(...)` | async | Remote prompt mutation | `sdk/ts/remote.ts:165-174` |
-| `RemoteHarness.score(...)` | async | Remote score write | `sdk/ts/remote.ts:176-188` |
-| `runAgentRemote(opts)` | async generator | One-shot remote | `sdk/ts/remote.ts:193-200` |
-
-### How it communicates
-**Local (`harness.ts`):** Spawns `opts.binary ?? defaultBinary()` with `spawnArgs(opts)` (always includes `--json`). Stderr is inherited (`stdio: ["pipe", "pipe", "inherit"]`) so tool progress prints directly to the terminal (`sdk/ts/harness.ts:165-167`). A `readline.Interface` pumps stdout line-by-line into an internal queue/buffer. If the process errors or closes before a terminal event, `reportError` fires OTLP telemetry and the waiting promise rejects (`sdk/ts/harness.ts:180-184`).
-
-**Remote (`remote.ts`):** Uses `fetch` exclusively. `create()` POSTs to `/v1/sessions` with `{model?, yolo?, system_prompt?, append_system_prompt?}` and stores the returned `session_id` (`sdk/ts/remote.ts:95-110`). Every turn POSTs to `/v1/sessions/{id}` and the response body is parsed via `ndjson()`, a Web-Streams reader that yields parsed JSON lines (`sdk/ts/remote.ts:47-71`). If the stream ends without a terminal event, it throws `Error: bridge stream ended mid-turn`.
-
----
-
-## 3. SDK Generation Script (`sdk/generate.py`)
-
-### What it does
-`generate.py` is a codegen tool that reads the JSON schema emitted by `graff --schema` and produces all three SDK artifacts:
-
-- `sdk/ts/harness.ts` — Node.js stdio client
-- `sdk/ts/remote.ts` — Edge-safe fetch client
-- `sdk/py/harness_sdk.py` — Python stdio + urllib client
-
-The script is the **single source of truth** for SDK types; the generated files carry the header `"AUTO-GENERATED by sdk/generate.py from \`harness --schema\`. Do not edit."` (`sdk/generate.py:1`, `sdk/ts/harness.ts:1`, `sdk/py/harness_sdk.py:1`).
-
-### How it works
-1. **Schema ingestion** (`load_schema`) accepts:
- - `stdin` (e.g. `graff --schema | python3 sdk/generate.py`)
- - `--schema FILE`
- - `--harness BIN` (runs the binary for you)
- (`sdk/generate.py:16-34`)
-
-2. **Type extraction** pulls three arrays from the schema:
- - `models` → `ModelName` union / `MODELS` constant
- - `tools` → `ToolName` union / `TOOLS` constant
- - `providers` → `ProviderId` union / `PROVIDERS` constant
- - `version` → `HARNESS_VERSION` constant
- (`sdk/generate.py:37-42`, `sdk/generate.py:44-47`, `sdk/generate.py:431-438`)
-
-3. **Template generation** uses large Python f-string templates that embed the sorted unions and version. The templates contain the full class implementations (including telemetry, prompt fingerprinting, score signing, event parsing, etc.). No logic is synthesized from the schema beyond the literal type constants and version string; the rest is static boilerplate maintained inside `generate.py` itself.
-
-4. **Output** writes all three files via `write()` and prints byte counts (`sdk/generate.py:439-445`).
-
-### CI enforcement
-The `.github/workflows/sdk.yml` workflow publishes the committed SDKs to npm and PyPI on every `sdk-v*` tag, but the generation must be run locally before tagging because the action does **not** regenerate— it ships what is committed (`sdk/README.md:11-15`, `.github/workflows/sdk.yml:1-8`). The `.github/workflows/ci.yml` also includes a `sdk` job that validates the committed SDKs without requiring a Zig build (`codedb` context for `.github/workflows/ci.yml:10`).
-
----
-
-## 4. Relationship to the Broader Project
-
-### Verified facts
-1. **The core is a Zig CLI binary.** The project’s engine lives in `src/main.zig` (~1,250 lines of Zig 0.16) and compiles to a single executable named `graff` (formerly `harness`) (`architecture.md:1-3`, `build.zig:32-35`).
-2. **The SDKs are thin clients over that binary.** They do not reimplement the agent loop, LLM provider routing, tool dispatch, or context compaction. They only wrap the `--json` stdio protocol or the HTTP bridge (`harness serve`) (`sdk/README.md:1-4`, `sdk/ts/harness.ts:155-157`).
-3. **`harness --schema` is the contract.** The Zig binary emits its own interface (models, tools, providers, event protocol, version). The generation script consumes this JSON to keep the SDK types in lockstep with the binary (`sdk/generate.py:1-8`, `sdk/README.md:11-15`).
-4. **`harness serve` is an HTTP bridge.** The remote clients do not talk to a separate server implementation. The server side of the bridge still runs the same `harness --json` child per session; one POST equals one protocol request, streamed back as NDJSON (`sdk/ts/remote.ts:1-10`, `sdk/py/harness_sdk.py:338-341`).
-5. **The DGM evolution loop is built on the SDK.** `examples/dgm_loop.py` imports `Harness`, `prompt_fingerprint`, and `verify_score` from the Python SDK to implement a Darwin Gödel Machine that mutates system prompts, scores them via a replay judge, and writes lineage into the trajectory archive (`examples/dgm_loop.py:18-20`, `examples/dgm_loop.py:101-110`).
-6. **Telemetry is shared.** Both the harness binary and the SDKs report to the same OTLP endpoint (`https://harness-telemetry.rachpradhan.workers.dev` by default) using the same opt-out environment variables (`GRAFF_NO_TELEMETRY`, `OTEL_EXPORTER_OTLP_ENDPOINT`) (`sdk/py/harness_sdk.py:54-96`, `sdk/ts/harness.ts:79-121`).
-7. **The CLI was renamed.** The default binary is now `graff`, with `harness` as a fallback compatibility name (`sdk/py/harness_sdk.py:139-142`, `sdk/ts/harness.ts:133-140`).
-
-### Inferred but not directly verified
-- The `harness serve` mode is likely implemented inside `src/main.zig` as an HTTP server (referenced in `architecture.md` under “Where this could go next” and in `sdk/ts/remote.ts` comments), but I did not read the Zig server code directly because `src/main.zig` is not indexed by `codedb` in this output.
-
----
-
-## Top 3 Load-Bearing Facts
-
-1. **The SDKs are auto-generated from `graff --schema`; the schema JSON is the only source of truth for models, tools, providers, and the event protocol.** Any drift between the binary and the SDKs is caught by regenerating via `sdk/generate.py` (`sdk/generate.py:1`, `sdk/py/harness_sdk.py:1`, `sdk/ts/harness.ts:1`).
-2. **Both Python and TypeScript SDKs are thin wrappers: they spawn the local Zig binary (`Harness`) or talk HTTP to a bridge that still spawns the binary per session (`RemoteHarness`).** They do not contain the agent loop, tool implementations, or LLM logic (`sdk/py/harness_sdk.py:148-180`, `sdk/ts/harness.ts:157-167`, `sdk/README.md:1-4`).
-3. **The `score()` and `pull_elites()` APIs exist to support the Darwin Gödel Machine evolution loop.** The SDK is not just a chat client; it is the programmatic interface for automated prompt evolution, with HMAC-signed fitness records and fleet telemetry (`sdk/py/harness_sdk.py:261-323`, `examples/dgm_loop.py:1-110`).
-
----
-
-## 1 Open Question
-
-**Does `harness serve` (the HTTP bridge) live entirely in `src/main.zig`, or is it a separate binary / wrapper?** The SDKs and docs refer to it as the server side of the remote transport, but I did not inspect the Zig source to confirm whether it is a built-in subcommand (`graff serve`) or an external component.
diff --git a/.graff/subagents/sa-004-7c59681c.md b/.graff/subagents/sa-004-7c59681c.md
deleted file mode 100644
index 2f305eb3..00000000
--- a/.graff/subagents/sa-004-7c59681c.md
+++ /dev/null
@@ -1,119 +0,0 @@
-# subagent sa-004-7c59681c
-
-- label: TUI prompt provenance
-- kind: workflow_task
-- status: ok
-- elapsed_ms: 317731
-- tools: codedb,codedb,codedb,codedb,codedb,codedb,bash,codedb,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash!,bash,bash,bash,bash,bash,bash,bash!,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash
-
-## task
-
-Investigate why the TUI prompt UX that used to look like `[gpt-5.5]({folder_name})` might be missing in the current checkout/binary. Use codedb first (search/symbol/outline/context) to inspect `src/main.zig` prompt rendering and any recent changes around model/workspace/folder display. Compare with git history/branches only as needed. Report: current code path, whether folder_name is present, and likely cause.
-
-## report
-
-## Verified
-
-### 1) Current checkout still has workspace/folder data, but it is `g_cwd_display`, not `folder_name`
-
-- `src/main.zig` defines a global display string: `g_cwd_display`, documented as “Human-facing current workspace folder shown in the REPL prompt.” (`src/main.zig:2557-2560`)
-- At startup, it is populated from `Io.Dir.cwd().realPath(...)`, falling back to `$PWD` or `"."`; this means it is the full cwd path, not a basename/folder-name-only value. (`src/main.zig:4573-4577`)
-- The startup banner also prints it as `folder: <g_cwd_display>`. (`src/main.zig:4579-4580`)
-- I found no current `folder_name` symbol via codedb (`codedb search "folder_name"` returned no results), and the current code path uses `g_cwd_display`.
-
-### 2) Current prompt-rendering function would show the cwd if it were called
-
-`Agent.prompt()` renders the TUI prompt. In the current checkout:
-
-- It early-returns in JSON mode, so GUI/SDK `--json` sessions never get the human prompt. (`src/main.zig:8226-8228`)
-- It computes mode/cost/cache suffixes. (`src/main.zig:8229-8242`)
-- With context tokens, it prints:
-
- ```text
- [<model><flags> · cwd <g_cwd_display> · <tokens>k tok ...] ›
- ```
-
- (`src/main.zig:8243-8251`)
-
-- Without context tokens, it prints:
-
- ```text
- [<model><flags> · cwd <g_cwd_display><cost>] ›
- ```
-
- (`src/main.zig:8252-8258`)
-
-So the current intended prompt shape is **not** `[gpt-5.5]({folder_name})`; it is closer to:
-
-```text
-[gpt-5.5 · cwd /full/path] ›
-```
-
-or, once token metadata exists:
-
-```text
-[gpt-5.5 · cwd /full/path · 123/217k tok (56%)] ›
-```
-
-### 3) The likely bug: the main REPL loop no longer calls `root.prompt()` before reading input
-
-In the current checkout, the REPL loop starts at `while (true)` and immediately drains steering input / reads a line:
-
-- Current loop begins with steering-drain setup. (`src/main.zig:4904-4911`)
-- It then sets `raw_line` from queued steering input, `readLine(...)`, or stdin delimiter. (`src/main.zig:4912-4923`)
-- There is **no** `try root.prompt();` at the top of this loop. (`src/main.zig:4904-4923`)
-
-The only current `root.prompt()` calls I found are inside `readLine` feedback paths after clipboard/image/drop messages:
-
-- Clipboard-image feedback redraws by calling `root.prompt()`. (`src/main.zig:3670-3675`)
-- Drag/drop image feedback redraws by calling `root.prompt()`. (`src/main.zig:3850-3855`)
-
-That means normal interactive input can miss the model/cwd prompt entirely, even though `Agent.prompt()` still exists and contains cwd rendering.
-
-### 4) Git history points to `1f54380` as the likely regression
-
-Before the steering feature, the loop explicitly rendered the prompt before reading input:
-
-- In `91a7c2e:src/main.zig`, the main loop had:
-
- ```zig
- while (true) {
- try root.prompt();
- const raw_line = if (interactive)
- (try readLine(...))
- ```
-
- (`91a7c2e:src/main.zig:4539-4544`, viewed via `git show 91a7c2e:src/main.zig | nl -ba`)
-
-The steering commit changed that loop:
-
-- In `1f54380:src/main.zig`, the loop begins with steering-drain code and then reads either a queued steer line or `readLine(...)`; the `try root.prompt();` line is gone. (`1f54380:src/main.zig:4774-4789`, viewed via `git show 1f54380:src/main.zig | nl -ba`)
-- The commit is titled `feat: Codex-style steering — queue follow-up prompts while a turn streams`, and its diff shows the removal of `try root.prompt();` in the loop (`git show 1f54380 -- src/main.zig`, diff hunk around old loop).
-
-So the most likely cause is: **the steering-followup change accidentally removed the normal prompt render call from the top of the REPL loop.**
-
-### 5) Current installed/built binaries may also be behind the current checkout
-
-In this environment:
-
-- `git describe` reports the checkout as `v0.0.161-24-g85ccf25`.
-- `./zig-out/bin/graff --version` reports `simple-harness v0.0.14-7-g782e707-dirty`.
-- `graff --version` from PATH reports `graff v0.0.161-18-g7bea7e7`.
-
-So a user testing “current binary” may not actually be running the exact current checkout. However, `7bea7e7` also lacks the normal loop `root.prompt()` call and still has only the redraw-path calls, so the missing TUI prompt is consistent with both the installed PATH binary and the current checkout.
-
-## Inferred
-
-- The old UX remembered as `[gpt-5.5]({folder_name})` does not match the exact current or recent source format I verified. The verified current format would be `[gpt-5.5 · cwd <full path>] ›`, not `[gpt-5.5](folder)`.
-- If a user sees no model/folder prompt at all, the likely reason is not that folder data disappeared; it is that the main interactive loop stopped invoking `Agent.prompt()` before `readLine`.
-- If a user sees only the startup `codegraff · folder: ...` banner but not per-turn `[model · cwd ...] ›`, that is exactly what the current control flow predicts.
-
-## 3 most load-bearing facts
-
-1. `Agent.prompt()` still contains cwd rendering using `g_cwd_display`. (`src/main.zig:8226-8258`)
-2. `g_cwd_display` is still populated from the current real cwd at startup. (`src/main.zig:4573-4577`)
-3. The current main REPL loop reads input without calling `root.prompt()`, whereas pre-steering history did call `try root.prompt();` before `readLine`. (`src/main.zig:4904-4923`; `91a7c2e:src/main.zig:4539-4544`; `1f54380:src/main.zig:4774-4789`)
-
-## Open question
-
-Was the desired UX supposed to be the remembered compact basename form `[gpt-5.5]({folder_name})`, or is the intended current design the checked-in full-path form `[gpt-5.5 · cwd /full/path] ›` once the missing `root.prompt()` call is restored?
diff --git a/.graff/subagents/sa-004-ca7d57ca.md b/.graff/subagents/sa-004-ca7d57ca.md
deleted file mode 100644
index 663d0e8d..00000000
--- a/.graff/subagents/sa-004-ca7d57ca.md
+++ /dev/null
@@ -1,1417 +0,0 @@
-# subagent sa-004-ca7d57ca
-
-- label: codebase tour
-- kind: workflow_task
-- status: ok
-- elapsed_ms: 178793
-- tools: (none)
-
-## task
-
-Synthesize the reconnaissance results into a clear guided tour of the codebase for the user. Include: project purpose/stack, directory map, main execution flow, key modules, how to run/test, risks/hotspots, and recommended next exploration steps. Previous phase results:
-### architecture map
-## Verified architecture map
-
-### Tech stack
-- **Core CLI/agent:** Zig 0.16, built as a single `graff` executable; `build.zig` names the executable `graff` and points its root source at `src/main.zig` (`build.zig:42-49`). README describes it as “a minimal agentic coding harness in Zig 0.16,” using `std.http.Client`, `std.json`, and `std.Io` for HTTPS, JSON, and parallel tool/subagent execution (`README.md:4-5`, `README.md:25-28`).
-- **Desktop GUI:** Tauri 2 + Rust backend + React/TypeScript/Vite frontend. The GUI package depends on React 19, Tauri API/plugin packages, Vite, TypeScript, Zustand, dockview, etc. (`gui/package.json:18-40`, `gui/package.json:42-60`); the Rust crate is `codegraff-gui`, edition 2024, with Tauri, Tokio, Diesel/SQLite, serde, reqwest/rustls, and portable-pty dependencies (`gui/src-tauri/Cargo.toml:7-20`, `gui/src-tauri/Cargo.toml:25-52`).
-- **Monorepo/tooling:** root package is a Bun workspace covering `gui` and `packages/*` (`package.json:1-8`).
-- **Reusable UI package:** `@codegraff/diffs` is a TypeScript package for lightweight diff/file-change rendering, exported for plain and React use (`packages/diffs/package.json:1-24`).
-
-### Top-level directories / major areas
-- **`src/`**: Zig CLI/agent implementation; `build.zig` compiles `src/main.zig` as `graff` (`build.zig:42-49`), and `src/mcp.zig` is a stdio MCP client (`src/mcp.zig:1-12`).
-- **`gui/`**: Tauri desktop app with React frontend and Rust backend; frontend entry renders `App` (`gui/src/main.tsx:1-13`), Rust entry calls `codegraff_gui_lib::run()` (`gui/src-tauri/src/main.rs:4-6`).
-- **`packages/diffs/`**: shared diff-rendering library consumed by the GUI via workspace dependency (`gui/package.json:18-21`, `packages/diffs/package.json:12-24`).
-- **`sdk/` and `examples/`**: SDK/example support exists in the repo tree; README advertises “SDKs — TypeScript & Python” in the docs navigation (`README.md:30-41`). I did not deep-read these because the main runtime/GUI paths were more load-bearing.
-- **`docs/`, `plans/`, `.github/`**: documentation, planning notes, and CI/release workflows observed in the repository tree (`codedb tree`, this run).
-
-### Main entry points
-- **CLI build/runtime entry:** `build.zig` configures build options, version stamping, telemetry endpoint, and installs the `graff` executable from `src/main.zig` (`build.zig:7-40`, `build.zig:42-51`). `src/main.zig` has `pub fn main(init: std.process.Init) !void` and parses CLI flags including `--yolo`, `--json`, `--schema`, `--model`, `--resume`, etc. (`src/main.zig:4307-4385`).
-- **CLI protocol surfaces:** `src/main.zig` embeds a JSON stdio protocol for `--json`, including user/control requests and streamed event types like `text`, `reasoning`, `tool_call`, `tool_result`, `turn`, and `error` (`src/main.zig:79-111`). It also embeds an HTTP bridge schema for `graff serve` with `/healthz`, `/v1/schema`, session create/message/delete endpoints (`src/main.zig:114-128`).
-- **GUI frontend entry:** `gui/src/main.tsx` imports styles and renders `<App />` inside React `StrictMode` (`gui/src/main.tsx:1-13`).
-- **GUI Rust entry:** `gui/src-tauri/src/main.rs` calls `codegraff_gui_lib::run()` (`gui/src-tauri/src/main.rs:4-6`); `run()` builds the Tauri app, installs plugins, initializes app data/project store, manages `DesktopState`, registers invoke commands, and runs the Tauri context (`gui/src-tauri/src/lib.rs:49-85`, `gui/src-tauri/src/lib.rs:108-176`).
-
-### Core modules
-- **Zig agent loop (`src/main.zig`)**
- - `Agent` owns allocator/arena, shared HTTP client, provider, message history, MCP registry, approval/tracing state, system prompts, tool JSON variants, todo state, and runtime options (`src/main.zig:8163-8224`).
- - `Agent.runTurn()` repeatedly sends a model request, dispatches provider-specific response parsing for Anthropic/OpenAI/Responses, and returns once a final text is produced (`src/main.zig:8316-8335`).
- - `Agent.request()` builds provider body, optionally streams root requests, retries flaky HTTP failures, and emits JSON events for GUI/SDK clients (`src/main.zig:8337-8365`).
- - `Agent.runTools()` separates meta tools from external tools, gates/rejects tools, and runs external calls in parallel via `io.async(execTool, ...)`, then joins all futures (`src/main.zig:8807-8870`).
- - `execTool()` applies codedb/companion/hook gates, calls `execToolInner`, records tracing/telemetry/tool-use, and returns structured tool output (`src/main.zig:11809-11831`).
- - `execSubagent()` prevents nested subagents, validates prompt input, and delegates to `runSub()` (`src/main.zig:12484-12494`); `runSub()` creates a fresh `Agent` with fresh history but shared client/provider and runs it to completion (`src/main.zig:12512-12537`, `src/main.zig:12549-12587`).
- - `execWorkflow()` models workflows as sequential phases of parallel subagent tasks, capped at 5 phases and 8 tasks per phase, carrying previous phase results via `{{prev}}` or appended text (`src/main.zig:12594-12600`, `src/main.zig:12601-12617`, `src/main.zig:12635-12672`, `src/main.zig:12675-12698`).
-
-- **MCP client (`src/mcp.zig`)**
- - `src/mcp.zig` is a minimal MCP client over stdio JSON-RPC: it spawns servers from `.mcp.json`, runs `initialize → initialized → tools/list`, exposes namespaced tools, and routes `tools/call` back to the server (`src/mcp.zig:1-12`, `src/mcp.zig:84-120`, `src/mcp.zig:229-323`, `src/mcp.zig:334-404`).
- - MCP access is serialized with a registry mutex because each server has one bidirectional stdio pipe (`src/mcp.zig:8-11`, `src/mcp.zig:355-360`).
-
-- **GUI app shell/state**
- - `App` wraps the UI in `SessionProvider` and `DragDropProvider`, then renders `AppShell` (`gui/src/app/App.tsx:385-396`).
- - `AppShell` composes theme/sidebar/settings state, `ProjectSidebar`, settings panes, and `WorkspaceBoard` inside resizable panels (`gui/src/app/App.tsx:123-170`, `gui/src/app/App.tsx:265-379`).
- - `SessionProvider` is the main frontend orchestrator: it applies snapshots into `sessionStore`, bootstraps via `useSessionBootstrap`, opens workspace paths forwarded from the launcher, and exposes action methods through `SessionActionsContext` (`gui/src/app/SessionProvider.tsx:55-92`, `gui/src/app/SessionProvider.tsx:127-178`, `gui/src/app/SessionProvider.tsx:651-655`).
- - Prompt submission reads active workspace/conversation, appends attachments, clears draft/attachments, calls `desktopClient.sendPrompt`, then applies the returned snapshot (`gui/src/app/SessionProvider.tsx:563-619`).
-
-- **Frontend desktop boundary (`gui/src/services/desktop/client.ts`)**
- - `desktop/client.ts` wraps Tauri `invoke` and `listen`, with a QA mock mode that replaces Tauri calls with deterministic fixtures (`gui/src/services/desktop/client.ts:1-10`, `gui/src/services/desktop/client.ts:56-60`, `gui/src/services/desktop/client.ts:266-319`, `gui/src/services/desktop/client.ts:321-336`).
- - It exports typed functions for workspace/session/prompt/provider/MCP/git/layout/terminal commands; e.g. `openWorkspace`, `getSessionSnapshot`, `sendPrompt`, `runSlashCommand`, MCP functions, provider auth, saved workspaces, and terminal event listeners (`gui/src/services/desktop/client.ts:338-457`, `gui/src/services/desktop/client.ts:529-590`, `gui/src/services/desktop/client.ts:691-800`).
-
-- **Tauri command layer (`gui/src-tauri/src/commands.rs`)**
- - Commands are thin Tauri adapters that map frontend invocations to `DesktopState.manager` methods and convert errors with `format_error_chain` (`gui/src-tauri/src/commands.rs:20-22`, `gui/src-tauri/src/commands.rs:48-80`, `gui/src-tauri/src/commands.rs:155-180`).
- - The command layer also owns some local desktop/file/git helpers: file pickers, pasted image persistence/thumbnailing, workspace-confined file reads, `git clone`, GitHub project creation, and terminal commands (`gui/src-tauri/src/commands.rs:24-46`, `gui/src-tauri/src/commands.rs:252-292`, `gui/src-tauri/src/commands.rs:626-694`, `gui/src-tauri/src/commands.rs:839-958`, `gui/src-tauri/src/commands.rs:781-827`).
-
-- **Desktop runtime adapter (`gui/src-tauri/src/runtime/simple.rs`)**
- - `RuntimeManager` coordinates GUI state, project registry, active `graff --json` sessions, and UI event emission (`gui/src-tauri/src/runtime/simple.rs:104-130`).
- - It maintains `RuntimeState` containing active workspace/conversation, conversations, model/provider selections, pending followups, and model catalog (`gui/src-tauri/src/runtime/simple.rs:51-73`).
- - Each conversation can own a persistent `GraffSession` child process, preserving context and KV cache across turns (`gui/src-tauri/src/runtime/simple.rs:85-97`).
- - `send_prompt()` creates/updates conversation state, queues concurrent prompts, emits snapshots, optionally generates a title, and drives `stream_turn()` (`gui/src-tauri/src/runtime/simple.rs:467-688`).
- - `stream_turn()` writes `{type:"user", text: prompt}` to the child, reads JSONL events, translates them into GUI messages/followups/tool rows/errors, emits snapshots during streaming, and releases session IO at turn end (`gui/src-tauri/src/runtime/simple.rs:690-1005`).
- - `acquire_session_io()` spawns a `graff --json` child on first use and sends live controls for agent, plan mode, effort, fast mode, and ultracode (`gui/src-tauri/src/runtime/simple.rs:1126-1203`).
-
-- **Persistence (`gui/src-tauri/src/persistence/project_store.rs`)**
- - `ProjectStore` uses Diesel with SQLite, with a mutex around connections (`gui/src-tauri/src/persistence/project_store.rs:1-10`, `gui/src-tauri/src/persistence/project_store.rs:31-36`, `gui/src-tauri/src/persistence/project_store.rs:534-544`).
- - It stores opened projects, managed chat workspaces, conversation layouts, saved workspaces, and saved workspace layouts; tables are created/migrated in `init()` (`gui/src-tauri/src/persistence/project_store.rs:460-514`).
- - It supports project registration/listing, managed chat workspace creation, conversation layout save/load, and saved workspace CRUD (`gui/src-tauri/src/persistence/project_store.rs:71-148`, `gui/src-tauri/src/persistence/project_store.rs:286-323`, `gui/src-tauri/src/persistence/project_store.rs:325-458`).
-
-## Data/control flow
-
-### CLI flow
-1. User runs `graff`; `build.zig` builds `src/main.zig` as the `graff` executable (`build.zig:42-51`), and `main()` parses CLI/session/model/protocol flags (`src/main.zig:4307-4385`).
-2. A root `Agent` holds provider, messages, tools, registry, approvals, tracing, and state (`src/main.zig:8163-8224`).
-3. `Agent.runTurn()` loops: build/post request → provider-specific step parsing → if model requests tools, execute them → continue until final text (`src/main.zig:8316-8335`).
-4. External tools run concurrently via `io.async`; meta tools are handled inline, gated tools can be denied, and all futures are joined before result processing (`src/main.zig:8807-8870`).
-5. Subagents/workflows are just tool execution paths that instantiate isolated child `Agent` loops or phase/task fan-outs (`src/main.zig:12484-12587`, `src/main.zig:12597-12698`).
-6. MCP tools are discovered from `.mcp.json`, namespaced as `mcp__<server>__<tool>`, and invoked via JSON-RPC `tools/call` over server stdio (`src/mcp.zig:84-120`, `src/mcp.zig:298-323`, `src/mcp.zig:334-404`).
-
-### Desktop GUI flow
-1. React renders `App`, which mounts `SessionProvider`, drag/drop context, and `AppShell` (`gui/src/main.tsx:9-13`, `gui/src/app/App.tsx:385-396`).
-2. `AppShell` displays sidebar/settings/workspace board and waits for session bootstrap before showing the main shell (`gui/src/app/App.tsx:253-263`, `gui/src/app/App.tsx:265-379`).
-3. `SessionProvider` exposes UI actions and calls `desktopClient` methods; opening a workspace calls `desktopClient.openWorkspace`, applies the returned snapshot, and loads runtime/prompt metadata (`gui/src/app/SessionProvider.tsx:127-149`).
-4. `desktopClient` converts frontend calls into Tauri invokes/listens, or mock responses under `VITE_CODEGRAFF_QA_MOCK=1` (`gui/src/services/desktop/client.ts:311-319`, `gui/src/services/desktop/client.ts:321-336`).
-5. Tauri `commands.rs` maps invokes to `DesktopState.manager` methods (`gui/src-tauri/src/commands.rs:48-80`, `gui/src-tauri/src/commands.rs:155-180`).
-6. `RuntimeManager.send_prompt()` updates conversation state, emits snapshots, then `stream_turn()` writes a JSON user event to the persistent `graff --json` child and translates streamed JSONL events back into GUI messages (`gui/src-tauri/src/runtime/simple.rs:467-688`, `gui/src-tauri/src/runtime/simple.rs:690-1005`).
-7. UI receives live session updates through the Tauri emitter; `emit()` builds a snapshot and calls `emit_session_updated` (`gui/src-tauri/src/runtime/simple.rs:1074-1079`), while frontend listens via `listenSessionUpdates` (`gui/src/services/desktop/client.ts:752-756`).
-
-## Inferred architecture
-- The repo is effectively **two runtimes sharing one agent core**: terminal users talk directly to the Zig `graff` REPL/JSON/HTTP surfaces, while desktop users talk to a Tauri/Rust adapter that keeps long-lived `graff --json` child processes per conversation. This is inferred by combining the CLI `--json` schema (`src/main.zig:79-111`) with `RuntimeManager`’s persistent `GraffSession` design (`gui/src-tauri/src/runtime/simple.rs:85-97`) and child-session streaming (`gui/src-tauri/src/runtime/simple.rs:690-1005`).
-- The GUI Rust layer is intentionally a **thin adapter**, not a replacement agent runtime: comments describe it as coordinating the copied desktop GUI with the Zig-native binary (`gui/src-tauri/src/runtime/simple.rs:104-105`), and many commands simply delegate to `state.manager` (`gui/src-tauri/src/commands.rs:48-80`, `gui/src-tauri/src/commands.rs:155-180`).
-
-## 3 most load-bearing facts
-1. The **agent core is `src/main.zig`**, compiled into `graff`, and it owns provider requests, tool execution, subagents, workflows, and JSON/HTTP protocols (`build.zig:42-49`, `src/main.zig:8316-8365`, `src/main.zig:8807-8870`).
-2. The **desktop app does not reimplement the agent loop**; it spawns and streams from persistent `graff --json` child processes per conversation (`gui/src-tauri/src/runtime/simple.rs:85-97`, `gui/src-tauri/src/runtime/simple.rs:1126-1203`).
-3. The **main UI state transition unit is a `SessionSnapshot`**: frontend actions call `desktopClient`, Tauri commands delegate to `RuntimeManager`, runtime emits snapshots, and frontend applies snapshots into `sessionStore` (`gui/src/app/SessionProvider.tsx:61-65`, `gui/src/services/desktop/client.ts:371-432`, `gui/src-tauri/src/runtime/simple.rs:1074-1079`).
-
-## Open question
-- `src/main.zig` is central and very large, but it was not indexed by `codedb` during this run; why is it absent from the codedb index despite being the root CLI source referenced by `build.zig`?
-
-[subagent sa-003-995d48a9 · inspect: .graff/subagents/sa-003-995d48a9.md]
-
-### build test config
-## Verified repository build/run/test/lint/config map
-
-### 1) Top-level project structure and package manager
-
-- The repository is a mixed Zig CLI + Bun workspace + Tauri/Rust desktop app + SDKs repo. The root `package.json` is private, pins `[email protected]`, and declares workspaces `gui` and `packages/*`; it has no root `scripts` block. (`package.json:1-9`)
-- The main Zig build creates a single executable named `graff` from `src/main.zig`. (`build.zig:42-51`)
-- The GUI is a separate Bun workspace package named `codegraff-gui`, also pinned to `[email protected]`. (`gui/package.json:1-7`)
-- The reusable diff renderer is a workspace package named `@codegraff/diffs`. (`packages/diffs/package.json:1-7`)
-
-### 2) CLI / Zig build and run
-
-**Build:**
-
-```sh
-zig build
-```
-
-- CI runs exactly `zig build`. (`.github/workflows/ci.yml:39-40`)
-- The Zig build installs the `graff` artifact via `b.installArtifact(exe)`. (`build.zig:42-51`)
-
-**Run from source:**
-
-```sh
-zig build run
-# or
-./zig-out/bin/graff
-```
-
-- `build.zig` defines a `run` step that runs the built executable. (`build.zig:53-56`)
-- README documents `zig build run` and `./zig-out/bin/graff` as in-place alternatives. (`README.md:692-699`)
-
-**Release/cross-compile:**
-
-```sh
-zig build -Doptimize=ReleaseSafe -Dtarget="$target" -Dversion="$VERSION" -Dtelemetry-endpoint="$TELEMETRY_ENDPOINT"
-```
-
-- Release CI runs that command for `aarch64-macos`, `x86_64-macos`, `x86_64-linux`, and `aarch64-linux`. (`.github/workflows/release.yml:24-33`)
-- Release artifacts are tarballs containing `graff`, `README.md`, and `LICENSE`, plus `SHA256SUMS`. (`.github/workflows/release.yml:34-40`)
-- Release is triggered by tags matching `v*`. (`.github/workflows/release.yml:6-8`)
-
-**Versioning / build options:**
-
-- `-Dversion=...` overrides the version string; otherwise `build.zig` derives it from `git describe --tags --always --dirty`, falling back to `0.1.0-dev`. (`build.zig:7-25`)
-- `-Dtelemetry-endpoint=...` sets a baked-in default OTLP endpoint; passing `-Dtelemetry-endpoint=""` disables it. (`build.zig:26-37`)
-
-### 3) CLI tests, formatting, and CI checks
-
-**Unit tests:**
-
-```sh
-zig build test
-zig build test --summary all
-```
-
-- `build.zig` defines a `test` step using `src/main.zig` as the test root. (`build.zig:58-69`)
-- CI runs `zig build test --summary all`. (`.github/workflows/ci.yml:45-46`)
-- README documents `zig build test` as the test suite. (`README.md:697-699`)
-
-**Formatting/lint-equivalent for Zig:**
-
-```sh
-zig fmt --check src/main.zig src/mcp.zig build.zig
-```
-
-- CI enforces that exact `zig fmt --check` command. (`.github/workflows/ci.yml:42-43`)
-
-**Protocol/JSON control test:**
-
-```sh
-python3 scripts/test-json-controls.py zig-out/bin/graff
-```
-
-- CI runs that exact command after building `graff`. (`.github/workflows/ci.yml:48-49`)
-
-**SDK drift check:**
-
-```sh
-python3 sdk/generate.py --harness ./zig-out/bin/graff
-git diff --exit-code sdk/
-```
-
-- CI regenerates SDKs with the built binary and fails if `sdk/` changes. (`.github/workflows/ci.yml:51-55`)
-
-**CI toolchain assumption:**
-
-- CI pins Zig to `0.16.0`. (`.github/workflows/ci.yml:34-37`)
-- The installer also says the harness needs Zig 0.16 and warns on other versions. (`install.sh:41-51`)
-
-### 4) CLI install flow and environment overrides
-
-**Install latest release / fallback to source:**
-
-```sh
-curl -fsSL https://github.com/justrach/codegraff/releases/latest/download/install.sh | sh
-# or from checkout:
-./install.sh
-```
-
-- README documents the release installer command. (`README.md:56-64`)
-- README says from a checkout run `./install.sh`, installing to `~/bin` by default, overridable by `HARNESS_DIR`. (`README.md:66-67`)
-- `install.sh` defaults `HARNESS_REPO` to `https://github.com/justrach/codegraff`, `HARNESS_DIR` to `$HOME/bin`, and binary name to `graff`. (`install.sh:11-16`)
-- `HARNESS_BUILD=source` skips release download and forces source build. (`install.sh:11-12`, `install.sh:171-175`)
-- Source install runs:
-
-```sh
-zig build -Doptimize=ReleaseFast
-```
-
- (`install.sh:149-152`)
-
-- The installer creates a compatibility symlink from `harness` to `graff`. (`install.sh:179-181`)
-- Optional companion suite install can be skipped with `HARNESS_NO_GRAFF=1`; optional `kuri` install is enabled with `HARNESS_WITH_KURI=1`. (`install.sh:183-207`, `install.sh:209-224`)
-
-### 5) CLI runtime credentials/config assumptions
-
-- API keys can be supplied by login, key storage, or environment variables; examples include `graff login`, `graff key set deepseek sk-...`, and `export DEEPSEEK_API_KEY=sk-...`. (`README.md:74-82`)
-- Provider environment variables documented include `ANTHROPIC_API_KEY`, `CODEGRAFF_API_KEY`, `DEEPSEEK_API_KEY`, `OPENAI_API_KEY`, `MINIMAX_API_KEY`, `XIAOMI_API_KEY`, `KIMI_API_KEY`, `XAI_API_KEY`, and `ZAI_API_KEY`; Codex uses `~/.codex/auth.json`. (`README.md:219-228`)
-- Stored keys live in macOS Keychain using service `simple-harness`; elsewhere in `0600` `~/.simple-harness-keys.json`; environment variables win. (`README.md:712-716`)
-- `graff login` writes the Codegraff device-flow key to `~/.simple-harness-codegraff.json`; `graff login codex` writes `~/.codex/auth.json`. (`README.md:721-727`)
-
-### 6) Telemetry/tracing assumptions
-
-- The CLI writes `harness.trace.jsonl` in the current working directory when tracing is enabled, truncating it at startup for the current session. (`README.md:644-650`)
-- Release telemetry can be opted out with `--no-telemetry` or `GRAFF_NO_TELEMETRY=1`; env endpoints `OTEL_EXPORTER_OTLP_ENDPOINT` or `GRAFF_OTEL_ENDPOINT` override the default. (`README.md:652-659`)
-- **Important verified discrepancy:** `build.zig` currently bakes the telemetry endpoint by default for “release, source-install, and dev” builds unless `-Dtelemetry-endpoint=""` is passed. (`build.zig:26-37`) README says “Builds from source have no endpoint baked in” unless an env endpoint is set. (`README.md:656-659`) Those two statements conflict.
-
-### 7) GUI / frontend build, dev, test, lint
-
-The GUI package scripts are:
-
-```sh
-cd gui
-bun run dev
-bun run build
-bun run lint
-bun run preview
-bun run tauri
-bun test
-```
-
-- `dev` runs `bun run build:deps && vite`. (`gui/package.json:8-10`)
-- `build:deps` runs `bun run --filter '@codegraff/diffs' build`. (`gui/package.json:10-12`)
-- `build` runs `bun run build:deps && bun run gen:desktop-contracts && tsc -b && vite build`. (`gui/package.json:12`)
-- `lint` runs `bun run build:deps && bun run gen:desktop-contracts && eslint .`. (`gui/package.json:13`)
-- `test` runs `bun test`. (`gui/package.json:16`)
-- `preview` runs `vite preview`; `tauri` delegates to the Tauri CLI. (`gui/package.json:14-15`)
-
-**Desktop contract generation:**
-
-```sh
-cd gui
-bun run gen:desktop-contracts
-```
-
-- This runs:
-
-```sh
-cargo run --quiet --manifest-path src-tauri/Cargo.toml --example generate_desktop_contracts
-```
-
- (`gui/package.json:10`)
-
-**Vite config:**
-
-- Vite uses Tailwind, React, and Babel with React Compiler preset. (`gui/vite.config.ts:8-15`)
-- Vite aliases `@` to `gui/src`. (`gui/vite.config.ts:16-20`)
-
-**TypeScript config:**
-
-- `tsc -b` builds references to `tsconfig.app.json` and `tsconfig.node.json`. (`gui/tsconfig.json:9-13`)
-- App TS target is `es2023`, module `esnext`, bundler resolution, React JSX, `noEmit`, `noUnusedLocals`, `noUnusedParameters`, `erasableSyntaxOnly`, and `noFallthroughCasesInSwitch`. (`gui/tsconfig.app.json:2-29`)
-- Node TS config includes only `vite.config.ts`. (`gui/tsconfig.node.json:17-23`)
-
-**ESLint config:**
-
-- ESLint ignores `dist`, `vendor/**`, `src-tauri/gen/**`, and `src-tauri/target/**`. (`gui/eslint.config.js:8-14`)
-- It applies to `**/*.{ts,tsx}` and extends JS recommended, TypeScript recommended, React Hooks latest, and React Refresh Vite configs. (`gui/eslint.config.js:15-22`)
-- It enforces `react-refresh/only-export-components`, allowing constant exports and `useSidebar`. (`gui/eslint.config.js:27-34`)
-
-### 8) GUI / Tauri run and package flow
-
-Likely commands:
-
-```sh
-cd gui
-bun run tauri dev
-bun run tauri build
-```
-
-Evidence:
-
-- `gui/package.json` exposes `"tauri": "tauri"`. (`gui/package.json:14-15`)
-- Tauri config says dev uses `devUrl` `http://localhost:5173`, and `beforeDevCommand` is `bun run dev`. (`gui/src-tauri/tauri.conf.json:6-10`)
-- Tauri config says packaged frontend is `../dist`, and `beforeBuildCommand` is `bun run build`. (`gui/src-tauri/tauri.conf.json:6-10`)
-- The bundle includes external binary `binaries/graff`, targets all bundle formats, and has macOS signing identity `Developer ID Application: Rachit Pradhan (WWP9DLJ27P)` with hardened runtime enabled. (`gui/src-tauri/tauri.conf.json:35-49`)
-
-**Tauri/Rust assumptions:**
-
-- The Rust crate is its own workspace root; the empty `[workspace]` prevents Cargo from walking up to a parent workspace. (`gui/src-tauri/Cargo.toml:1-5`)
-- Rust package is `codegraff-gui` version `0.0.13`, edition `2024`, and requires Rust `1.92`. (`gui/src-tauri/Cargo.toml:7-16`)
-- It uses Tauri `2.10.3` with `macos-private-api`. (`gui/src-tauri/Cargo.toml:39`)
-- Tauri app identifier is `dev.codegraff.gui`; product name is `Codegraff`. (`gui/src-tauri/tauri.conf.json:1-5`)
-
-**GUI runtime engine discovery:**
-
-- The GUI spawns `graff --json --yolo --resume <conversation_id>`, optionally `--model <model>`, in the workspace directory. (`gui/src-tauri/src/runtime/simple.rs:2626-2649`)
-- The GUI passes a login-shell environment into the spawned `graff`, explicitly to make shell-exported provider keys visible to GUI launches. (`gui/src-tauri/src/runtime/simple.rs:2641-2647`)
-- That login-shell env is collected by running `$SHELL -ilc env`, defaulting `SHELL` to `/bin/zsh`, with a 4-second timeout. (`gui/src-tauri/src/runtime/simple.rs:2588-2613`)
-- The GUI binary lookup order is: `CODEGRAFF_GUI_BINARY`, bundled sidecar next to current executable, `../../zig-out/bin/graff`, known install locations like `~/bin/graff`, `/opt/homebrew/bin/graff`, `/usr/local/bin/graff`, then bare `graff` on inherited `PATH`. (`gui/src-tauri/src/runtime/simple.rs:3240-3300`)
-- If spawning fails, the GUI error tells the user to install the CLI or set `CODEGRAFF_GUI_BINARY`. (`gui/src-tauri/src/runtime/simple.rs:2652-2657`)
-
-**Tauri debug bridge:**
-
-- In debug builds only, the app starts `debug_bridge::DebugBridge`. (`gui/src-tauri/src/lib.rs:92-97`)
-- The `scripts/tdev` helper talks to that dev-only bridge at `http://127.0.0.1:9233`. (`scripts/tdev:1-7`, `scripts/tdev:26`)
-- `scripts/tdev` supports `health`, `eval`, `shot`, `click`, `type`, and `key`. (`scripts/tdev:9-15`, `scripts/tdev:37-75`)
-
-### 9) Rust/Tauri tests
-
-Verified but not wired into package scripts/CI:
-
-- `gui/src-tauri/src/runtime/simple.rs` contains Rust `#[test]` declarations under a tests module. (`gui/src-tauri/src/runtime/simple.rs:4001-4259`)
-- `gui/src-tauri/Cargo.toml` has `pretty_assertions` as a dev dependency. (`gui/src-tauri/Cargo.toml:54-56`)
-
-**Inferred exact command:**
-
-```sh
-cargo test --manifest-path gui/src-tauri/Cargo.toml
-```
-
-This command is not found in CI or package scripts; it is inferred from the Cargo manifest and Rust tests.
-
-### 10) Shared diff package build/test
-
-```sh
-cd packages/diffs
-bun run build
-bun test
-```
-
-- `@codegraff/diffs` build script is `tsc -p tsconfig.build.json`. (`packages/diffs/package.json:23-25`)
-- Its test script is `bun test`. (`packages/diffs/package.json:23-26`)
-- Its build emits declarations, declaration maps, source maps, and JS into `dist` from `src`, excluding `test`. (`packages/diffs/tsconfig.build.json:1-14`)
-- Its TS config is strict, targets ES2022, uses bundler module resolution, React JSX, and `bun-types`. (`packages/diffs/tsconfig.json:2-16`)
-
-### 11) SDK generation, validation, and publishing
-
-**Regenerate SDKs locally:**
-
-```sh
-python3 sdk/generate.py --harness ./zig-out/bin/graff
-# or
-graff --schema | python3 sdk/generate.py
-```
-
-- SDK README documents both commands. (`sdk/README.md:13-18`)
-- `sdk/generate.py` accepts `--schema`, `--harness`, or stdin; `--harness` runs `<binary> --schema`. (`sdk/generate.py:22-32`)
-- SDKs are auto-generated and should not be hand-edited. (`sdk/README.md:1-5`)
-
-**CI SDK validation:**
-
-- Python smoke test imports `sdk/py/harness_sdk.py` and asserts `MODELS` and `TOOLS`. (`.github/workflows/ci.yml:15-16`)
-- TS validation parses `sdk/ts/package.json` and uses Node’s experimental type stripping to import `sdk/ts/harness.ts`, checking `Harness`, `runAgent`, and `MODELS`. (`.github/workflows/ci.yml:18-25`)
-
-**SDK package metadata:**
-
-- Python SDK package is `codegraff`, version `0.3.1`, requires Python `>=3.8`, and uses setuptools. (`sdk/py/pyproject.toml:1-20`)
-- TypeScript SDK package is `@codegraff/sdk`, version `0.3.1`, exports `harness.ts` and `remote.ts`, and requires Node `>=18`. (`sdk/ts/package.json:1-31`)
-
-**Publish flow:**
-
-- SDK publishing triggers on tags matching `sdk-v*`. (`.github/workflows/sdk.yml:6-8`)
-- PyPI build uses Python `3.12`, rewrites `pyproject.toml` version from the tag, installs `build`, and runs `python3 -m build`. (`.github/workflows/sdk.yml:20-30`)
-- npm publish uses Node `24`, updates package version from the tag, and runs `npm publish --access public`. (`.github/workflows/sdk.yml:35-44`)
-
-### 12) Remote / edge example
-
-**Local edge-worker smoke flow:**
-
-```sh
-harness serve --port 8926 --token edge-test
-npx wrangler dev --port 8970
-curl http://127.0.0.1:8970
-curl -N 'http://127.0.0.1:8970/?q=run:%20echo%20hi'
-```
-
-- The edge-worker README documents those commands. (`examples/edge-worker/README.md:8-13`)
-- `wrangler.toml` also documents the bridge and `wrangler dev` local check. (`examples/edge-worker/wrangler.toml:1-5`)
-- Worker config sets `name = "harness-edge-worker"`, `main = "src/index.ts"`, compatibility date `2026-04-01`, and `BRIDGE_URL = "http://127.0.0.1:8926"`. (`examples/edge-worker/wrangler.toml:8-14`)
-- For real deploy, the docs say front the bridge with TLS and store the token using `npx wrangler secret put BRIDGE_TOKEN`. (`examples/edge-worker/README.md:20-22`)
-
-## Inferred / not directly wired
-
-- `cd gui && bun run tauri dev` and `cd gui && bun run tauri build` are the likely desktop dev/package commands because the GUI exposes `"tauri": "tauri"` and Tauri config defines `beforeDevCommand`/`beforeBuildCommand`; I did not find these exact commands in CI. (`gui/package.json:14-15`, `gui/src-tauri/tauri.conf.json:6-10`)
-- `cargo test --manifest-path gui/src-tauri/Cargo.toml` is the likely Rust/Tauri unit-test command because Rust tests and dev-dependencies exist, but it is not wired into the package scripts or GitHub Actions I inspected. (`gui/src-tauri/src/runtime/simple.rs:4001-4259`, `gui/src-tauri/Cargo.toml:54-56`)
-- Dependency install is likely `bun install` at the repo root because the root package declares Bun workspaces and pins Bun, but there is no explicit install script. (`package.json:1-9`)
-
-## 3 most load-bearing facts
-
-1. **The authoritative CI path for the CLI is Zig 0.16.0 with `zig build`, `zig fmt --check src/main.zig src/mcp.zig build.zig`, `zig build test --summary all`, JSON protocol test, and SDK drift check.** (`.github/workflows/ci.yml:27-55`)
-2. **The GUI build pipeline is `bun run build:deps && bun run gen:desktop-contracts && tsc -b && vite build`; lint runs the same presteps then `eslint .`; tests are `bun test`.** (`gui/package.json:8-17`)
-3. **The desktop app depends on finding a usable `graff` binary, with `CODEGRAFF_GUI_BINARY` as the first override and bundled/installed/dev locations as fallbacks.** (`gui/src-tauri/src/runtime/simple.rs:3240-3300`)
-
-## Open question
-
-- **Which telemetry behavior is intended for source/dev builds?** `build.zig` says every build gets the default endpoint unless disabled with `-Dtelemetry-endpoint=""`, while README says source builds have no endpoint baked in unless env vars are set. (`build.zig:26-37`, `README.md:656-659`)
-
-[subagent sa-002-e9970bea · inspect: .graff/subagents/sa-002-e9970bea.md]
-
-### feature inventory
-## Verified inventory of main product features / user-facing flows
-
-### 1. Core product: `graff` agent harness (CLI/REPL + one-shot + JSON protocol)
-- The repository’s primary CLI is `graff`, described as a minimal agentic coding harness that talks to Anthropic, OpenAI-compatible endpoints, and ChatGPT/Codex subscription credentials. `README.md:1-6`
-- The harness loop sends user text to a model, executes model-requested tools in parallel, feeds results back, and repeats until the model stops. `README.md:17-28`
-- User-facing install/run flows include `graff`, `graff --model ...`, `graff -p "prompt"` one-shot mode, login/key management, `--schema`, and JSON protocol mode. `README.md:279-300`
-- The REPL exposes slash commands such as `/model`, `/plan`, `/key`, `/reasoning`, `/compact`, `/save`, `/resume`, `/todo`, `/mcp`, and `/help`. `README.md:317-346`
-- The harness supports permission-gated tools (`bash`, file reads/writes/edits, MCP tools), plus modes such as `yolo`, `plan`, and `strict`. `README.md:364-398`
-- The harness supports subagents and workflow fan-out, including an “ultracode” codeword that steers work into multi-agent workflow mode. `README.md:541-560`
-
-### 2. Desktop GUI / Codegraff app shell
-- The desktop app is a Tauri GUI over the `graff` agent CLI; README says the macOS desktop app installs a `codegraff` launcher and runs whatever `graff` is on `PATH`. `README.md:46-51`
-- The React app boots through `SessionProvider`, `DragDropProvider`, and `AppShell`; `/success` is a special route for provider OAuth success UI. `gui/src/app/App.tsx:385-395`
-- `AppShell` renders a resizable sidebar + content area, global theme toggle, sidebar toggle, new-chat trigger, settings panes, and the main `WorkspaceBoard`. `gui/src/app/App.tsx:265-379`
-- The global Cmd/Ctrl+N shortcut calls the same `NewChatTrigger` flow as the button. `gui/src/app/App.tsx:235-250`
-- The content switches between settings (`ProvidersSettingsPane`, `McpSettingsPane`, `GeneralSettingsPane`) and the workspace/chat board. `gui/src/app/App.tsx:359-375`
-
-### 3. Session bootstrap, state, and live updates
-- `SessionProvider` calls `useSessionBootstrap`, persists the latest active workspace path in local storage, and exposes session actions through context. `gui/src/app/SessionProvider.tsx:89-103`, `gui/src/app/SessionProvider.tsx:651-655`
-- `useSessionBootstrap` subscribes to backend session-update events, gets an initial snapshot, tries to reopen the latest workspace, then falls back to creating a managed chat. `gui/src/hooks/useSessionBootstrap.ts:28-88`
-- Cold-start and single-instance `codegraff <path>` flows are wired through `drainPendingOpen` and `open-workspace-path`; `SessionProvider` opens either pending or forwarded paths. `gui/src/app/SessionProvider.tsx:151-178`
-- The Tauri backend stores cold-start CLI args in `PendingOpen`, emits `open-workspace-path` for second instances, and focuses the main window. `gui/src-tauri/src/lib.rs:53-63`, `gui/src-tauri/src/lib.rs:86-89`, `gui/src-tauri/src/lib.rs:197-200`
-
-### 4. Sidebar flows: saved workspaces, managed chats, projects, settings
-- `ProjectSidebar` has sections for saved “Workspaces”, standalone “Chats” / managed chats, and “Projects”. `gui/src/components/ProjectSidebar.tsx:244-423`
-- Sidebar actions include opening a project folder, selecting chats, opening saved workspaces, starting new chats, archiving conversations/workspaces, and renaming/deleting saved workspaces. `gui/src/components/ProjectSidebar.tsx:74-85`, `gui/src/components/ProjectSidebar.tsx:103-148`
-- In settings mode, the sidebar becomes a settings navigator with General, Providers, and MCP sections. `gui/src/components/ProjectSidebar.tsx:150-225`
-
-### 5. New chat / onboarding / project setup
-- `NewChatScreen` is the empty or draft conversation surface; it wires onboarding, provider setup, clone-repository dialog, quick-start project dialog, launch actions, and a prompt section. `gui/src/components/new-chat-screen/NewChatScreen.tsx:81-143`, `gui/src/components/new-chat-screen/NewChatScreen.tsx:259-303`
-- The onboarding panel appears when there are no command results and setup is incomplete, based on provider/workspace state. `gui/src/components/new-chat-screen/NewChatScreen.tsx:192-200`
-- Project setup supports “open folder”, “clone repository”, and “quick start” flows; the controller calls `pickDirectory`, `cloneRepository`, `quickStartProject`, and `openProject`. `gui/src/components/new-chat-screen/hooks/useNewChatScreenController.ts:149-190`, `gui/src/components/new-chat-screen/hooks/useNewChatScreenController.ts:197-251`
-- Backend clone runs `git clone`; backend quick-start runs `gh repo create --clone --add-readme`, validates names, and returns the created directory path. `gui/src-tauri/src/commands.rs:839-884`, `gui/src-tauri/src/commands.rs:913-936`
-
-### 6. Conversation/chat flow
-- `ConversationPanel` chooses between `NewChatScreen`, a loading spinner, or the active chat thread + prompt composer. `gui/src/components/ConversationPanel.tsx:65-79`, `gui/src/components/ConversationPanel.tsx:93-127`
-- The chat display uses `ChatThread` for messages and local command results, while `PromptComposer` handles followups, goal chips, plan/interrupt prompts, todos, and the prompt input. `gui/src/components/ConversationPanel.tsx:112-126`, `gui/src/components/PromptComposer.tsx:167-234`
-- Existing chats and bound chat tiles submit prompts through `useConversationActions`; it appends file/image attachments into the prompt, supports Ultra mode injection, clears composer state, calls `desktopClient.sendPrompt`, and applies the returned snapshot. `gui/src/hooks/useConversationActions.ts:91-135`
-- Draft/new-chat submission in `SessionProvider` does the same first-message flow, selecting agent `muse` for planning mode or `forge` otherwise. `gui/src/app/SessionProvider.tsx:563-627`
-
-### 7. Prompt composer capabilities
-- The prompt card supports slash-command autocomplete, model picker, reasoning-effort picker, Plan mode, Fast mode, Ultra mode, stop/send behavior, prompt history navigation, drag-drop attachments, and pasted image attachments. `gui/src/components/PromptInputCard.tsx:93-181`, `gui/src/components/PromptInputCard.tsx:199-327`, `gui/src/components/PromptInputCard.tsx:329-621`
-- Pasted images are persisted through the Tauri `save_pasted_image` command, then classified as attachments. `gui/src/components/PromptInputCard.tsx:298-325`, `gui/src-tauri/src/commands.rs:252-269`
-- Image thumbnails are generated by a backend `image_thumbnail` command that decodes/downscales/re-encodes images as JPEG data URLs. `gui/src-tauri/src/commands.rs:271-292`
-
-### 8. Slash command flow
-- The prompt composer first tries to route a draft as a slash command before sending it as a normal prompt. `gui/src/components/PromptComposer.tsx:73-78`
-- `useCommandRouter` parses `/command args`, handles local UI commands such as plan/act, new chat, provider settings, MCP settings, delete/archive, compact, and routes other commands to `desktopClient.runSlashCommand`. `gui/src/hooks/useCommandRouter.ts:36-47`, `gui/src/hooks/useCommandRouter.ts:89-117`, `gui/src/hooks/useCommandRouter.ts:120-181`
-- Commands needing free-form arguments are completed into the draft instead of immediately run. `gui/src/hooks/useCommandRouter.ts:15-25`, `gui/src/hooks/useCommandRouter.ts:184-217`
-- Backend command inventory currently includes `/help`, `/agent`, `/goal`, `/loop`, `/bash`, `/compact`, `/workspace-status`, and `/ultracode`. `gui/src-tauri/src/runtime/simple.rs:450-465`
-- Backend command execution handles agent status, persistent ultracode toggle, goal get/set/clear, autonomous `/loop`, conversation compaction, shell `/bash`, and workspace git status payloads. `gui/src-tauri/src/runtime/simple.rs:1236-1428`
-
-### 9. Backend prompt execution / streaming
-- Tauri command `send_prompt` forwards frontend prompt submissions to `DesktopState.manager.send_prompt`. `gui/src-tauri/src/commands.rs:155-165`
-- `RuntimeManager.send_prompt` creates or selects a conversation, appends the user message, queues prompts if a request is already active, emits a snapshot, optionally auto-generates a title, and then streams the turn. `gui/src-tauri/src/runtime/simple.rs:470-688`
-- `stream_turn` writes a JSON user line into a long-lived `graff` session, then maps streamed events into GUI message types: assistant text, reasoning, tool starts/results, followup requests, errors, and turn completion. `gui/src-tauri/src/runtime/simple.rs:692-1005`
-- Runtime snapshots include active workspace/conversation, visible messages, active request IDs, todos, goal, followup, all conversation views, registered workspaces, and saved workspaces. `gui/src-tauri/src/runtime/simple.rs:2093-2215`
-
-### 10. Workspace board / multi-chat layout
-- `WorkspaceBoard` is a Dockview-based board that renders empty state, workspace draft, single chat, or saved-workspace multi-chat layouts. `gui/src/components/workspace-board/WorkspaceBoard.tsx:51-104`, `gui/src/components/workspace-board/WorkspaceBoard.tsx:538-586`
-- Dragging/adding a second chat converts a single-chat selection into a saved workspace by serializing Dockview layout and calling `createSavedWorkspace`. `gui/src/components/workspace-board/WorkspaceBoard.tsx:313-388`
-- Saved workspace layouts are restored from saved JSON and persisted on layout changes. `gui/src/components/workspace-board/WorkspaceBoard.tsx:63-83`, `gui/src/components/workspace-board/WorkspaceBoard.tsx:238-302`, `gui/src/components/workspace-board/WorkspaceBoard.tsx:439-481`
-- `ChatTile` is the inner Dockview layout for one chat; it hosts the conversation pane plus auxiliary preview, terminal, and changes panes. `gui/src/components/workspace-board/ChatTile.tsx:495-540`, `gui/src/components/workspace-board/ChatTile.tsx:729-781`
-- Per-conversation layout is saved and restored with `saveConversationLayout` / `getConversationLayout`. `gui/src/components/workspace-board/ChatTile.tsx:147-162`, `gui/src/components/workspace-board/ChatTile.tsx:572-608`
-
-### 11. Changes/diff/git flow
-- The Changes pane derives file changes from conversation messages, resolves renderable diffs, shows additions/deletions, lets files open in an editor, and shows commit/push actions when git actions are available. `gui/src/components/workspace-board/ChangesPane.tsx:199-246`, `gui/src/components/workspace-board/ChangesPane.tsx:248-349`
-- Git actions in session context include checkout branch, create branch, commit, push, and open workspace in a target app. `gui/src/app/SessionProvider.tsx:180-228`, `gui/src/app/SessionProvider.tsx:376-385`
-- Backend git commands route through `RuntimeManager` for checkout/create/commit/push. `gui/src-tauri/src/commands.rs:536-582`
-
-### 12. Terminal pane flow
-- `ChatTile` can open/close terminal panes, add terminal tabs, restart terminals, and confirm destructive closing of multiple terminals. `gui/src/components/workspace-board/ChatTile.tsx:343-385`, `gui/src/components/workspace-board/ChatTile.tsx:451-481`, `gui/src/components/workspace-board/ChatTile.tsx:746-779`
-- `useTerminalSession` creates a `WTerm`, subscribes to backend terminal output/exit/error events, opens a backend terminal, writes user input, resizes backend PTY size, and closes the backend terminal on cleanup. `gui/src/components/workspace-board/hooks/useTerminalSession.ts:148-235`, `gui/src/components/workspace-board/hooks/useTerminalSession.ts:253-272`
-- Tauri terminal API commands route to `state.terminal_manager.open/write/resize/close`. `gui/src-tauri/src/commands.rs:781-827`
-
-### 13. Provider setup/settings flow
-- Providers settings lists/searches providers, shows configured/unconfigured state, opens setup dialogs, removes configured providers, and refreshes prompt settings after changes. `gui/src/components/providers-settings/ProvidersSettingsPane.tsx:62-132`, `gui/src/components/providers-settings/ProvidersSettingsPane.tsx:134-328`
-- Provider setup supports multiple auth kinds: API key, device code, CLI login, and OAuth authorization code. `gui/src/components/providers-settings/ProviderSetupDialog.tsx:416-572`
-- Provider setup starts auth through `startProviderAuth`, completes through `completeProviderAuth`, listens for OAuth callbacks, and auto-polls CLI login completion via `listProviders`. `gui/src/components/providers-settings/ProviderSetupDialog.tsx:128-165`, `gui/src/components/providers-settings/ProviderSetupDialog.tsx:167-207`, `gui/src/components/providers-settings/ProviderSetupDialog.tsx:209-276`, `gui/src/components/providers-settings/ProviderSetupDialog.tsx:304-330`
-- Backend provider APIs are registered in Tauri and route to `RuntimeManager` methods. `gui/src-tauri/src/lib.rs:116-144`, `gui/src-tauri/src/commands.rs:95-141`
-
-### 14. MCP settings flow
-- MCP settings lists servers, reloads, imports JSON config, removes servers, and triggers login/logout when auth status is present. `gui/src/components/mcp-settings/McpSettingsPane.tsx:35-94`, `gui/src/components/mcp-settings/McpSettingsPane.tsx:96-275`
-- MCP backend commands are exposed through the desktop client (`listMcpServers`, `importMcpConfig`, `removeMcpServer`, `reloadMcpServers`, `loginMcpServer`, `logoutMcpServer`). `gui/src/services/desktop/client.ts:529-567`
-- Tauri routes these MCP commands to `RuntimeManager` methods. `gui/src-tauri/src/commands.rs:307-377`
-
-### 15. General settings / theme flow
-- General settings currently covers appearance mode and theme preset selection, persisted through `themeStore`. `gui/src/components/general-settings/GeneralSettingsPane.tsx:18-82`
-- The app-level theme toggle is also exposed in the shell. `gui/src/app/App.tsx:51-77`, `gui/src/app/App.tsx:269-272`
-
-### 16. Desktop API boundary / route map
-- The frontend desktop API boundary is `gui/src/services/desktop/client.ts`; all production calls go through `invokeCommand`, with QA mock mode swapping Tauri invocations for deterministic browser fixtures. `gui/src/services/desktop/client.ts:56-60`, `gui/src/services/desktop/client.ts:266-319`
-- Frontend API functions map directly to Tauri command names for workspace/session/chat, slash commands, prompt settings, providers, MCP, git, external open/read-file, layouts, saved workspaces, and terminal operations. `gui/src/services/desktop/client.ts:338-802`
-- Tauri registers the command surface with `tauri::generate_handler!`, covering the same product areas. `gui/src-tauri/src/lib.rs:108-174`
-- Most Tauri command handlers are thin adapters that call `DesktopState.manager`; terminal handlers call `DesktopState.terminal_manager`; clone/quick-start and file/image helpers are implemented directly in `commands.rs`. `gui/src-tauri/src/commands.rs:48-827`
-
-### 17. SDK / remote API product surface
-- The repo includes generated TypeScript and Python SDKs over `graff --json`; README says `graff --schema` is the machine-readable interface used to generate SDKs. `README.md:402-411`
-- SDK examples include Python `Harness` and TypeScript `Harness` / `runAgent`, with streamed event handling. `README.md:413-437`
-- Remote clients exist for `graff serve`, including `@graff-new/sdk/remote` and Python `RemoteHarness`. `README.md:439-443`
-- The `serve` mode exposes the same protocol over HTTP for clients that cannot spawn a local process, with NDJSON streaming and bearer-token support for non-loopback use. `README.md:735-746`
-
-## Important components/services/routes and how they connect
-
-```text
-React UI
- App.tsx
- -> SessionProvider
- -> useSessionBootstrap
- -> desktopClient.listenSessionUpdates / getSessionSnapshot / createManagedChat
- -> ProjectSidebar
- -> useSessionActions
- -> desktopClient workspace/chat/saved-workspace APIs
- -> WorkspaceBoard
- -> Dockview layouts
- -> ChatTile
- -> ConversationPanel
- -> ChatThread + PromptComposer
- -> PromptInputCard
- -> useCommandRouter / useConversationActions
- -> desktopClient.sendPrompt / runSlashCommand / stopPrompt / settings APIs
- -> ChangesPane
- -> readWorkspaceFile/openPathInTarget/git actions
- -> TerminalPane/useTerminalSession
- -> terminal_open/write/resize/close + terminal events
- -> Settings panes
- -> ProvidersSettingsPane / ProviderSetupDialog
- -> McpSettingsPane
- -> GeneralSettingsPane
-
-desktopClient.ts
- -> Tauri invoke(command_name)
- -> Tauri event listen(session-updated, provider OAuth callback, terminal output/exit/error)
-
-Tauri Rust
- lib.rs generate_handler![...]
- -> commands.rs thin adapters
- -> runtime/simple.rs RuntimeManager for sessions, prompts, commands, providers, MCP, git, saved layouts
- -> terminal_manager for PTY sessions
- -> direct helpers for clone, quick-start, image/file helpers
-
-graff runtime
- RuntimeManager.spawn/acquire session
- -> JSON stdin/stdout protocol with graff child
- -> streams text/tool/followup/error events into SessionSnapshot
-```
-
-Evidence for the frontend-to-backend boundary: `desktopClient.invokeCommand` wraps Tauri `invoke`, and all exported client functions call named backend commands. `gui/src/services/desktop/client.ts:311-319`, `gui/src/services/desktop/client.ts:338-802`
-Evidence for Tauri route registration: `generate_handler!` registers the desktop command surface. `gui/src-tauri/src/lib.rs:108-174`
-Evidence for session/prompt backend routing: `commands.rs` forwards `send_prompt`, `run_slash_command`, and many app actions to `state.manager`. `gui/src-tauri/src/commands.rs:155-180`, `gui/src-tauri/src/commands.rs:415-582`
-
-## Inferred, but strongly supported
-
-- The GUI is the main user-facing desktop product layer, while the Zig `graff` harness remains the core agent engine; this is inferred from README’s statement that the desktop app runs `graff` from `PATH` and from the Tauri runtime streaming through a `graff` session. `README.md:46-51`, `gui/src-tauri/src/runtime/simple.rs:692-707`
-- Saved workspaces are a GUI construct for arranging multiple chat panels, not a core CLI concept; this is inferred from Dockview layout serialization and `ProjectStore` saved-workspace APIs being used by the GUI/Tauri layer. `gui/src/components/workspace-board/WorkspaceBoard.tsx:365-384`, `gui/src-tauri/src/runtime/simple.rs:2178-2188`
-- The product’s “agent workbench” direction combines chat, code changes, terminals, git, providers, MCP, and multi-agent workflows into one desktop surface; this is inferred from the connected GUI panes and backend APIs rather than from a single product statement. `gui/src/components/workspace-board/ChatTile.tsx:495-540`, `gui/src/components/workspace-board/ChangesPane.tsx:279-349`, `gui/src/components/workspace-board/hooks/useTerminalSession.ts:148-235`, `gui/src/components/providers-settings/ProvidersSettingsPane.tsx:134-328`, `gui/src/components/mcp-settings/McpSettingsPane.tsx:96-275`
-
-## 3 most load-bearing facts
-
-1. **All desktop user flows cross one typed bridge:** `desktopClient.ts` exports the frontend API and maps directly to Tauri command names, while `lib.rs` registers the matching backend handlers. `gui/src/services/desktop/client.ts:338-802`, `gui/src-tauri/src/lib.rs:108-174`
-2. **Conversation state is snapshot/event driven:** frontend bootstraps via `getSessionSnapshot` and `listenSessionUpdates`, while backend `RuntimeManager.snapshot` materializes workspaces, conversations, messages, todos, goals, followups, and saved workspaces. `gui/src/hooks/useSessionBootstrap.ts:28-88`, `gui/src-tauri/src/runtime/simple.rs:2093-2215`
-3. **The main GUI product flow is chat-centric but workspace-aware:** `WorkspaceBoard` organizes one or many `ChatTile`s, each tile embeds conversation, changes, terminal, and layout persistence. `gui/src/components/workspace-board/WorkspaceBoard.tsx:51-104`, `gui/src/components/workspace-board/WorkspaceBoard.tsx:313-388`, `gui/src/components/workspace-board/ChatTile.tsx:495-540`
-
-## Open question
-
-- Which layer should be considered the canonical “product” for roadmap/inventory purposes: the Zig CLI/SDK harness, the Tauri desktop app, or both as one combined Codegraff product? The README foregrounds the CLI harness while also documenting the desktop app as a major install path. `README.md:1-6`, `README.md:46-51`
-
-[subagent sa-001-546805fc · inspect: .graff/subagents/sa-001-546805fc.md]
-
-### risk hotspots
-## Defensible findings
-
-### 1) Unauthenticated localhost debug bridge can execute arbitrary JS in the Tauri webview
-**File:** `gui/src-tauri/src/debug_bridge.rs:91`, `gui/src-tauri/src/debug_bridge.rs:137`, `gui/src-tauri/src/debug_bridge.rs:188`, `gui/src-tauri/src/debug_bridge.rs:291`
-**Rationale:** In debug builds, the app starts an HTTP server on `127.0.0.1:9233` with no token/origin check. `POST /eval` accepts arbitrary `code`, interpolates it raw into a JS snippet, and evaluates it in the main Tauri webview. Responses include `Access-Control-Allow-Origin: *`.
-
-**Breaking sequence:**
-1. Developer runs a debug build of the GUI.
-2. Attacker-controlled web page or local process sends `POST http://127.0.0.1:9233/eval` with body like `{"code":"window.__TAURI_INTERNALS__.invoke('open_external_url',{url:'https://attacker.example'})"}` or code that drives privileged app APIs exposed to the webview.
-3. `handle_eval` embeds the supplied code at line 188 and calls `window.eval` at line 200.
-4. The attacker’s code runs inside the desktop app context.
-
-**Impact:** Localhost RCE-equivalent inside the debug app context. Debug-only reduces production risk, but it is still dangerous for developers because a browser page can target localhost services.
-
----
-
-### 2) MCP requests can hang forever on a silent/broken server
-**File:** `src/mcp.zig:410`–`src/mcp.zig:428`
-**Rationale:** `request()` writes a JSON-RPC request, then loops on `takeDelimiter('\n')` until it sees a matching `id`. There is no timeout, cancellation, or child liveness check beyond EOF.
-
-**Breaking sequence:**
-1. Workspace contains `.mcp.json` with a server like:
- ```json
- {
- "mcpServers": {
- "bad": { "command": "sleep", "args": ["999999"] }
- }
- }
- ```
-2. Registry startup calls `startServer()`.
-3. `startServer()` calls `request(..., "initialize")` at `src/mcp.zig:286`.
-4. `request()` blocks forever at `src/mcp.zig:422` because the process never writes a newline-delimited response.
-5. Startup or `/mcp trust` never completes.
-
-**Impact:** A malformed or hostile workspace MCP config can wedge the harness/GUI integration. This needs a request timeout and process cleanup path.
-
----
-
-### 3) Malformed `.mcp.json` can crash instead of failing closed
-**File:** `src/mcp.zig:103`, `src/mcp.zig:111`, `src/mcp.zig:250`
-**Rationale:** Several JSON values are accessed as `.object` or `.string` without checking the active union tag.
-
-**Breaking sequences:**
-- If `.mcp.json` contains:
- ```json
- { "mcpServers": [] }
- ```
- then `parsed.object.get("mcpServers").object` at `src/mcp.zig:103` accesses `.object` on an array value.
-
-- If `.mcp.json` contains:
- ```json
- { "mcpServers": { "x": [] } }
- ```
- then `entry.value_ptr.*.object` at `src/mcp.zig:111` accesses `.object` on an array value.
-
-- If `.mcp.json` contains:
- ```json
- {
- "mcpServers": {
- "x": {
- "command": "node",
- "env": { "TOKEN": 123 }
- }
- }
- }
- ```
- then `e.value_ptr.*.string` at `src/mcp.zig:250` accesses `.string` on an integer value.
-
-**Impact:** In safe builds this is a runtime panic; in unsafe/optimized contexts it risks undefined behavior. Workspace config is user-/repo-controlled, so this should be validated defensively and covered by malformed-config tests.
-
----
-
-### 4) Predictable temp-file writes can follow attacker-created symlinks
-**File:** `gui/src-tauri/src/commands.rs:264`–`gui/src-tauri/src/commands.rs:267`
-**Rationale:** `save_pasted_image` writes to a predictable path under the shared temp directory: `codegraff-pasted/paste-<pid>-<counter>.<ext>`. It uses `std::fs::write`, which follows symlinks.
-
-**Breaking sequence:**
-1. Local attacker creates `/tmp/codegraff-pasted` if it does not already exist and makes it writable.
-2. Attacker predicts or observes the GUI PID and creates a symlink such as:
- ```sh
- ln -s "$HOME/.zshrc" "/tmp/codegraff-pasted/paste-12345-0.png"
- ```
-3. User pastes an image into the GUI.
-4. `save_pasted_image` writes bytes to the symlink target at line 267.
-
-**Impact:** Local same-user or same-machine file clobber. Use a private `tempfile`/`NamedTempFile`-style creation with `O_EXCL` and a per-user 0700 directory.
-
----
-
-### 5) The debug screenshot endpoint uses a fixed temp filename
-**File:** `gui/src-tauri/src/debug_bridge.rs:249`–`gui/src-tauri/src/debug_bridge.rs:259`
-**Rationale:** `capture_screenshot` always writes the full-screen capture to `std::env::temp_dir().join("cg_debug_full.png")`.
-
-**Breaking sequence:**
-1. A local attacker pre-creates `/tmp/cg_debug_full.png` as a symlink to another writable user file.
-2. Developer calls `GET http://127.0.0.1:9233/screenshot` while running a debug build.
-3. `screencapture -x /tmp/cg_debug_full.png` writes through the symlink or overwrites the predictable file.
-
-**Impact:** Local file clobber in debug builds, plus stale/racy screenshots when multiple app instances or requests run. Use a securely created unique temp file and delete it.
-
----
-
-## Complexity hotspots / likely maintenance risks
-
-- **`gui/src-tauri/src/runtime/simple.rs` — 4,499 lines.** This file owns runtime state, provider auth, model selection, MCP config, persistence, child-process sessions, git commands, and tests. The most failure-prone areas are:
- - session lifecycle / queued prompts: `send_prompt`, `stream_turn`, `send_control`, `acquire_session_io`;
- - provider credential detection and env bootstrapping;
- - persistence with best-effort ignored errors.
-- **`gui/src/app/sessionStore.ts` — 924 lines.** Central client-side state with selection, drafts, attachments, request timing, view caching, and async request de-duplication. Race-prone; needs broad regression coverage.
-- **`gui/src-tauri/src/commands.rs` — 959 lines.** Large Tauri command surface; security-sensitive functions live next to ordinary UI glue.
-- **`gui/src/services/desktop/client.ts` — 802 lines.** Contains both real Tauri client and QA mock mode. Risk: mock drift from generated contracts.
-- **`gui/src/components/providers-settings/ProviderSetupDialog.tsx` — 697 lines.** Complex provider auth state machine; likely needs more integration tests around failure/retry/cancel.
-- **`src/mcp.zig` — MCP stdio client.** Small enough to reason about but currently has the most concrete robustness issues: no timeout and unsafe JSON shape assumptions.
-
----
-
-## TODOs / stubs / cleanup
-
-- `grep` did not find meaningful source TODO/FIXME comments beyond test fixtures and identifiers.
-- There are explicit MVP/stub/no-op areas:
- - `gui/src-tauri/src/runtime/simple.rs:1442`–`1488`: workflow sync/query/draft paths are placeholders.
- - `gui/src-tauri/src/runtime/simple.rs:1634`–`1649`: MCP OAuth login/logout explicitly unsupported.
- - `gui/src-tauri/src/lib.rs:12`–`15`, `18`–`22`: copied bridge/persistence modules retained for future parity.
-- Working tree has ignored runtime artifacts (`session-*.json`, `harness.trace.jsonl`, `harness.trajectory.jsonl`, `codedb.snapshot`, etc.) and untracked `.graff/` plus `apps/ios/build/...`. These are cleanup hazards even if ignored.
-
----
-
-## Areas needing tests
-
-1. **MCP malformed config tests** for non-object `mcpServers`, non-object server entries, non-string env values.
-2. **MCP timeout tests** with a server that never responds or emits only notifications.
-3. **Debug bridge security tests** asserting either disabled-by-default behavior or required auth token.
-4. **Temp file safety tests** for pasted images: no symlink following, private directory permissions, unique paths.
-5. **Runtime session lifecycle tests** around:
- - queued prompt order;
- - stop while streaming;
- - control messages during active runs;
- - dropped child and retry behavior.
-6. **Provider auth retry/cancel tests** for the large settings dialog + runtime provider code.
-
----
-
-## Verdict
-
-**Most dangerous defect:** the unauthenticated debug bridge at `gui/src-tauri/src/debug_bridge.rs:91`/`137`/`188`, because any local process or reachable browser context can drive arbitrary JS execution inside a debug Tauri app with no shared secret or origin validation.
-
-[subagent sa-000-f57b1da8 · inspect: .graff/subagents/sa-000-f57b1da8.md]
-
-## report
-
-# Guided tour of the Codegraff codebase
-
-## 1. Project purpose and stack
-
-### Verified
-
-Codegraff is a mixed CLI + desktop agentic coding harness. The core product is the `graff` executable, described as “a minimal agentic coding harness in Zig 0.16” that talks to LLM providers, executes model-requested tools, and repeats until the model stops. The README describes the loop as model request → parallel tool execution → feed results back → continue. (`README.md:1-6`, `README.md:17-28`)
-
-The repo has four major technology layers:
-
-| Layer | Purpose | Stack / evidence |
-|---|---|---|
-| CLI agent core | Main `graff` runtime, tools, providers, JSON/HTTP protocol, subagents/workflows | Zig 0.16; `build.zig` builds executable `graff` from `src/main.zig`. (`build.zig:42-51`) |
-| Desktop app | Tauri desktop GUI over the CLI runtime | Tauri 2 + Rust backend + React/TypeScript/Vite frontend. (`gui/package.json:18-60`, `gui/src-tauri/Cargo.toml:7-52`) |
-| Shared UI package | Diff/file-change rendering used by GUI | `@codegraff/diffs` TypeScript package. (`packages/diffs/package.json:1-24`) |
-| SDK / remote API | Generated TypeScript/Python SDKs and HTTP bridge clients | `graff --schema` is machine-readable interface used to generate SDKs. (`README.md:402-411`, `sdk/README.md:13-18`) |
-
-The root repo is a Bun workspace covering `gui` and `packages/*`. (`package.json:1-9`)
-
-### Inferred
-
-The project is best understood as **one product with two primary front doors**:
-
-1. Terminal users run `graff` directly.
-2. Desktop users run the Tauri GUI, which spawns persistent `graff --json` child processes and translates their streamed events into GUI state.
-
-This is inferred from the CLI JSON protocol definition in `src/main.zig` and the GUI runtime’s persistent `GraffSession` design. (`src/main.zig:79-111`, `gui/src-tauri/src/runtime/simple.rs:85-97`, `gui/src-tauri/src/runtime/simple.rs:690-1005`)
-
----
-
-## 2. Directory map
-
-### Top-level map
-
-```text
-.
-├── build.zig # Zig build file for graff CLI
-├── src/
-│ ├── main.zig # Core CLI/agent runtime
-│ └── mcp.zig # Minimal stdio MCP client
-├── gui/
-│ ├── package.json # Bun/Vite/React/Tauri frontend scripts
-│ ├── src/ # React frontend
-│ └── src-tauri/ # Rust/Tauri backend
-├── packages/
-│ └── diffs/ # Shared TypeScript diff renderer
-├── sdk/
-│ ├── generate.py # SDK generator from graff --schema
-│ ├── py/ # Python SDK package
-│ └── ts/ # TypeScript SDK package
-├── examples/
-│ └── edge-worker/ # Remote bridge / Cloudflare Worker example
-├── scripts/ # Helper/test/dev scripts
-├── docs/ # Documentation
-├── plans/ # Planning notes
-└── .github/workflows/ # CI, release, SDK publishing
-```
-
-### Key verified areas
-
-- `src/` contains the Zig CLI/agent implementation; `build.zig` compiles `src/main.zig` as `graff`. (`build.zig:42-49`)
-- `src/mcp.zig` implements a stdio MCP client. (`src/mcp.zig:1-12`)
-- `gui/` contains the Tauri desktop app; frontend entry renders `<App />`, Rust entry calls `codegraff_gui_lib::run()`. (`gui/src/main.tsx:1-13`, `gui/src-tauri/src/main.rs:4-6`)
-- `packages/diffs/` is a shared diff-rendering package consumed by the GUI. (`gui/package.json:18-21`, `packages/diffs/package.json:12-24`)
-- `sdk/` contains generated TypeScript and Python SDKs; SDKs are generated from `graff --schema`. (`sdk/README.md:1-18`)
-- `.github/workflows/ci.yml` validates the Zig CLI, formatting, JSON protocol, and SDK drift. (`.github/workflows/ci.yml:27-55`)
-
----
-
-## 3. Main execution flow
-
-## 3.1 CLI / agent flow
-
-### Verified flow
-
-1. `zig build` builds the executable named `graff` from `src/main.zig`. (`build.zig:42-51`)
-2. `src/main.zig` exposes `pub fn main(init: std.process.Init) !void` and parses CLI flags such as `--yolo`, `--json`, `--schema`, `--model`, and `--resume`. (`src/main.zig:4307-4385`)
-3. A root `Agent` owns allocator/arena, shared HTTP client, provider, message history, MCP registry, approval/tracing state, system prompts, tool JSON variants, todo state, and runtime options. (`src/main.zig:8163-8224`)
-4. `Agent.runTurn()` loops through provider request/response handling until final text is produced. (`src/main.zig:8316-8335`)
-5. `Agent.request()` builds provider-specific request bodies, streams where needed, retries flaky HTTP failures, and emits JSON events for clients. (`src/main.zig:8337-8365`)
-6. If the model asks for tools, `Agent.runTools()` separates meta tools from external tools, gates/rejects tools as appropriate, runs external calls in parallel via `io.async`, and joins futures. (`src/main.zig:8807-8870`)
-7. `execTool()` applies gates, calls `execToolInner`, records tracing/telemetry/tool-use, and returns structured tool output. (`src/main.zig:11809-11831`)
-8. Subagents and workflows are implemented as tool execution paths. `execSubagent()` delegates to `runSub()`, which creates a fresh `Agent` with fresh history but shared client/provider. (`src/main.zig:12484-12587`)
-9. `execWorkflow()` runs sequential phases of parallel subagent tasks, capped at 5 phases and 8 tasks per phase. (`src/main.zig:12594-12698`)
-
-### CLI mental model
-
-```text
-user prompt
- -> graff main()
- -> Agent.runTurn()
- -> Agent.request()
- -> provider API call
- -> parse model response
- -> if tool calls:
- Agent.runTools()
- -> execTool()
- -> maybe MCP / bash / file / subagent / workflow
- feed tool results back
- -> final assistant text
-```
-
-## 3.2 MCP flow
-
-### Verified flow
-
-`src/mcp.zig` is a minimal MCP client over stdio JSON-RPC. It spawns servers from `.mcp.json`, runs `initialize → initialized → tools/list`, exposes namespaced tools, and routes `tools/call` back to the server. (`src/mcp.zig:1-12`, `src/mcp.zig:84-120`, `src/mcp.zig:229-323`, `src/mcp.zig:334-404`)
-
-MCP tool names are namespaced as `mcp__<server>__<tool>`. (`src/mcp.zig:298-323`)
-
-MCP access is serialized with a registry mutex because each server has one bidirectional stdio pipe. (`src/mcp.zig:8-11`, `src/mcp.zig:355-360`)
-
-## 3.3 Desktop GUI flow
-
-### Verified flow
-
-1. React entrypoint renders `<App />`. (`gui/src/main.tsx:9-13`)
-2. `App` wraps the UI in `SessionProvider` and `DragDropProvider`, then renders `AppShell`. (`gui/src/app/App.tsx:385-396`)
-3. `AppShell` displays sidebar/settings/workspace board inside resizable panels. (`gui/src/app/App.tsx:265-379`)
-4. `SessionProvider` bootstraps the session, subscribes to backend updates, opens forwarded workspace paths, and exposes action methods. (`gui/src/app/SessionProvider.tsx:55-92`, `gui/src/app/SessionProvider.tsx:127-178`, `gui/src/app/SessionProvider.tsx:651-655`)
-5. Frontend actions call `desktopClient`, which wraps Tauri `invoke` and `listen`. (`gui/src/services/desktop/client.ts:311-319`, `gui/src/services/desktop/client.ts:338-802`)
-6. Tauri registers backend commands with `tauri::generate_handler!`. (`gui/src-tauri/src/lib.rs:108-174`)
-7. `commands.rs` mostly delegates to `DesktopState.manager` methods. (`gui/src-tauri/src/commands.rs:48-80`, `gui/src-tauri/src/commands.rs:155-180`)
-8. `RuntimeManager.send_prompt()` creates/selects a conversation, appends the user message, queues concurrent prompts if necessary, emits snapshots, optionally generates a title, and streams the turn. (`gui/src-tauri/src/runtime/simple.rs:467-688`)
-9. `stream_turn()` writes a JSON user line to a long-lived `graff --json` child process, reads JSONL events, and maps those events into GUI messages, reasoning, tool rows, followups, errors, and turn completion. (`gui/src-tauri/src/runtime/simple.rs:690-1005`)
-10. The runtime emits `SessionSnapshot` updates back to the frontend. (`gui/src-tauri/src/runtime/simple.rs:1074-1079`, `gui/src/services/desktop/client.ts:752-756`)
-
-### Desktop mental model
-
-```text
-React UI
- -> SessionProvider action
- -> desktopClient.invoke(...)
- -> Tauri command in commands.rs
- -> RuntimeManager
- -> persistent graff --json child process
- -> streamed JSONL events
- -> SessionSnapshot
- -> frontend applies snapshot to sessionStore
-```
-
----
-
-## 4. Key modules to know
-
-## 4.1 Zig core
-
-### `src/main.zig`
-
-This is the center of gravity for the CLI runtime.
-
-It contains:
-
-- CLI parsing and modes such as `--json`, `--schema`, `--model`, `--resume`, and `--yolo`. (`src/main.zig:4307-4385`)
-- JSON stdio protocol event schema, including `text`, `reasoning`, `tool_call`, `tool_result`, `turn`, and `error`. (`src/main.zig:79-111`)
-- HTTP bridge schema for `graff serve`, including `/healthz`, `/v1/schema`, and session endpoints. (`src/main.zig:114-128`)
-- `Agent` state and run loop. (`src/main.zig:8163-8335`)
-- Provider request handling. (`src/main.zig:8337-8365`)
-- Parallel tool execution. (`src/main.zig:8807-8870`)
-- Subagents and workflows. (`src/main.zig:12484-12698`)
-
-### `src/mcp.zig`
-
-This is the MCP integration layer.
-
-It:
-
-- Reads `.mcp.json`.
-- Spawns MCP server subprocesses.
-- Performs JSON-RPC initialization.
-- Lists server tools.
-- Calls MCP tools through stdio.
-- Serializes access with a mutex. (`src/mcp.zig:1-12`, `src/mcp.zig:84-120`, `src/mcp.zig:229-404`)
-
-## 4.2 GUI frontend
-
-### `gui/src/app/App.tsx`
-
-Top-level shell. It wires:
-
-- `SessionProvider`
-- drag/drop context
-- app shell
-- sidebar/settings/workspace layout
-- `/success` OAuth success route
-
-Evidence: (`gui/src/app/App.tsx:123-170`, `gui/src/app/App.tsx:265-396`)
-
-### `gui/src/app/SessionProvider.tsx`
-
-Main frontend orchestrator. It:
-
-- Applies backend snapshots into frontend state.
-- Bootstraps sessions.
-- Handles forwarded workspace paths.
-- Exposes user actions.
-- Submits prompts through `desktopClient.sendPrompt`.
-
-Evidence: (`gui/src/app/SessionProvider.tsx:55-92`, `gui/src/app/SessionProvider.tsx:127-178`, `gui/src/app/SessionProvider.tsx:563-619`, `gui/src/app/SessionProvider.tsx:651-655`)
-
-### `gui/src/services/desktop/client.ts`
-
-Frontend/backend boundary. It:
-
-- Wraps Tauri `invoke`.
-- Wraps Tauri event `listen`.
-- Supports QA mock mode through `VITE_CODEGRAFF_QA_MOCK=1`.
-- Exports typed functions for workspaces, sessions, prompts, providers, MCP, git, layouts, saved workspaces, and terminals.
-
-Evidence: (`gui/src/services/desktop/client.ts:56-60`, `gui/src/services/desktop/client.ts:266-336`, `gui/src/services/desktop/client.ts:338-802`)
-
-### `gui/src/components/workspace-board/WorkspaceBoard.tsx`
-
-Main multi-chat workspace surface. It:
-
-- Uses Dockview layouts.
-- Renders empty state, workspace draft, single chat, or saved multi-chat workspace.
-- Converts multiple chats into saved workspaces.
-- Persists/restores layouts.
-
-Evidence: (`gui/src/components/workspace-board/WorkspaceBoard.tsx:51-104`, `gui/src/components/workspace-board/WorkspaceBoard.tsx:313-388`, `gui/src/components/workspace-board/WorkspaceBoard.tsx:439-481`, `gui/src/components/workspace-board/WorkspaceBoard.tsx:538-586`)
-
-### `gui/src/components/workspace-board/ChatTile.tsx`
-
-Per-chat workspace tile. It hosts:
-
-- Conversation pane.
-- Preview pane.
-- Terminal pane.
-- Changes pane.
-- Per-conversation layout persistence.
-
-Evidence: (`gui/src/components/workspace-board/ChatTile.tsx:495-540`, `gui/src/components/workspace-board/ChatTile.tsx:572-608`, `gui/src/components/workspace-board/ChatTile.tsx:729-781`)
-
-## 4.3 GUI Rust backend
-
-### `gui/src-tauri/src/lib.rs`
-
-Tauri app setup. It:
-
-- Initializes app data/project store.
-- Manages `DesktopState`.
-- Registers command handlers.
-- Starts the app.
-- Starts the debug bridge in debug builds only.
-
-Evidence: (`gui/src-tauri/src/lib.rs:49-85`, `gui/src-tauri/src/lib.rs:92-97`, `gui/src-tauri/src/lib.rs:108-176`)
-
-### `gui/src-tauri/src/commands.rs`
-
-Tauri command adapter layer. It:
-
-- Maps frontend commands to `RuntimeManager`.
-- Implements some direct helpers: file pickers, pasted image persistence, thumbnails, workspace-confined file reads, `git clone`, GitHub quick-start, and terminal commands.
-
-Evidence: (`gui/src-tauri/src/commands.rs:24-46`, `gui/src-tauri/src/commands.rs:48-80`, `gui/src-tauri/src/commands.rs:155-180`, `gui/src-tauri/src/commands.rs:252-292`, `gui/src-tauri/src/commands.rs:626-694`, `gui/src-tauri/src/commands.rs:781-958`)
-
-### `gui/src-tauri/src/runtime/simple.rs`
-
-Desktop runtime adapter. This is the GUI backend’s main state machine.
-
-It owns:
-
-- Runtime state.
-- Project registry.
-- Active conversations.
-- Persistent `graff --json` child sessions.
-- Prompt streaming.
-- Snapshot emission.
-- Provider auth.
-- MCP config.
-- Git operations.
-- Saved workspaces/layouts.
-- Tests.
-
-Evidence: (`gui/src-tauri/src/runtime/simple.rs:51-130`, `gui/src-tauri/src/runtime/simple.rs:467-688`, `gui/src-tauri/src/runtime/simple.rs:690-1005`, `gui/src-tauri/src/runtime/simple.rs:1126-1203`, `gui/src-tauri/src/runtime/simple.rs:2093-2215`, `gui/src-tauri/src/runtime/simple.rs:4001-4259`)
-
-### `gui/src-tauri/src/persistence/project_store.rs`
-
-SQLite persistence layer. It:
-
-- Uses Diesel with SQLite.
-- Stores opened projects, managed chat workspaces, conversation layouts, saved workspaces, and saved workspace layouts.
-- Creates/migrates tables in `init()`.
-
-Evidence: (`gui/src-tauri/src/persistence/project_store.rs:1-10`, `gui/src-tauri/src/persistence/project_store.rs:31-36`, `gui/src-tauri/src/persistence/project_store.rs:460-544`)
-
-## 4.4 Shared diff package
-
-### `packages/diffs`
-
-This package builds reusable diff/file-change rendering for plain and React use. It is consumed by the GUI through a workspace dependency. (`gui/package.json:18-21`, `packages/diffs/package.json:12-24`)
-
-Build script is `tsc -p tsconfig.build.json`. (`packages/diffs/package.json:23-25`)
-
----
-
-## 5. User-facing feature map
-
-### CLI features
-
-Verified CLI features include:
-
-- REPL and one-shot prompt mode. (`README.md:279-300`)
-- Model selection with `--model`. (`README.md:279-300`)
-- Login/key management. (`README.md:74-82`, `README.md:219-228`)
-- JSON protocol mode and schema generation. (`README.md:402-411`)
-- Slash commands such as `/model`, `/plan`, `/key`, `/reasoning`, `/compact`, `/save`, `/resume`, `/todo`, `/mcp`, and `/help`. (`README.md:317-346`)
-- Permission-gated tools, `yolo`, `plan`, and `strict` modes. (`README.md:364-398`)
-- Subagents and workflow fan-out, including “ultracode”. (`README.md:541-560`)
-- HTTP `serve` mode for remote clients, with NDJSON streaming and bearer-token support for non-loopback use. (`README.md:735-746`)
-
-### Desktop features
-
-Verified desktop flows include:
-
-- Sidebar with saved workspaces, managed chats, projects, and settings. (`gui/src/components/ProjectSidebar.tsx:244-423`)
-- New chat onboarding, provider setup, clone repository, quick-start project, and open folder flows. (`gui/src/components/new-chat-screen/NewChatScreen.tsx:81-143`, `gui/src/components/new-chat-screen/hooks/useNewChatScreenController.ts:149-251`)
-- Prompt composer with slash-command autocomplete, model picker, reasoning effort picker, Plan mode, Fast mode, Ultra mode, stop/send, prompt history, drag/drop attachments, and pasted image attachments. (`gui/src/components/PromptInputCard.tsx:93-181`, `gui/src/components/PromptInputCard.tsx:199-621`)
-- Conversation streaming into chat messages, reasoning, tools, followups, errors, and turn completion. (`gui/src-tauri/src/runtime/simple.rs:692-1005`)
-- Multi-chat saved workspace layout through Dockview. (`gui/src/components/workspace-board/WorkspaceBoard.tsx:313-388`)
-- Changes/diff/git actions. (`gui/src/components/workspace-board/ChangesPane.tsx:199-349`, `gui/src/app/SessionProvider.tsx:180-228`)
-- Terminal panes backed by backend PTY sessions. (`gui/src/components/workspace-board/hooks/useTerminalSession.ts:148-272`, `gui/src-tauri/src/commands.rs:781-827`)
-- Provider settings with API key, device code, CLI login, and OAuth authorization code flows. (`gui/src/components/providers-settings/ProviderSetupDialog.tsx:128-330`, `gui/src/components/providers-settings/ProviderSetupDialog.tsx:416-572`)
-- MCP settings for listing, importing, removing, reloading, login, and logout. (`gui/src/components/mcp-settings/McpSettingsPane.tsx:35-275`, `gui/src/services/desktop/client.ts:529-567`)
-
----
-
-## 6. How to run, build, and test
-
-## 6.1 CLI
-
-### Build
-
-```sh
-zig build
-```
-
-CI runs exactly this. (`.github/workflows/ci.yml:39-40`)
-
-### Run from source
-
-```sh
-zig build run
-# or
-./zig-out/bin/graff
-```
-
-`build.zig` defines a `run` step, and the README documents both commands. (`build.zig:53-56`, `README.md:692-699`)
-
-### Test
-
-```sh
-zig build test
-zig build test --summary all
-```
-
-`build.zig` defines the test step using `src/main.zig` as the test root, and CI runs `zig build test --summary all`. (`build.zig:58-69`, `.github/workflows/ci.yml:45-46`)
-
-### Format check
-
-```sh
-zig fmt --check src/main.zig src/mcp.zig build.zig
-```
-
-CI enforces this exact command. (`.github/workflows/ci.yml:42-43`)
-
-### JSON protocol test
-
-```sh
-python3 scripts/test-json-controls.py zig-out/bin/graff
-```
-
-CI runs this after building `graff`. (`.github/workflows/ci.yml:48-49`)
-
-### SDK drift check
-
-```sh
-python3 sdk/generate.py --harness ./zig-out/bin/graff
-git diff --exit-code sdk/
-```
-
-CI regenerates SDKs and fails if generated SDK files change. (`.github/workflows/ci.yml:51-55`)
-
-## 6.2 GUI frontend
-
-From `gui/`:
-
-```sh
-bun run dev
-bun run build
-bun run lint
-bun test
-bun run preview
-```
-
-Verified scripts:
-
-- `dev`: `bun run build:deps && vite`
-- `build`: `bun run build:deps && bun run gen:desktop-contracts && tsc -b && vite build`
-- `lint`: `bun run build:deps && bun run gen:desktop-contracts && eslint .`
-- `test`: `bun test`
-- `preview`: `vite preview`
-
-Evidence: (`gui/package.json:8-17`)
-
-### Desktop contract generation
-
-```sh
-cd gui
-bun run gen:desktop-contracts
-```
-
-This runs:
-
-```sh
-cargo run --quiet --manifest-path src-tauri/Cargo.toml --example generate_desktop_contracts
-```
-
-Evidence: (`gui/package.json:10`)
-
-## 6.3 Tauri desktop app
-
-Likely commands:
-
-```sh
-cd gui
-bun run tauri dev
-bun run tauri build
-```
-
-This is inferred because `gui/package.json` exposes `"tauri": "tauri"`, and Tauri config defines `beforeDevCommand` as `bun run dev` and `beforeBuildCommand` as `bun run build`. (`gui/package.json:14-15`, `gui/src-tauri/tauri.conf.json:6-10`)
-
-### Important runtime requirement
-
-The desktop app must find a usable `graff` binary. Lookup order starts with `CODEGRAFF_GUI_BINARY`, then bundled sidecar, dev path `../../zig-out/bin/graff`, known install locations, and finally bare `graff` on `PATH`. (`gui/src-tauri/src/runtime/simple.rs:3240-3300`)
-
-If spawning fails, the GUI error tells the user to install the CLI or set `CODEGRAFF_GUI_BINARY`. (`gui/src-tauri/src/runtime/simple.rs:2652-2657`)
-
-The GUI spawns:
-
-```text
-graff --json --yolo --resume <conversation_id>
-```
-
-and optionally `--model <model>`, in the workspace directory. (`gui/src-tauri/src/runtime/simple.rs:2626-2649`)
-
-## 6.4 Rust/Tauri tests
-
-Inferred command:
-
-```sh
-cargo test --manifest-path gui/src-tauri/Cargo.toml
-```
-
-This is not wired into package scripts or CI, but Rust `#[test]` declarations exist and `pretty_assertions` is a dev dependency. (`gui/src-tauri/src/runtime/simple.rs:4001-4259`, `gui/src-tauri/Cargo.toml:54-56`)
-
-## 6.5 Shared diff package
-
-```sh
-cd packages/diffs
-bun run build
-bun test
-```
-
-Build script is `tsc -p tsconfig.build.json`; test script is `bun test`. (`packages/diffs/package.json:23-26`)
-
-## 6.6 SDKs
-
-Regenerate SDKs locally:
-
-```sh
-python3 sdk/generate.py --harness ./zig-out/bin/graff
-# or
-graff --schema | python3 sdk/generate.py
-```
-
-Evidence: (`sdk/README.md:13-18`, `sdk/generate.py:22-32`)
-
----
-
-## 7. Risks and hotspots
-
-## 7.1 Security / robustness risks
-
-### Debug bridge can execute arbitrary JS in debug builds
-
-In debug builds, the GUI starts an HTTP debug bridge on `127.0.0.1:9233` with no token/origin check. `POST /eval` accepts arbitrary code, embeds it into a JS snippet, and evaluates it in the main Tauri webview. Responses include `Access-Control-Allow-Origin: *`. (`gui/src-tauri/src/debug_bridge.rs:91`, `gui/src-tauri/src/debug_bridge.rs:137`, `gui/src-tauri/src/debug_bridge.rs:188`, `gui/src-tauri/src/debug_bridge.rs:291`)
-
-Impact: local process or malicious browser page can drive arbitrary JS execution inside a debug Tauri app context.
-
-### MCP request can hang forever
-
-`src/mcp.zig` writes a JSON-RPC request and loops on newline-delimited responses until it sees a matching `id`, with no timeout, cancellation, or child-liveness check beyond EOF. (`src/mcp.zig:410-428`)
-
-Impact: a silent or broken MCP server from workspace `.mcp.json` can wedge startup or MCP operations.
-
-### Malformed `.mcp.json` can crash
-
-Several JSON values in `src/mcp.zig` are accessed as `.object` or `.string` without checking the active union tag. (`src/mcp.zig:103`, `src/mcp.zig:111`, `src/mcp.zig:250`)
-
-Impact: malformed workspace-controlled config can cause runtime panic in safe builds and worse behavior in unsafe/optimized contexts.
-
-### Predictable temp-file writes for pasted images
-
-`save_pasted_image` writes to a predictable path under the shared temp directory: `codegraff-pasted/paste-<pid>-<counter>.<ext>`, using `std::fs::write`, which follows symlinks. (`gui/src-tauri/src/commands.rs:264-267`)
-
-Impact: local same-user or same-machine file clobber risk.
-
-### Debug screenshot uses fixed temp filename
-
-The debug screenshot endpoint writes to `std::env::temp_dir().join("cg_debug_full.png")`. (`gui/src-tauri/src/debug_bridge.rs:249-259`)
-
-Impact: local file clobber or stale/racy screenshot behavior in debug builds.
-
-## 7.2 Complexity hotspots
-
-### `gui/src-tauri/src/runtime/simple.rs`
-
-Large, central Rust file around 4,499 lines. It owns runtime state, provider auth, model selection, MCP config, persistence, child-process sessions, git commands, and tests.
-
-Most failure-prone areas:
-
-- `send_prompt`
-- `stream_turn`
-- `send_control`
-- `acquire_session_io`
-- provider credential detection
-- login-shell environment bootstrapping
-- persistence with best-effort ignored errors
-
-Evidence for scope: (`gui/src-tauri/src/runtime/simple.rs:51-130`, `gui/src-tauri/src/runtime/simple.rs:467-688`, `gui/src-tauri/src/runtime/simple.rs:690-1005`, `gui/src-tauri/src/runtime/simple.rs:1126-1203`, `gui/src-tauri/src/runtime/simple.rs:2093-2215`)
-
-### `src/main.zig`
-
-The Zig agent core is central and very large. It owns provider requests, tool execution, subagents, workflows, JSON protocol, HTTP protocol, and CLI parsing. (`src/main.zig:79-128`, `src/main.zig:4307-4385`, `src/main.zig:8163-8870`, `src/main.zig:12484-12698`)
-
-### `gui/src/app/sessionStore.ts`
-
-Central frontend state file around 924 lines. It manages selection, drafts, attachments, request timing, view caching, and async request de-duplication. This is likely race-prone and needs regression coverage.
-
-### `gui/src-tauri/src/commands.rs`
-
-Large Tauri command surface around 959 lines. Security-sensitive helpers live beside ordinary UI glue. Evidence for command surface and direct helpers: (`gui/src-tauri/src/commands.rs:24-46`, `gui/src-tauri/src/commands.rs:48-827`)
-
-### `gui/src/services/desktop/client.ts`
-
-Large frontend API boundary around 802 lines. It contains both production Tauri calls and QA mock mode, creating risk of mock/contract drift. (`gui/src/services/desktop/client.ts:266-319`, `gui/src/services/desktop/client.ts:338-802`)
-
-### `gui/src/components/providers-settings/ProviderSetupDialog.tsx`
-
-Complex provider auth state machine, including API keys, device code, CLI login, OAuth, polling, cancellation, and callbacks. (`gui/src/components/providers-settings/ProviderSetupDialog.tsx:128-330`, `gui/src/components/providers-settings/ProviderSetupDialog.tsx:416-572`)
-
-## 7.3 Verified documentation/config discrepancy
-
-`build.zig` currently bakes a telemetry endpoint by default unless `-Dtelemetry-endpoint=""` is passed. (`build.zig:26-37`)
-
-README says source builds have no endpoint baked in unless an environment endpoint is set. (`README.md:656-659`)
-
-These statements conflict.
-
----
-
-## 8. Recommended next exploration steps
-
-### 1. Trace one full CLI prompt in `src/main.zig`
-
-Start with:
-
-- CLI parsing: `src/main.zig:4307-4385`
-- `Agent` fields: `src/main.zig:8163-8224`
-- turn loop: `src/main.zig:8316-8335`
-- request construction/streaming: `src/main.zig:8337-8365`
-- tool execution: `src/main.zig:8807-8870`
-- subagents/workflows: `src/main.zig:12484-12698`
-
-Goal: understand the exact lifecycle of a model turn and how provider responses are normalized.
-
-### 2. Trace one desktop prompt end-to-end
-
-Follow:
-
-```text
-PromptComposer / SessionProvider
- -> desktopClient.sendPrompt
- -> commands.rs send_prompt
- -> RuntimeManager.send_prompt
- -> stream_turn
- -> graff --json child
- -> SessionSnapshot event
- -> frontend sessionStore
-```
-
-Key files:
-
-- `gui/src/app/SessionProvider.tsx`
-- `gui/src/services/desktop/client.ts`
-- `gui/src-tauri/src/commands.rs`
-- `gui/src-tauri/src/runtime/simple.rs`
-- `gui/src/app/sessionStore.ts`
-
-Evidence for this path: (`gui/src/app/SessionProvider.tsx:563-619`, `gui/src/services/desktop/client.ts:338-457`, `gui/src-tauri/src/commands.rs:155-165`, `gui/src-tauri/src/runtime/simple.rs:467-1005`)
-
-### 3. Inspect the generated desktop contracts
-
-The GUI build runs `gen:desktop-contracts` before TypeScript build/lint. (`gui/package.json:10-13`)
-
-Next step: inspect the generated files under `gui/src-tauri/gen/**` and compare them with `desktopClient.ts` and `commands.rs` to understand how strongly typed the frontend/backend boundary is.
-
-### 4. Audit MCP robustness
-
-Focus on:
-
-- `.mcp.json` parsing shape validation. (`src/mcp.zig:103`, `src/mcp.zig:111`, `src/mcp.zig:250`)
-- request timeout/cancellation. (`src/mcp.zig:410-428`)
-- process cleanup on failure.
-
-This is a compact subsystem with concrete failure modes.
-
-### 5. Explore provider auth from GUI to CLI
-
-Follow:
-
-- `ProvidersSettingsPane`
-- `ProviderSetupDialog`
-- `desktopClient` provider calls
-- Tauri provider commands
-- `RuntimeManager` provider methods
-- CLI credential expectations from README
-
-Evidence: (`gui/src/components/providers-settings/ProvidersSettingsPane.tsx:62-328`, `gui/src/components/providers-settings/ProviderSetupDialog.tsx:128-572`, `gui/src-services/desktop/client.ts:529-590`, `gui/src-tauri/src/commands.rs:95-141`, `README.md:219-228`)
-
-### 6. Add or inspect tests around session lifecycle
-
-High-value scenarios:
-
-- queued prompt order
-- stop while streaming
-- child process death and retry
-- control messages during active run
-- snapshot consistency
-- persisted layout save/load
-
-Rust tests already exist in `runtime/simple.rs`, but are not wired into CI/package scripts. (`gui/src-tauri/src/runtime/simple.rs:4001-4259`)
-
----
-
-## 9. Verified vs inferred summary
-
-### Verified
-
-- The core executable is `graff`, built from `src/main.zig`. (`build.zig:42-51`)
-- The CLI agent loop lives in `src/main.zig` and owns provider calls, tools, subagents, workflows, and protocols. (`src/main.zig:8316-8870`, `src/main.zig:12484-12698`)
-- The desktop app is Tauri 2 + Rust + React/TypeScript/Vite. (`gui/package.json:18-60`, `gui/src-tauri/Cargo.toml:7-52`)
-- The GUI frontend talks to Rust through `desktopClient.ts` and Tauri commands. (`gui/src/services/desktop/client.ts:311-319`, `gui/src-tauri/src/lib.rs:108-174`)
-- The GUI backend streams turns through persistent `graff --json` child processes. (`gui/src-tauri/src/runtime/simple.rs:85-97`, `gui/src-tauri/src/runtime/simple.rs:690-1005`)
-- The main GUI state transition unit is `SessionSnapshot`. (`gui/src-tauri/src/runtime/simple.rs:1074-1079`, `gui/src-tauri/src/runtime/simple.rs:2093-2215`)
-- CI validates Zig build/test/fmt, JSON controls, and SDK drift. (`.github/workflows/ci.yml:27-55`)
-
-### Inferred
-
-- The GUI is intentionally a thin adapter over the Zig runtime rather than a second implementation of the agent. This is inferred from the persistent `graff --json` child-session design and comments describing the Rust runtime as coordinating the copied desktop GUI with the Zig-native binary. (`gui/src-tauri/src/runtime/simple.rs:85-105`, `gui/src-tauri/src/runtime/simple.rs:690-1005`)
-- Saved workspaces are a GUI-level multi-chat/layout concept rather than a core CLI concept. This is inferred from Dockview layout serialization and saved-workspace persistence in the GUI/Tauri layer. (`gui/src/components/workspace-board/WorkspaceBoard.tsx:365-384`, `gui/src-tauri/src/runtime/simple.rs:2178-2188`)
-- The product direction is an agent workbench: chat, code changes, terminals, git, providers, MCP, and multi-agent workflows in one desktop surface. This is inferred from the connected GUI panes and backend APIs. (`gui/src/components/workspace-board/ChatTile.tsx:495-540`, `gui/src/components/workspace-board/ChangesPane.tsx:279-349`, `gui/src/components/workspace-board/hooks/useTerminalSession.ts:148-235`, `gui/src/components/providers-settings/ProvidersSettingsPane.tsx:134-328`, `gui/src/components/mcp-settings/McpSettingsPane.tsx:96-275`)
-
----
-
-## 10. Three most load-bearing facts
-
-1. **`src/main.zig` is the agent core.** It is compiled into `graff` and owns provider requests, tool execution, subagents, workflows, and JSON/HTTP protocols. (`build.zig:42-49`, `src/main.zig:8316-8365`, `src/main.zig:8807-8870`, `src/main.zig:12484-12698`)
-
-2. **The desktop app does not reimplement the agent loop.** It spawns persistent `graff --json` child processes per conversation and translates streamed JSONL events into GUI state. (`gui/src-tauri/src/runtime/simple.rs:85-97`, `gui/src-tauri/src/runtime/simple.rs:690-1005`, `gui/src-tauri/src/runtime/simple.rs:1126-1203`)
-
-3. **The frontend/backend desktop contract centers on snapshots and Tauri commands.** Frontend actions call `desktopClient`, Tauri commands delegate to `RuntimeManager`, the runtime emits `SessionSnapshot`s, and the frontend applies them into session state. (`gui/src/services/desktop/client.ts:338-802`, `gui/src-tauri/src/lib.rs:108-174`, `gui/src-tauri/src/runtime/simple.rs:1074-1079`, `gui/src-tauri/src/runtime/simple.rs:2093-2215`)
-
-## Open question
-
-Which telemetry behavior is intended for source/dev builds? `build.zig` bakes a telemetry endpoint by default unless `-Dtelemetry-endpoint=""` is passed, while the README says source builds have no endpoint baked in unless environment variables are set. (`build.zig:26-37`, `README.md:656-659`)
diff --git a/.graff/subagents/sa-004-d913162c.md b/.graff/subagents/sa-004-d913162c.md
deleted file mode 100644
index ea7c3897..00000000
--- a/.graff/subagents/sa-004-d913162c.md
+++ /dev/null
@@ -1,213 +0,0 @@
-# subagent sa-004-d913162c
-
-- label: Explore iOS app
-- kind: workflow_task
-- status: ok
-- elapsed_ms: 73291
-- tools: codedb,bash,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,codedb,codedb,read_file,read_file,read_file,codedb,codedb,codedb,codedb
-
-## task
-
-You are exploring the iOS companion app in apps/ios/. Use the codedb tool (search, symbol, outline, callers, context) to thoroughly understand:
-1. The overall app structure (GraffApp.swift, project.yml, build scripts)
-2. GraffServeClient.swift — the NDJSON protocol client that speaks to graff serve
-3. ChatView.swift, SessionsListView.swift — the main UI and how it displays sessions/chat
-4. How the app connects to the core harness, what data it streams, and how it handles the protocol
-5. Any build/automation scripts (autotest.sh, build-sim.sh, recap.sh)
-
-Be thorough and return a structured markdown report.
-
-## report
-
-# iOS Companion App (`apps/ios/`) — Structured Report
-
-## 1. Overall App Structure
-
-### Source layout
-| File | Purpose | Lines |
-|------|---------|-------|
-| `GraffApp.swift` | `@main` entry point, app-level models, sample data, Liquid Glass helpers | 165 |
-| `GraffServeClient.swift` | NDJSON-over-HTTP transport that speaks to `graff serve` | 98 |
-| `ChatView.swift` | Session detail: chat bubbles, task progress, composer, plan decision bar | 226 |
-| `SessionsListView.swift` | Root list of sessions with status chips and progress | 66 |
-| `Info.plist` | Bundle metadata, iOS 26.0 minimum, local-network ATS exception | 29 |
-
-### Entry point & launch modes
-- `GraffApp` (`GraffApp.swift:4`) is a `SwiftUI.App` whose `WindowGroup` shows either `AutoTestView` (when `CommandLine.arguments.contains("--autotest")`) or `SessionsListView`.
-- `AutoTestView` (`GraffApp.swift:19`) opens the first sample session (`sampleSessions[0]`) and passes `autoSend: "Reply with one short sentence confirming the serve transport works."` to `ChatView`. This is a CI/automation gate: it verifies the live transport on the simulator without manual tapping.
-
-### Models (all in `GraffApp.swift`)
-- **`AgentSession`** (`GraffApp.swift:101`): identity (`id`, `title`, `model`), `status: SessionStatus`, `todos: [TodoItem]`, `messages: [ChatMessage]`, `planPending: Bool`, and a computed `progress` tuple.
-- **`ChatMessage`** (`GraffApp.swift:42`): `role: Role` (`.user` / `.assistant`), `text`, optional `reasoning`.
-- **`SessionStatus`** (`GraffApp.swift:73`): `working`, `waiting`, `idle`, `done` with symbols/tints.
-- **`TodoStatus`** (`GraffApp.swift:49`): `pending`, `inProgress`, `completed` with SF Symbols.
-
-### Configuration
-- **`project.yml`** (`project.yml:1`): xcodegen spec. Target name `Graff`, iOS platform, deployment target **iOS 26.0**, Swift 6.0, `GENERATE_INFOPLIST_FILE: NO`, device family `1` (iPhone only).
-- **`Info.plist`** (`Info.plist:10`): `CFBundleIdentifier` is `com.codegraff.graff`, `MinimumOSVersion` is `26.0`, and it sets `NSAllowsLocalNetworking` to `true` under `NSAppTransportSecurity` so the simulator can reach `127.0.0.1:8787`.
-
-### Inferred design note
-The Liquid Glass extensions (`glassPanel`, `glassCapsule`) and iOS 26.0 floor suggest this UI is built for the very latest SwiftUI/iOS 26 visual language.
-
----
-
-## 2. `GraffServeClient.swift` — The NDJSON Protocol Client
-
-### Transport contract
-- The client implements the **local `serve` transport** described in `architecture.md` and the TS/Python SDKs (`sdk/ts/remote.ts`, `sdk/py/harness_sdk.py`).
-- Two HTTP calls are required per turn:
- 1. `POST /v1/sessions` → returns `{session_id}` (`GraffServeClient.swift:47`).
- 2. `POST /v1/sessions/{id}` with a JSON payload `{"type": "user", "text": text}` → streamed back as **NDJSON** (one JSON object per line) until a terminal event (`turn` or `error`) (`GraffServeClient.swift:57`).
-
-### Request builder
-- `base` defaults to `http://127.0.0.1:8787` (`GraffServeClient.swift:25`).
-- Always sends `Content-Type: application/json` and `User-Agent: Graff-iOS/0.1` (`GraffServeClient.swift:33`). The comment explicitly states the UA is required because *"CF WAF rejects empty UA on the gateway path"*.
-- Optional bearer token: `Authorization: Bearer <token>` (`GraffServeClient.swift:34`).
-
-### Event decoding
-- `GraffEvent` enum (`GraffServeClient.swift:4`) covers:
- - `.reasoning(String)`
- - `.text(String)`
- - `.toolCall(name: String)`
- - `.turn(text: String, contextTokens: Int, costUSD: Double)`
- - `.error(String)`
- - `.other(String)` (fallback for unknown types)
-- `decode(_:)` (`GraffServeClient.swift:82`) uses `JSONSerialization` to parse each line and switches on the `type` field:
- - `reasoning`, `text`, `tool_call`, `turn`, `error` are mapped explicitly.
- - Anything else becomes `.other(type)`.
-
-### Streaming implementation
-- `streamTurn(sessionID:text:)` returns an `AsyncThrowingStream<GraffEvent, Error>` (`GraffServeClient.swift:57`).
-- It uses `URLSession.shared.bytes(for:)` to get an `AsyncBytes` sequence, iterates `bytes.lines`, and yields decoded events.
-- **Termination rules**: it stops yielding and finishes the stream when it encounters either `.turn` or `.error` (`GraffServeClient.swift:69-70`).
-- Cancellation is wired up: `continuation.onTermination` cancels the `Task` reading the bytes (`GraffServeClient.swift:77`).
-
-### Inferred design note
-A code comment (`GraffServeClient.swift:23`) states: *"The `cube` transport is this same client with a different base URL + a tenant capability header."* The current struct only has `base` and `token`; the capability header is not yet implemented.
-
----
-
-## 3. Main UI: `ChatView.swift` & `SessionsListView.swift`
-
-### `SessionsListView` — Root navigation
-- Wraps a `NavigationStack` containing a `List` of `NavigationLink`s (`SessionsListView.swift:3`).
-- Each row is bound to an `AgentSession` via `ForEach($sessions)` and pushes `ChatView(session: $session)` on tap.
-- `SessionRow` (`SessionsListView.swift:28`) displays:
- - Title + `StatusChip` (tinted capsule with SF Symbol).
- - Model name, todo progress (`done/total`), and `lastActivity` timestamp.
- - A `ProgressView` tinted to the session status.
-- The toolbar has a `+` button (no-op implementation: `Button { }`).
-
-### `ChatView` — Session detail
-- Takes `@Binding var session: AgentSession` and an optional `autoSend: String?` (`ChatView.swift:3`).
-- **Layout** (top to bottom):
- 1. `TaskProgressCard` — shows todos with status symbols, pulse animation on `.inProgress`, and strikethrough for completed items (`ChatView.swift:106`).
- 2. `ScrollViewReader` + `ScrollView` with `LazyVStack` of `MessageBubble`s. Auto-scrolls to the last message when its text changes (`ChatView.swift:23`).
- 3. `PlanDecisionBar` — shown conditionally when `session.planPending` is true; has "Keep planning" and "Implement plan" buttons (`ChatView.swift:185`).
- 4. `Composer` — multiline `TextField` (axis `.vertical`, line limit 1…4) plus send button; disabled while `streaming` is true (`ChatView.swift:205`).
-
-### `MessageBubble` & assistant states
-- `MessageBubble` (`ChatView.swift:136`) left/right aligns based on role.
-- If `message.reasoning` is present, it shows a `Label` with `systemImage: "brain"` in caption italic style.
-- If the assistant message text is empty and reasoning is empty, it renders a `TypingIndicator` (three pulsing dots) so an in-flight turn never looks like a stuck empty bubble (`ChatView.swift:167`).
-
-### Turn lifecycle (`send` → `runTurn`)
-- `send()` (`ChatView.swift:64`) appends a user `ChatMessage`, sets `streaming = true`, `session.status = .working`, and kicks off `runTurn` in a `Task`.
-- `runTurn(_:)` (`ChatView.swift:75`) is `@MainActor`:
- - Lazily creates a remote session via `client.createSession(model: session.model)` if `serveSessionID` is nil.
- - Appends a blank assistant message.
- - Iterates `client.streamTurn` and mutates the message in place:
- - `.reasoning` appends to `message.reasoning`.
- - `.text` appends to `message.text`.
- - `.turn` overwrites `message.text` with the final text.
- - `.error` sets `message.text` to `"Error: " + m`.
- - `.toolCall` and `.other` are ignored (`break`).
- - On catch, appends a transport error message.
- - Always sets `session.status = .idle` in `defer { streaming = false }`.
-
-### Inferred design note
-`ChatView` is purely optimistic/in-memory: there is no CoreData, no SwiftData, no file persistence. Session state survives only while the view hierarchy retains it.
-
----
-
-## 4. Connection to the Core Harness, Data Streamed, and Protocol Handling
-
-### How it connects
-- The iOS app targets `http://127.0.0.1:8787`, which is the default address of `graff serve` (or `harness serve`) running on the host Mac.
-- Because the iOS simulator shares localhost with the host, `127.0.0.1:8787` from the simulator reaches the host's serve process (`GraffServeClient.swift:20` comment).
-
-### What data streams
-- **Request** (turn): `{"type": "user", "text": "<prompt>"}`.
-- **Response**: NDJSON lines, each a JSON object. The iOS client specifically handles:
- - `reasoning` → shown in the bubble as a brain-labeled italic caption.
- - `text` → appended to the assistant bubble.
- - `turn` → final text + metadata (`context_tokens`, `cost_usd`). The client replaces the bubble text with the final `turn.text`.
- - `error` → displayed as `"Error: ..."`.
- - `tool_call` → **ignored** (`ChatView.swift:97`).
-
-### Protocol handling characteristics
-- **Session-oriented**: A `serveSessionID` is created once per `ChatView` and reused for subsequent turns.
-- **Terminal-event driven**: The stream ends on `.turn` or `.error`. This matches the Python/TS SDK behavior (`sdk/py/harness_sdk.py:447`, `sdk/ts/remote.ts:165`).
-- **No interactive tool loop**: Unlike the Python/TS SDKs, the iOS client does not currently handle `ask_user` or multi-step `tool_call` / `tool_result` cycles. It treats the stream as a single-turn text response.
-- **NDJSON parsing**: Uses `JSONSerialization` (not `Codable`) for line-by-line decoding, which is tolerant of unknown fields.
-
-### Verified cross-reference
-The architecture document (`architecture.md`) describes the core harness as a Zig REPL/agent that can run in `--json` mode (stdio) or `serve` mode (HTTP). The iOS client consumes the *serve* bridge, where each session is a real `harness --json` child and one POST equals one protocol request, streamed back as NDJSON (`sdk/ts/remote.ts:8` comment).
-
----
-
-## 5. Build / Automation Scripts
-
-### `build-sim.sh` (`apps/ios/build-sim.sh`)
-- **No Xcode required**. Compiles the app directly with `swiftc` for the iOS simulator.
-- Key steps:
- 1. Sets `TARGET=arm64-apple-ios26.0-simulator` and fetches the iPhoneSimulator SDK path via `xcrun`.
- 2. `rm -rf build && mkdir -p build/Graff.app`.
- 3. Compiles `Graff/Sources/*.swift` into `build/Graff.app/Graff` with `-emit-executable`.
- 4. Copies `Info.plist` into the app bundle.
- 5. Boots the simulator (`xcrun simctl boot`), opens the Simulator app.
- 6. Installs and launches the bundle (`com.codegraff.graff`).
- 7. Waits 4 seconds and screenshots `build/launch.png`.
-- Default device is `iPhone 17 Pro`, overridable via `SIM` env var.
-
-### `autotest.sh` (`apps/ios/autotest.sh`)
-- **Smoke test for the live transport**.
-- Terminates any running instance of the app, then launches it with `--autotest`.
-- Waits 16 seconds for the auto-fired turn to complete.
-- Captures a screenshot to `build/autotest.png`.
-- Used to verify the full stack (simulator → `graff serve` → NDJSON stream → UI) without human interaction.
-
-### `recap.sh` (`apps/ios/recap.sh`)
-- **Multi-stage screenshot capture for documentation/demos**.
-- Launches with `--autotest`, then takes three timed screenshots:
- - `sleep 5` → `build/cap_typing.png` (should catch the `TypingIndicator` while waiting for the first token).
- - `sleep 3` → `build/cap_mid.png` (partial stream).
- - `sleep 8` → `build/cap_reply.png` (final response).
-- These screenshots are likely the ones referenced in the repo (existing `build/cap_*.png` files).
-
----
-
-## Verified vs. Inferred
-
-| Claim | Status | Evidence |
-|-------|--------|----------|
-| The app uses the same NDJSON contract as the TS/Python SDKs | **Verified** | `sdk/ts/remote.ts:8`, `sdk/py/harness_sdk.py`, `GraffServeClient.swift:20` |
-| The app ignores `tool_call` events | **Verified** | `ChatView.swift:97` (`case .toolCall, .other: break`) |
-| Build scripts require no Xcode project | **Verified** | `build-sim.sh` calls `swiftc` directly; `project.yml` is only for ongoing Xcode work (`project.yml:2`) |
-| iOS 26.0 is required | **Verified** | `project.yml:8`, `Info.plist:18` (`MinimumOSVersion` 26.0) |
-| The `cube` transport is planned but not implemented | **Inferred** | `GraffServeClient.swift:23` comment says it is the same client with different base + header, but no header field exists besides `token` |
-| `sampleSessions` is hardcoded demo data | **Verified** | `GraffApp.swift:111` static constant array |
-
----
-
-## 3 Load-Bearing Facts
-
-1. **`GraffServeClient` consumes the serve NDJSON stream via `AsyncThrowingStream`, terminating on `.turn` or `.error` events, and decodes only a subset of the full harness event contract** (`GraffServeClient.swift:57-82`, `ChatView.swift:75-104`).
-2. **The entire build/install/run cycle is scriptable without Xcode** (`build-sim.sh` compiles with `swiftc`, `autotest.sh` gates the live transport, and `recap.sh` captures demo screenshots), making the iOS app a lightweight CI-verified frontend.
-3. **The iOS app is a thin, in-memory client with no persistence layer**: sessions are hardcoded (`sampleSessions`), state lives in `@State`/`@Binding`, and the connection is to `127.0.0.1:8787` on the host Mac via the simulator's shared localhost (`GraffApp.swift:111`, `GraffServeClient.swift:25`, `Info.plist` local-network exception).
-
----
-
-## 1 Open Question
-
-**How will the iOS app handle interactive tool loops** (e.g., `ask_user`, `tool_call`/`tool_result` cycles, or multi-turn streaming) **when `ChatView.runTurn` currently breaks the stream on `.turn`/`.error` and explicitly ignores `.toolCall` events?** The full harness protocol supports these (`sdk/ts/remote.ts` Event union includes `tool_call`, `ask_user`, `tool_result`), but the current UI has no affordances for answering in-flight questions or rendering tool execution steps.
diff --git a/.graff/subagents/sa-005-47447216.md b/.graff/subagents/sa-005-47447216.md
deleted file mode 100644
index d55908e9..00000000
--- a/.graff/subagents/sa-005-47447216.md
+++ /dev/null
@@ -1,192 +0,0 @@
-# subagent sa-005-47447216
-
-- label: Explore examples and docs
-- kind: workflow_task
-- status: ok
-- elapsed_ms: 103678
-- tools: codedb,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,read_file,codedb,codedb,codedb,read_file,read_file,read_file,read_file,read_file,read_file
-
-## task
-
-You are exploring the examples/ and docs/ directories of the codebase. Use the codedb tool and bash as needed to thoroughly understand:
-1. The architecture.md document — what is the overall system architecture described there
-2. The examples/ scripts (dgm_loop.py, replay_judge.py, test_step1.py, edge-worker/) — what do they demonstrate, how do they use the SDK or core
-3. The docs/ (hyperagents.md, install-flow.md, memory-architecture.md, zig-0.17-port-plan.md) — what design decisions and future plans are documented
-4. The packages/diffs/ package — what it does and how it integrates with the GUI
-
-Be thorough and return a structured markdown report.
-
-## report
-
-# Exploration Report: `examples/`, `docs/`, `architecture.md`, and `packages/diffs/`
-
-## 1. `architecture.md` — Overall System Architecture
-
-**`simple-harness`** (also called `graff`) is a terminal agentic loop implemented in ~1,250 lines of Zig 0.16 with **zero third-party dependencies** — only the Zig standard library (`architecture.md:1-5`). It compiles to a single self-contained executable (~1.69 MB on arm64) that talks to multiple LLM providers, runs tools (including subagents and MCP servers) in parallel, and compacts its own context.
-
-### Core loop (`Agent.runTurn`)
-The unit of execution is a single `Agent` struct that owns a message history (`std.json.Array`), a provider, an arena, and the loop methods (`architecture.md:33-37`). The root REPL agent and every subagent are the **same type**; a subagent is just an `Agent` with `sub = true`, a fresh arena, empty history, and `out = null` (`architecture.md:38-40`).
-
-`runTurn` works as follows:
-1. `buildBody` serializes the request for the current provider.
-2. `post` sends it via the thread-safe `std.http.Client.fetch`.
-3. `stepAnthropic` / `stepOpenAI` / `stepResponses` parse the response, echo the assistant turn into history verbatim, collect tool calls, dispatch them via `runTools`, append results, and return either final text (turn done) or `null` (loop again) (`architecture.md:41-48`).
-
-### Providers
-The system decouples **wire format** (`Provider.Kind`: `anthropic`, `openai`, `responses`) from **auth style** (`Provider.Auth`: `x_api_key`, `bearer`) (`architecture.md:50-54`). The `provider_specs` table is the single source of truth. Supported providers include anthropic, codegraff, deepseek, openai, minimax, xiaomi, codex (ChatGPT OAuth), and claude (Claude Code OAuth) (`architecture.md:63-73`). `Provider.context` drives per-model compaction at 80% of the context window.
-
-### Streaming
-Root-agent requests stream on **all three** wire formats using SSE. `request()` decides per call whether to stream (`live = !sub && out != null && !stream_quiet`). After streaming deltas to the user, the buffered events are **reassembled** into the exact non-streaming response shape so that `step*`, history echo, compaction, and `/save`/`/resume` are untouched (`architecture.md:97-112`).
-
-### Tools
-Three kinds, all dispatched through `runTools` (`architecture.md:141`):
-1. **Built-in** (`bash`, `read_file`, `edit_file`, `write_file`, `subagent`, `workflow`) — run on the `std.Io` thread pool. `workflow` is dynamic workflows as data: sequential phases of parallel subagents with `{{prev}}` substitution (`architecture.md:142-147`).
-2. **Meta** (`todo_write`, `todo_read`, `attempt_completion`, `ask_user`) — handled inline by the orchestrator (`handleMeta`), never on a pool thread. They act on the agent/conversation itself (`architecture.md:148-152`).
-3. **MCP** — discovered at runtime from `.mcp.json`, namespaced `mcp__<server>__<tool>`, dispatched to `mcp.Registry.call` (`architecture.md:153-154`).
-
-### Permission model
-State-changing tools run behind a shared `Approvals` struct backed by an `Io.Mutex` (`architecture.md:156-157`):
-- `gateTool` (root only) covers `bash`, `write_file`, `edit_file`, and MCP calls. Unapproved calls prompt on stdin; approval keys are the bash command's first word or the tool name (`architecture.md:159-162`).
-- Subagents are gated structurally: bash is allowlist-only, file writes are path-confined, MCP isn't exposed (`architecture.md:168-170`).
-- **Path confinement** (`confinedPath`): file tools reject absolute paths and `..`, confining them to the cwd subtree. This is **not** bypassed by `/yolo` (`architecture.md:175-176`).
-- **`/yolo`** lifts the prompt gate and the bash cwd-lock, but never lifts `confinedPath` (`architecture.md:178-179`).
-
-### Parallelism and subagents
-`runTools` separates meta calls (inline) from external calls, then fans them out with `io.async` — one `Future` per call — and awaits them in order. Because subagents are external tool calls, three subagents requested in one assistant message run concurrently on the pool, each making its own HTTPS calls through the shared client (`architecture.md:181-187`). Depth is capped at one level; subagents get only the base tool set (no `subagent`, no MCP, no meta tools) (`architecture.md:189-194`).
-
-### MCP client (`src/mcp.zig`)
-The harness is an MCP **client**. `Registry.init` reads `.mcp.json`, spawns stdio servers, performs JSON-RPC handshake (`initialize` → `notifications/initialized` → `tools/list`), and registers each tool. It sanitizes schemas by recursively renaming `oneOf` to `anyOf` because OpenAI's validator rejects `oneOf` outright (`architecture.md:224-236`). `Registry.call` serializes `tools/call` behind an `Io.Mutex` because a server is one bidirectional pipe.
-
-### KV-cache and compaction
-The loop is structured for prefix cache hits: frozen system prompt, append-only message history, comptime tool-list rendering, and explicit `cache_control: {type: ephemeral}` breakpoints for Anthropic (`architecture.md:248-252`). Compaction is client-side and provider-agnostic: at 80% of the model's context window, the harness sends history plus a handoff instruction with no tools, forces a text summary, and replaces history with one user message embedding that summary (`architecture.md:280-285`).
-
-### Other key features
-- **Session persistence**: `/save` serializes `{provider, model, strict, messages}` to `<name>.session.json`; `/resume` parses it back (`architecture.md:257-261`).
-- **Lifecycle hooks**: `pre_tool`, `post_tool`, `turn_end` configured in `.harness/settings.json`. `pre_tool` is the only hook with power: exit 2 blocks the call (`architecture.md:290-327`).
-- **Tracing**: One shared `Tracer` writes to `harness.trace.jsonl` — one JSON line per event, flushed immediately (`architecture.md:329-334`).
-- **Strict mode**: `/strict` forces `tool_choice` so the model must call a tool every turn. Combined with `ask_user` and `attempt_completion`, *every* message is a tool call or tool result (`architecture.md:196-210`).
-
----
-
-## 2. `examples/` Scripts — What They Demonstrate
-
-### `dgm_loop.py` — The minimal Darwin Gödel Machine loop
-This is a ~110-line runnable proof of the DGM checklist using the Python SDK (`examples/dgm_loop.py:1-12`). It demonstrates:
-- **Genome**: a system prompt (auto-captured as `kind:"prompt"` in `harness.trajectory.jsonl`).
-- **Archive + lineage**: loaded from `harness.trajectory.jsonl` with `prompt_sha` parent-child edges.
-- **Modify**: the harness's own model mutates the parent prompt via `h.ask()`.
-- **Evaluate**: uses `replay_eval()` (Step 1 primary gradient) and `llm_tiebreak()` (secondary, capped).
-- **Select**: DGM parent selection via `sigmoid(score − frontier) × 1/(1+children)` (`examples/dgm_loop.py:72-84`).
-- **Score write-back**: `h.score()` with signed provenance (`judge_id`, `artifact_sha`, `eval_set_hash`) and HMAC verification when `GRAFF_SCORE_KEY_FILE` is set (`examples/dgm_loop.py:144-148`, `148-161`).
-
-It uses `Harness(yolo=True)` from `sdk/py/harness_sdk.py` and spawns subagents with per-child `system_prompt` overrides.
-
-### `replay_judge.py` — Step 1: Grounded, out-of-process evolution judge
-This is the primary fitness gradient. It runs a candidate system prompt against a held-out eval set of tasks with **deterministic assertions** — a shell command's exit code or a golden substring in the final report (`examples/replay_judge.py:1-12`). Key properties:
-- **Custody**: the eval set lives outside the editable tree (`GRAFF_EVAL_SET_FILE`); its sha256 is pinned (`GRAFF_EVAL_SET_HASH`). Hash mismatch → exit 3, fail-closed (`examples/replay_judge.py:35-51`).
-- **Hermetic**: each task runs in a fresh scratch directory so file assertions are isolated (`examples/replay_judge.py:93-96`).
-- **Speaks `--json` directly**: dependency-free, no SDK import; it drives `graff --json --yolo` as a subprocess and parses the NDJSON stream (`examples/replay_judge.py:55-91`).
-- **Efficiency gradient**: counts `tool_calls` and `cost` so once all tasks pass, economy (fewer tool calls) discriminates winners (`examples/replay_judge.py:123-130`).
-
-### `test_step1.py` — Proof obligations for the grounded judge
-Offline tests (no model calls) verify structural invariants (`examples/test_step1.py:1-12`):
-1. **Score-band invariant**: a variant failing ANY held-out task can never reach the promotable band (≥ 0.9). The worst gap is verified to be > 0 (`examples/test_step1.py:38-42`).
-2. **Fail-closed**: replay judge missing → score 0.0 (`examples/test_step1.py:44-48`).
-3. **Integrity exits**: missing eval set → exit 2; hash-pin mismatch → exit 3 (`examples/test_step1.py:56-64`).
-4. **Live Goodhart rejection**: a sabotage variant that claims success but does nothing gets a high `h.ask` score, yet `judge()` pins it ≤ 0.8 because the replay suite fails. An honest seed reaches ≥ 0.9 (`examples/test_step1.py:67-86`).
-
-### `edge-worker/` — Remote SDK in Cloudflare Workers
-Proof that the remote SDK runs in the real Workers runtime (`workerd`), where the native harness binary cannot run (`examples/edge-worker/README.md:1-4`). It demonstrates:
-- `src/remote.ts` is a vendored copy of `sdk/ts/remote.ts` (auto-generated from `harness --schema`), using **fetch + Web Streams only** — no `node:` imports (`examples/edge-worker/src/remote.ts:1-5`).
-- `src/index.ts` shows two modes: a default multi-turn session + one-shot, and a streamed one-shot turn via `?q=` query param (`examples/edge-worker/src/index.ts:12-36`).
-- The bridge is `harness serve` running elsewhere; `BRIDGE_URL` and `BRIDGE_TOKEN` are configured via env/secrets.
-
----
-
-## 3. `docs/` — Design Decisions and Future Plans
-
-### `hyperagents.md` — Swarm trajectories & the path to hyperagents
-- **Prompt heterogeneity**: the swarm now supports per-child `system_prompt` overrides (precondition for DGM-style evolution) (`docs/hyperagents.md:1-18`).
-- **Trajectory mapping**: `harness.trajectory.jsonl` holds DGM-archive-tree nodes (`kind:"turn"`, `"subagent"`, `"prompt"`, `"score"`) with `parent`, `prompt_sha`, `prompt_mutated`, and `task` fields (`docs/hyperagents.md:19-42`).
-- **Internal DGM-H design**: the loop itself belongs in SDK code (Python/TS), not the harness. The harness exposes primitives: editable program (`set_system_prompt`), modify (`subagent`/`workflow` with override), evaluate (driver-owned judge), archive (`trajectory.jsonl` + scores), and selection (`sigmoid(...) × 1/(1+children)`) (`docs/hyperagents.md:43-82`).
-- **MAP-Elites**: niches = agent types (e.g. reviewer, researcher). Elites live at `.harness/agents/<niche>.md` — one markdown per cell with frontmatter (`name`, `description`, `score`). The driver promotes challengers that beat the incumbent score (`docs/hyperagents.md:83-112`).
-- **Step 0 — Signed fitness channel**: HMAC-SHA256 over a canonical message (`v1\n{prompt_sha}\n{parent_sha}\n{score:.6f}\n...`) so forged score rows are detectable. Key lives outside cwd; verification is fail-closed (`docs/hyperagents.md:113-145`).
-- **Step 1 — Grounded replay judge**: held-out replay eval with deterministic assertions. Score bands: fail → 0.0; pass_rate < 1.0 → capped at 0.8; all pass → 0.9 + 0.1×efficiency. LLM tie-break only reorders already-passing variants (`docs/hyperagents.md:146-173`).
-- **Step 2 — Federated fleet evolution**: scaffolded but not fully built. The fleet is the archive. Thousands of installs generate/evaluate variants on their own providers. Central infra (`harness-telemetry` worker) does only cheap work: HMAC-verify, artifact re-check, SQL-aggregate, serve elites. Data model includes `harness_elites` table and `GET /v1/elites` endpoint (`docs/hyperagents.md:174-258`).
-
-### `install-flow.md` — Diagnosis & fix
-Documents a bug in the `curl | sh` install path (`docs/install-flow.md:1-3`):
-- **Root cause 1**: tarball layout mismatch. CI nests the binary under `graff-<target>/`, but hand-repacked macOS tarballs ship it flat. `fetch_release` assumed nested, failed with `No such file`, and because it ran inside `if ...`, `set -e` was suppressed, so it returned `rm -rf`'s status (0) and falsely reported "ok" (`docs/install-flow.md:20-28`).
-- **Root cause 2**: companion step called `codegraff.com/install-graff.sh` (the harness installer) instead of `codegraff.com/install.sh` (the tools installer), causing infinite recursion and hang (`docs/install-flow.md:29-33`).
-- **Fix**: robust binary location handling both flat and nested layouts, explicit `return 1` if binary didn't land, correct companion URL, and `curl --max-time 120` bound (`docs/install-flow.md:35-43`).
-
-### `memory-architecture.md` — First-class, evolvable memory layer
-- **Hard constraint**: memory must be **append-only context**, never prefix mutation, to preserve the KV-cache (`docs/memory-architecture.md:1-22`).
-- **MemoryDesign interface**: the evolvable unit with `retrieve`, `update`, and optional `eval` vtable. Fingerprinted (`memory_sha`) like prompts (`docs/memory-architecture.md:23-38`).
-- **Built-in designs**: `null`, `scratchpad`, `episodic`, `structured`, `engram`, `summary-tree`. File-backed under `.harness/memory/` by default; `engram` is an optional MCP upgrade (`docs/memory-architecture.md:39-58`).
-- **Scopes**: `session` (arena), `project` (cwd), `user` (`~/.simple-harness/memory/`), `fleet` (shared, evolved). Fleet scope requires a **code-execution gate** because an evolved memory Design is code that runs (`docs/memory-architecture.md:59-82`).
-- **Evolution**: coordinate-ascent with DGM (mutate persona) and ALMA (mutate memory design). Memory designs are evaluated on long-horizon tasks with outcome-only credit (`docs/memory-architecture.md:83-95`).
-
-### `zig-0.17-port-plan.md` — Zig 0.17 migration plan
-- **Status**: not started; graff stays on Zig 0.16 stable (`docs/zig-0.17-port-plan.md:1-3`).
-- **Dry run result**: the scary part — **182 `std.Io` uses** — showed **no breakage**. Mechanical fixes needed: `b.build_root` removed, `std.ascii.indexOfIgnoreCase` removed, `**` array-repeat operator in flux. Estimated effort: an afternoon (`docs/zig-0.17-port-plan.md:8-14`, `27-30`).
-- **Validation checklist**: `zig build`, `zig build test`, `test-json-controls.py`, real streaming call, GUI smoke test, README badge bump last (`docs/zig-0.17-port-plan.md:75-82`).
-
----
-
-## 4. `packages/diffs/` — What It Does and GUI Integration
-
-### Package purpose
-`@codegraff/diffs` is a **lightweight, dependency-free diff and file-change rendering package** with no Shiki dependency (`packages/diffs/package.json:1-4`). It is built as an ESM module with TypeScript, managed by bun.
-
-### Core modules
-- **`parse.ts`** (`packages/diffs/src/parse.ts`): Parses git-style unified diffs into a structured `ParsedPatch` model (`FileDiff[]`, `DiffHunk[]`, `DiffLine[]`). Tolerant of partial/synthetic patches; normalizes CRLF; handles `diff --git`, `new file mode`, `deleted file mode`, binary files, and hunk headers (`@@ -l,s +l,s @@`). Tracks per-file and total `additions`/`deletions` stats.
-- **`highlight.ts`** (`packages/diffs/src/highlight.ts`): A tiny, dependency-free syntax tokenizer per line. Supports 11 languages (`ts`, `js`, `py`, `rs`, `go`, `zig`, `json`, `css`, `shell`, `md`, `plain`). Tokenizes into `keyword`, `string`, `comment`, `number`, `punct`, `plain`. Per-line only — multi-line strings/comments are not tracked.
-- **`wordDiff.ts`** (`packages/diffs/src/wordDiff.ts`): Intra-line word diff using LCS (longest common subsequence). Splits lines into word-ish tokens, then computes `DiffSegment[]` (`same`/`added`/`removed`). Has a **200,000 cell budget**; if the LCS table would exceed that, it bails out to a single removed/added segment to avoid hanging/OOMing the tab during render.
-- **`types.ts`** (`packages/diffs/src/types.ts`): Shared TypeScript interfaces for `DiffLine`, `DiffHunk`, `FileDiff`, `ParsedPatch`, `DiffSegment`, `DiffStats`.
-
-### React components
-- **`PatchDiff.tsx`** (`packages/diffs/src/react/PatchDiff.tsx`): Top-level component. Takes a raw git patch string, parses it with `useMemo(parsePatch)`, and renders a list of files with optional file headers and stats badges (`added`/`deleted`/`renamed`).
-- **`DiffBody.tsx`** (`packages/diffs/src/react/DiffBody.tsx`): Renders the body of a single file. Applies **word-level intra-line diffing** by pairing consecutive deletion/addition runs and running `diffWords()` on each pair. Renders hunks with line numbers, `+`/`-`/`` signs, and syntax-highlighted content via `tokenizeLine`. For `DiffSegment` lines, it renders only the side that owns the change (e.g., `removed` spans only on the before side, `added` only on the after side).
-- **`FilesChanged.tsx`** (`packages/diffs/src/react/FilesChanged.tsx`): A collapsible file list. Each row shows path, badge, stats, and a toggle caret. Clicking expands to show the `PatchDiff` for that file. Uses `memo` for row performance.
-
-### Styling
-- `src/style.css` provides the base CSS classes (`cgd-root`, `cgd-file`, `cgd-line`, `cgd-gutter`, `cgd-word`, `cgd-tok`, etc.) (`packages/diffs/src/style.css`).
-- The GUI imports the style in `gui/src/main.tsx` (`import '@codegraff/diffs/style.css'`) and binds theme tokens in `gui/src/styles/diffs.css` so diffs adapt to light/dark mode.
-
-### GUI integration
-The package is used in two main GUI locations:
-
-1. **Chat activity results** (`gui/src/components/chat/activity-results/FileDiffResult.tsx:3`): Imports `PatchDiff` from `@codegraff/diffs/react`. Displays a file diff inside an `ActivityResultCard` with an "open in editor" button. Uses `options={{ lineDiffType: "word", showFileHeader: false }}` (`gui/src/components/chat/activity-results/FileDiffResult.tsx:91-95`).
-2. **Workspace changes pane** (`gui/src/components/workspace-board/ChangesPane.tsx:11`): Imports `PatchDiff` to render session file changes in a collapsible sidebar. Each `ChangeRow` uses `Collapsible` to expand/collapse the diff. Also uses `lineDiffType: "word"` and `showFileHeader: false` (`gui/src/components/workspace-board/ChangesPane.tsx:88-94`, `176-180`).
-
-The GUI's `package.json` declares `"@codegraff/diffs": "workspace:*"` and has a `"build:deps"` script that builds the diffs package first (`gui/package.json:11`, `20`).
-
----
-
-## Verified vs. Inferred
-
-| Claim | Status | Evidence |
-|---|---|---|
-| The harness is a single Zig binary with zero third-party deps | **Verified** | `architecture.md:1-5`, `build.zig` |
-| `dgm_loop.py` uses the Python SDK's `Harness` class and `h.score()` | **Verified** | `examples/dgm_loop.py:16`, `144-148` |
-| `replay_judge.py` speaks `--json` directly without SDK imports | **Verified** | `examples/replay_judge.py:55-91` (no `harness_sdk` import) |
-| `test_step1.py` verifies fail-closed behavior and score-band invariant | **Verified** | `examples/test_step1.py:38-64` |
-| `edge-worker` uses fetch + Web Streams with no node: imports | **Verified** | `examples/edge-worker/src/remote.ts:1-5`, `src/index.ts:12-36` |
-| `@codegraff/diffs` is used in GUI chat results and changes pane | **Verified** | `gui/src/components/chat/activity-results/FileDiffResult.tsx:3`, `gui/src/components/workspace-board/ChangesPane.tsx:11` |
-| The DGM federated fleet loop (Step 2) is fully implemented | **Inferred** | `docs/hyperagents.md:174-258` says "scaffolded" — migration and endpoints exist, but LCB + anomaly-ejection + auto-promote logic are TODO. |
-| The `MemoryDesign` interface is already in the Zig source | **Inferred** | `docs/memory-architecture.md:23-38` proposes the shape; it is a design document, not yet implemented code. |
-
----
-
-## 3 Most Load-Bearing Facts
-
-1. **The harness is a single ~1.7 MB Zig binary with zero dependencies** that runs an agentic loop with streaming, multi-provider support, parallel subagents, MCP client, and client-side compaction — all in ~1,250 lines of Zig 0.16 (`architecture.md:1-5`, `build.zig`).
-2. **The DGM evolution loop is closed and grounded** through a signed fitness channel (HMAC-SHA256) and a held-out replay judge with deterministic assertions, so that an LLM cannot "charm" its way to a high score without actually passing the tasks (`docs/hyperagents.md:113-173`, `examples/replay_judge.py:1-12`, `examples/test_step1.py:38-64`).
-3. **`@codegraff/diffs` is a zero-dependency diff rendering package** used by the GUI in both chat activity results and the workspace changes pane, featuring git patch parsing, per-line syntax highlighting, and LCS-based intra-line word diffing with a render-time cell budget to prevent tab hangs (`packages/diffs/src/parse.ts`, `packages/diffs/src/wordDiff.ts`, `gui/src/components/workspace-board/ChangesPane.tsx:11`).
-
----
-
-## 1 Open Question
-
-**How does the GUI plan to handle the federated fleet evolution telemetry and elite pulling?** The docs scaffold `GET /v1/elites` and SDK `pull_elites()` methods, but the GUI code (React + Tauri) does not yet appear to call these. Is the GUI intended to remain a passive consumer of the local harness binary, or will it eventually participate in the fleet loop by prompting users to opt-in and surfacing evolved personas?
diff --git a/.graff/subagents/sa-005-4f629496.md b/.graff/subagents/sa-005-4f629496.md
deleted file mode 100644
index ff7f59f7..00000000
--- a/.graff/subagents/sa-005-4f629496.md
+++ /dev/null
@@ -1,257 +0,0 @@
-# subagent sa-005-4f629496
-
-- label: Branch binary mismatch
-- kind: workflow_task
-- status: ok
-- elapsed_ms: 221945
-- tools: codedb,bash,codedb,codedb,bash,codedb,codedb,bash,codedb,codedb,bash,codedb,codedb,bash,codedb,codedb,codedb,bash,codedb,codedb,bash,codedb,bash,bash,bash,bash,bash,bash,bash,bash,bash
-
-## task
-
-Investigate the current git branch/worktree state and built binary provenance for `/Users/blackfloofie/codegraff`. Use codedb for code navigation where relevant, and bash for git/build metadata. Determine whether the current checkout/branch (`chore/release-0.0.161-sdk-login-assets` vs downstream `feat/ios-companion-app`) could explain missing `[gpt-5.5]({folder_name})` UX. Report concise findings and exact commands/output evidence.
-
-## report
-
-## Verified findings
-
-### 1) Current worktree is **not** `feat/ios-companion-app`; it is `chore/release-0.0.161-sdk-login-assets`
-
-Command:
-
-```sh
-cd /Users/blackfloofie/codegraff &&
-pwd &&
-git status --short --branch &&
-git branch --show-current &&
-git rev-parse HEAD
-```
-
-Output:
-
-```text
-/Users/blackfloofie/codegraff
-## chore/release-0.0.161-sdk-login-assets...origin/chore/release-0.0.161-sdk-login-assets
-?? .graff/
-?? apps/
-chore/release-0.0.161-sdk-login-assets
-85ccf25a29a5e9fd78c492a3ff13c5c002144ad6
-```
-
-So the checkout is clean with respect to tracked files, but has untracked `.graff/` and `apps/`.
-
-`git worktree list --porcelain` confirms this worktree is on `refs/heads/chore/release-0.0.161-sdk-login-assets` at `85ccf25`, while `release/0.0.161` is checked out separately at `/Users/blackfloofie/codegraff-rel017`.
-
----
-
-### 2) Branch comparison: `feat/ios-companion-app` lacks the current-folder prompt UX; current branch has it
-
-Command:
-
-```sh
-git log --oneline --decorate --left-right --cherry-pick \
- chore/release-0.0.161-sdk-login-assets...feat/ios-companion-app --max-count=80
-```
-
-Relevant output:
-
-```text
-< 85ccf25 (HEAD -> chore/release-0.0.161-sdk-login-assets, origin/chore/release-0.0.161-sdk-login-assets) fix(gui): handle expired provider auth
-< 5d0e374 fix(gui): auto-detect CLI provider login
-...
-> f278fed (origin/feat/ios-companion-app, feat/ios-companion-app) feat(gui): surface ultracode mode
-> 904bfa8 feat: add ultracode mode and trajectory usage
-> 782e707 docs(AGENTS): GUI and engine must stay in lockstep — rebuild + redeploy graff on protocol changes
-...
-< ba861df Add pwd command and show workspace folder
-< 00e281a fix: label cwd in repl prompt
-```
-
-Command:
-
-```sh
-git branch -a --contains ba861df | grep -E 'chore/release|feat/ios|release/0.0.161|HEAD|main'
-git branch -a --contains 00e281a | grep -E 'chore/release|feat/ios|release/0.0.161|HEAD|main'
-```
-
-Output:
-
-```text
-* chore/release-0.0.161-sdk-login-assets
-+ release/0.0.161
- remotes/origin/HEAD -> origin/main
- remotes/origin/chore/release-0.0.161-sdk-login-assets
- remotes/origin/main
- remotes/origin/release/0.0.161
-* chore/release-0.0.161-sdk-login-assets
-+ release/0.0.161
- remotes/origin/chore/release-0.0.161-sdk-login-assets
- remotes/origin/release/0.0.161
-```
-
-Notably, `feat/ios-companion-app` is absent from both `--contains` results.
-
-Current branch source contains current-folder state and prompt rendering:
-
-- `src/main.zig:2559-2560` defines `g_cwd_display` as “Human-facing current workspace folder shown in the REPL prompt.”
-- `src/main.zig:4573-4580` populates it from real cwd / `PWD` and prints startup `folder: ...`.
-- `src/main.zig:8247-8255` renders the prompt with `· cwd {g_cwd_display}` beside the model.
-
-Evidence excerpt from current `src/main.zig`:
-
-```text
-8247 try w.print("\n{s}[{s}{s}{s}{s}{s} · cwd {s}{s}{s} · {d}/{d}k tok ...
-8248 style.reset, g_cwd_display, ...
-8253 try w.print("\n{s}[{s}{s}{s}{s}{s} · cwd {s}{s}{s}{s}]{s} ...
-8255 style.reset, g_cwd_display, ...
-```
-
-By contrast, `feat/ios-companion-app` prompt rendering lacks cwd/folder:
-
-Command:
-
-```sh
-git show feat/ios-companion-app:src/main.zig | nl -ba | sed -n '7738,7767p'
-```
-
-Relevant output:
-
-```text
-7749 const plain = std.fmt.bufPrint(&pbuf, "[{s}{s} · {d}/{d}k tok ({d}%){s}{s}] › ", .{
-7750 self.provider.model, flag, self.last_context_tokens, threshold / 1000, pct, cached, cost,
-...
-7760 const plain = std.fmt.bufPrint(&pbuf, "[{s}{s}{s}] › ", .{ self.provider.model, flag, cost }) catch "";
-...
-7762 try w.print("\r\n{s}[{s}{s}{s}{s}{s}{s}]{s} {s}›{s} ", .{
-7763 style.dim, style.reset, style.cyan, self.provider.model, flag, style.dim, cost,
-```
-
-So yes: a build from downstream `feat/ios-companion-app` can explain missing `[gpt-5.5] + folder/cwd` prompt UX. The current checkout source cannot, because it has the cwd prompt code.
-
----
-
-### 3) Built binary provenance is mixed/stale relative to current checkout
-
-Command:
-
-```sh
-command -v graff
-which -a graff
-ls -l ./zig-out/bin 2>/dev/null
-./zig-out/bin/graff --version 2>&1 || true
-graff --version 2>&1 || true
-```
-
-Output:
-
-```text
-/Users/blackfloofie/bin/graff
-/Users/blackfloofie/bin/graff
-total 14680
--rwxr-xr-x@ 1 blackfloofie staff 7514632 21 Jun 17:07 graff
-simple-harness v0.0.14-7-g782e707-dirty
-graff v0.0.161-18-g7bea7e7
-```
-
-Detailed binary metadata:
-
-```sh
-for b in ./zig-out/bin/graff /Users/blackfloofie/bin/graff; do
- ls -l "$b"
- stat -f 'mtime=%Sm size=%z inode=%i' "$b"
- shasum -a 256 "$b"
- "$b" --version
-done
-```
-
-Output:
-
-```text
---- ./zig-out/bin/graff
--rwxr-xr-x@ 1 blackfloofie staff 7514632 21 Jun 17:07 ./zig-out/bin/graff
-mtime=Jun 21 17:07:52 2026 size=7514632 inode=35841595
-cd06953adc3a814f39103e489b66f625c99978f5e0be227c952f5325da5590d6 ./zig-out/bin/graff
-simple-harness v0.0.14-7-g782e707-dirty
-
---- /Users/blackfloofie/bin/graff
--rwxr-xr-x@ 1 blackfloofie staff 7630808 21 Jun 13:57 /Users/blackfloofie/bin/graff
-mtime=Jun 21 13:57:14 2026 size=7630808 inode=35694914
-0b4b58e6d1aafda389006bd04b90e7d205bcd356f6d52c3605b4647ad714f961 /Users/blackfloofie/bin/graff
-graff v0.0.161-18-g7bea7e7
-```
-
-Command:
-
-```sh
-git name-rev --name-only 782e707 7bea7e7 85ccf25 f278fed
-git show --no-patch --format='%h %D %s' 782e707 7bea7e7 85ccf25 f278fed
-```
-
-Output:
-
-```text
-remotes/origin/feat/ios-companion-app~2
-feat/live-agent-tree~4
-chore/release-0.0.161-sdk-login-assets
-remotes/origin/feat/ios-companion-app
-
-782e707 docs(AGENTS): GUI and engine must stay in lockstep — rebuild + redeploy graff on protocol changes
-7bea7e7 Merge release/0.0.16 into release/0.0.161
-85ccf25 HEAD -> chore/release-0.0.161-sdk-login-assets, origin/chore/release-0.0.161-sdk-login-assets fix(gui): handle expired provider auth
-f278fed origin/feat/ios-companion-app, feat/ios-companion-app feat(gui): surface ultracode mode
-```
-
-The important point: `./zig-out/bin/graff` is stamped from `782e707-dirty`, i.e. close to downstream `feat/ios-companion-app`, and that branch lacks the cwd prompt. The installed CLI `/Users/blackfloofie/bin/graff` is stamped from `7bea7e7`, which does have the cwd prompt:
-
-Command:
-
-```sh
-git grep -n 'g_cwd_display\|cwd {s}\|folder:' 7bea7e7 -- src/main.zig
-```
-
-Output:
-
-```text
-7bea7e7:src/main.zig:2560:var g_cwd_display: []const u8 = ".";
-7bea7e7:src/main.zig:4573: g_cwd_display = if (Io.Dir.cwd().realPath(io, &cwd_buf)) |n|
-7bea7e7:src/main.zig:4579: try out.print("{s}codegraff{s} · folder: {s}{s}{s} ...
-7bea7e7:src/main.zig:8246: try w.print("\n{s}[{s}{s}{s}{s}{s} · cwd {s}{s}{s} ...
-7bea7e7:src/main.zig:8252: try w.print("\n{s}[{s}{s}{s}{s}{s} · cwd {s}{s}{s}{s}]{s} ...
-```
-
----
-
-### 4) GUI binary resolution can prefer stale `./zig-out/bin/graff` over installed `~/bin/graff`
-
-The GUI runtime resolver first checks an explicit `CODEGRAFF_GUI_BINARY`, then bundled sidecar, then dev `../../zig-out/bin/graff`, then known install locations like `~/bin/graff` and `~/.local/bin/graff`:
-
-- Explicit override: `gui/src-tauri/src/runtime/simple.rs:3240-3254`
-- Bundled sidecar next to app executable: `gui/src-tauri/src/runtime/simple.rs:3255-3266`
-- Dev build `../../zig-out/bin/graff`: `gui/src-tauri/src/runtime/simple.rs:3269-3274`
-- Known install locations including `~/bin/graff`: `gui/src-tauri/src/runtime/simple.rs:3276-3288`
-
-This means a dev-launched GUI from this checkout can select the stale `./zig-out/bin/graff` before the newer installed `/Users/blackfloofie/bin/graff`.
-
-That is a strong explanation path for missing folder/cwd prompt UX despite the current source having the feature.
-
----
-
-## Inference
-
-- If the missing `[gpt-5.5]({folder_name})` UX was observed in a GUI/dev run from `/Users/blackfloofie/codegraff`, the most likely cause is **binary provenance**, not tracked source state: the GUI resolver can prefer `./zig-out/bin/graff`, and that binary is built from `782e707-dirty`, near `feat/ios-companion-app`, where prompt rendering lacks cwd/folder.
-- If the missing UX was observed from terminal `graff`, then `/Users/blackfloofie/bin/graff` should be checked interactively, because its stamped commit `7bea7e7` contains cwd prompt code. The non-interactive `--version` evidence alone says it should have the feature, but I did not run an interactive TTY capture.
-
----
-
-## Bottom line
-
-Yes, `chore/release-0.0.161-sdk-login-assets` vs downstream `feat/ios-companion-app` **can explain** missing folder-name prompt UX **if the binary being run came from the downstream/stale lineage**. The current checkout source has the cwd/folder prompt; the downstream branch does not. The local `./zig-out/bin/graff` is in fact stamped `v0.0.14-7-g782e707-dirty`, and GUI dev resolution can prefer that stale binary over installed `~/bin/graff`.
-
-## 3 load-bearing facts
-
-1. Current worktree is `chore/release-0.0.161-sdk-login-assets` at `85ccf25`, not `feat/ios-companion-app`; tracked files are not dirty.
-2. `feat/ios-companion-app` lacks the cwd/folder prompt code; current branch contains it in `src/main.zig:2559-2560`, `src/main.zig:4573-4580`, and `src/main.zig:8247-8255`.
-3. `./zig-out/bin/graff` is stale/downstream-adjacent: `simple-harness v0.0.14-7-g782e707-dirty`, and GUI dev resolver checks `../../zig-out/bin/graff` before `~/bin/graff` per `gui/src-tauri/src/runtime/simple.rs:3269-3288`.
-
-## Open question
-
-Which exact executable did the observed failing UX use at runtime: bundled app sidecar, `./zig-out/bin/graff`, `/Users/blackfloofie/bin/graff`, or a `CODEGRAFF_GUI_BINARY` override?
diff --git a/.graff/subagents/sa-006-5eefb3a1.md b/.graff/subagents/sa-006-5eefb3a1.md
deleted file mode 100644
index c8f0ec06..00000000
--- a/.graff/subagents/sa-006-5eefb3a1.md
+++ /dev/null
@@ -1,107 +0,0 @@
-# subagent sa-006-5eefb3a1
-
-- label: Ultracode interaction audit
-- kind: workflow_task
-- status: ok
-- elapsed_ms: 215420
-- tools: codedb,codedb,codedb,bash,bash,codedb,codedb,codedb,codedb,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash,bash
-
-## task
-
-Audit whether the ultracode changes could have removed or overwritten a TUI prompt badge format like `[gpt-5.5]({folder_name})`. Use codedb search/symbol/callers/outline first to locate ultracode prompt badge changes in `src/main.zig`, then inspect diffs/history if useful. Report whether ultracode caused the regression, and if so how; if not, identify the more likely culprit.
-
-## report
-
-I used codedb first:
-
-- `codedb search ultracode` found the relevant docs/GUI/runtime hits and pointed to `src/main.zig`.
-- `codedb outline src/main.zig` failed because `src/main.zig` is not indexed in codedb in this checkout, so I fell back to git/file inspection.
-
-## Current TUI prompt format
-
-Current `src/main.zig` prints the REPL prompt in `Agent.prompt` as:
-
-- `src/main.zig:8248` for context-token prompt:
- ```zig
- "\n{s}[{s}{s}{s}{s}{s} · cwd {s}{s}{s} · {d}/{d}k tok ..."
- ```
-- `src/main.zig:8255` for normal prompt:
- ```zig
- "\n{s}[{s}{s}{s}{s}{s} · cwd {s}{s}{s}{s}]{s} {s}›{s} "
- ```
-
-So the current format is effectively:
-
-```text
-[gpt-5.5 · cwd /path/to/folder] ›
-```
-
-not:
-
-```text
-[gpt-5.5](folder_name) ›
-```
-
-## Did ultracode remove/overwrite `[gpt-5.5]({folder_name})`?
-
-I do **not** see a defensible current-branch regression caused by the ultracode commits.
-
-Concrete history:
-
-1. `ba861df Add pwd command and show workspace folder` added the folder display to `Agent.prompt`, but it added it **inside the square brackets** with a middle-dot separator:
- ```diff
- - [{model...}]
- + [{model...} · {g_cwd_display}]
- ```
- It did not implement `[model](folder)`.
-
-2. `00e281a fix: label cwd in repl prompt` changed that same display to include the literal label `cwd`:
- ```diff
- - [model · /path]
- + [model · cwd /path]
- ```
-
-3. The current-branch ultracode TUI commits I inspected:
- - `529c65a feat: shine the ultracode codeword banner`
- - `b0a0de4 feat: shine the ultracode codeword on the input line too`
- - `9104c87 feat: wave the ultracode input shine across letters over time`
- - `91a7c2e feat: softer ultracode wave — gentler pulse + smooth interpolated hues`
- - `460a400 feat: /ultracode slash command for persistent ultracode mode`
-
- do **not** rewrite the prompt badge format in `Agent.prompt`. `460a400` adds `/ultracode`, `root.ultracode_mode`, JSON control handling, and codeword behavior, but the shown diff does not touch the prompt-printing hunk.
-
-## Suspicious non-current ultracode branch
-
-There is one ultracode-related commit in `--all` history that *would* be suspicious if someone were auditing a different branch:
-
-- `904bfa8 feat: add ultracode mode and trajectory usage`
-
-That commit rewrites `Agent.prompt` to add an ultracode flag and prompt-width bookkeeping. Its parent did **not** have the cwd prompt changes, so its prompt hunk has no folder/cwd display. However:
-
-```text
-git merge-base --is-ancestor 904bfa8 HEAD
-# exit 1
-```
-
-So `904bfa8` is **not an ancestor of the current HEAD** I audited. It is not the cause of the current checkout’s prompt format.
-
-## More likely culprit
-
-If the expected format was specifically:
-
-```text
-[gpt-5.5]({folder_name})
-```
-
-then the likely culprit is not ultracode. The repo history I checked does not show that exact format ever existing in `src/main.zig`.
-
-The current visible behavior is more directly explained by:
-
-- `ba861df` introducing folder display as `[model · /path]`, and then
-- `00e281a` changing it to `[model · cwd /path]`.
-
-Those commits changed the prompt badge shape around the workspace display; ultracode did not.
-
-## Verdict
-
-No defensible defect found that current-branch ultracode changes removed or overwrote `[gpt-5.5]({folder_name})`. The more likely culprit is the folder-prompt work itself, especially `ba861df`/`00e281a`, which implemented/labeled cwd inside the bracketed badge rather than using a parenthesized folder suffix.
diff --git a/.graff/subagents/sa-006-c62e5331.md b/.graff/subagents/sa-006-c62e5331.md
deleted file mode 100644
index 0a353410..00000000
--- a/.graff/subagents/sa-006-c62e5331.md
+++ /dev/null
@@ -1,1499 +0,0 @@
-# subagent sa-006-c62e5331
-
-- label: Synthesize codebase overview
-- kind: workflow_task
-- status: ok
-- elapsed_ms: 127256
-- tools: (none)
-
-## task
-
-You are synthesizing a unified codebase overview from the parallel exploration reports below. Create a single, comprehensive markdown document that covers:
-
-1. **Project identity and purpose**: What is this project overall? What problem does it solve?
-2. **High-level architecture**: How do the major components (Zig core, GUI frontend, Tauri backend, SDKs, iOS app) fit together? Include a component diagram in text form.
-3. **Data flow / protocol**: How does data move between components? What protocols are used (NDJSON, WebSocket, Tauri commands, etc.)?
-4. **Component deep-dives**: For each major area, summarize:
- - Zig core: responsibilities, entry points, key modules, build
- - GUI frontend: tech stack, key state management, main views
- - Tauri backend: commands, runtime management, bridge to Zig core
- - SDKs: Python and TS APIs, generation, use cases
- - iOS app: structure, protocol client, UI
-5. **Key patterns and design decisions**: Notable patterns observed across the codebase
-6. **Notable files and their roles**: A curated list of "if you want to understand X, read Y"
-7. **Tech stack summary**: Languages, frameworks, build tools per component
-
-The input reports from Phase 1 are provided below. Integrate them, resolve any overlaps, and produce a coherent narrative. Be specific but concise.
-
-### Explore Zig core (src/)
-Here is the structured markdown report based on my thorough exploration of the Zig core.
-
----
-
-# Zig Core Report: `simple-harness` / `graff`
-
-## 1. Main Entry Point and Overall Architecture
-
-### Entry Point
-- **`src/main.zig:3991`**: `pub fn main(init: std.process.Init) !void` is the program entry point.
-- It parses CLI flags, loads API keys from environment, login files, or the macOS keychain, initializes an HTTP client, and then enters one of three modes:
- 1. **One-shot (`-p` / bare positional)**: Runs a single prompt, prints the result, exits.
- 2. **Interactive REPL**: Reads stdin line-by-line, maintains conversation history, and loops through `Agent.runTurn()`.
- 3. **`serve` subcommand**: Binds an HTTP server that spawns `harness --json` children per session.
-
-### Architecture of `src/main.zig`
-The file is a ~12,950-line monolithic Zig module (no sub-files) organized roughly as:
-
-| Layer | Lines | Responsibility |
-|-------|-------|--------------|
-| Top-level constants/schemas | 1–450 | Tool specs, system prompts, model tables, pricing |
-| Provider/key/auth logic | 450–900 | `Provider`, `Keys`, `ProviderSpec`, OAuth loaders |
-| JSON schema / help / version | 900–1400 | `emitSchema`, `schema_protocol_json` |
-| Telemetry / OTLP | 1400–2000 | `Telemetry` struct, OpenTelemetry-style HTTP posting |
-| Skills / hooks / approvals | 2000–2500 | `SkillDef`, `Hook`, `Approvals` |
-| Utility fns | 2500–3800 | Cost tracking, file I/O, `runCapped`, `runSub` |
-| `main()` | 3900–4600 | CLI parsing, session setup, key loading, agent init |
-| REPL / command dispatch | 4600–5600 | `handleCommand`, history, `readLine`, line editor |
-| Agent core | 7400–8700 | `Agent` struct, `runTurn`, `request`, `buildBody` |
-| HTTP POST / streaming | 8700–9100 | `postStream`, `postWatched`, stall-watchdog `Select` arms |
-| Tool execution | 10600–11700 | `execTool`, `execToolInner`, builtins |
-| Subagent / workflow | 11600–12600 | `runSub`, `runWorkflow`, fan-out via `Io.async` |
-| `serve` HTTP bridge | 6600–7200 | `serveMain`, `serveConn`, `serveRequest`, `serveMessage` |
-| Tests | 12500+ | Inline `test` blocks |
-
-### Architecture of `src/mcp.zig`
-- **`src/mcp.zig:1`**: A minimal MCP (Model Context Protocol) client over stdio.
-- **`src/mcp.zig:40`**: `pub const Registry` is the primary data structure. It holds:
- - `servers: []*Server` — spawned child processes
- - `tools: []Tool` — discovered tools qualified as `mcp__<server>__<tool>`
- - `mutex: Io.Mutex` — serializes JSON-RPC per server (one bidirectional pipe)
-- **`src/mcp.zig:56`**: `Registry.init()` reads `.mcp.json`, spawns each server, runs `initialize` → `notifications/initialized` → `tools/list` handshake, and collects discovered tools.
-- **`src/mcp.zig:224`**: `Registry.call()` dispatches a tool call via `tools/call` JSON-RPC, with `oneOf` → `anyOf` schema rewriting for OpenAI compatibility.
-
-### Relationship between `mcp.zig` and `main.zig`
-- `main.zig:37` imports `mcp.zig` as `const mcp = @import("mcp.zig");`
-- The root `Agent` struct (`src/main.zig:7461`) holds `registry: ?*mcp.Registry`.
-- At startup (`main.zig:4350`), `mcp.Registry.init()` is called if the user consents (or `--yolo` is passed). The registry is then threaded into the `Agent`.
-- In `Agent.runTools()` (`src/main.zig:8081`), external tool calls that are not built-in or meta are dispatched via `execTool()` on `Io.async` pool threads. `execTool` passes the registry pointer in `ToolCtx` (`src/main.zig:10695`), and `execToolInner` routes MCP-qualified names (`mcp__*`) to `mcp.Registry.call()` (`src/main.zig:11411` area).
-
----
-
-## 2. What the Core Zig Binary Does
-
-The binary is a **dual-mode AI agent harness**:
-
-### A. CLI / REPL (`--json` or TTY)
-- **Agentic loop**: Reads user input, POSTs to LLM APIs (Anthropic Messages, OpenAI Chat Completions, or OpenAI Responses/Codex), receives tool calls, executes them (in parallel when safe), and feeds results back into the conversation.
-- **Built-in tools**: `bash`, `read_file`, `edit_file`, `write_file`, `webfetch`, `codedb`, plus background bash helpers (`bash_output`, `bash_kill`).
-- **Meta tools**: `todo_write`, `todo_read`, `ask_user`, `attempt_completion` — handled inline by the orchestrator, not on pool threads.
-- **Advanced tools**: `subagent` (spawns isolated child agents) and `workflow` (multi-phase parallel fan-out).
-- **MCP integration**: Dynamically discovers and calls tools from `.mcp.json` servers.
-- **Permission gating**: Bash and MCP tool calls require user approval unless `/yolo` or `--yolo` is set.
-- **Tracing**: Every API call and tool execution is appended to `harness.trace.jsonl`.
-
-### B. HTTP Server (`harness serve`)
-- **`src/main.zig:6694`**: `fn serveMain(...)` binds an HTTP/1.1 server (default `127.0.0.1:8787`).
-- Each session is a **spawned child** of the same binary running `harness --json`.
-- The HTTP bridge speaks **NDJSON** over chunked transfer encoding:
- - `POST /v1/sessions` → spawns child, returns `session_id`.
- - `POST /v1/sessions/{id}` → forwards one JSON protocol line to the child's stdin, streams stdout events back as NDJSON.
- - `DELETE /v1/sessions/{id}` → graceful close.
-- CORS is enabled only when a `--token` bearer token is configured (`src/main.zig:6740`).
-- The serve protocol is documented in `schema_protocol_json` at `src/main.zig:79`.
-
-### C. One-shot (`-p` / bare prompt)
-- Runs a single prompt to completion with no human interaction, outputs final text to stdout, exits.
-
----
-
-## 3. Key Functions and Data Structures
-
-### Core Data Structures
-
-| Struct | File:Line | Role |
-|--------|-----------|------|
-| `Agent` | `src/main.zig:7461` | The orchestrator: holds message history, provider, HTTP client, tools, streaming state, markdown renderer state, and MCP registry pointer. |
-| `ToolCall` | `src/main.zig:7413` | `{id, name, input}` — a model-requested tool invocation. |
-| `ExecResult` | `src/main.zig:7420` | `{text, is_error, ms}` — outcome of a tool run, arena-owned. |
-| `ToolOutput` | `src/main.zig:10687` | `{text, is_error, ms}` — gpa-owned result from `execTool`. |
-| `ToolCtx` | `src/main.zig:10695` | Everything passed to `execTool` on a pool thread: `gpa`, `io`, `client`, `provider`, `registry`, `approvals`, `tracer`, `snapshots`. |
-| `Provider` | `src/main.zig:801` | `{id, kind, auth, url, api_key, model, context}` — wire-format abstraction for Anthropic, OpenAI, and Responses APIs. |
-| `Keys` | `src/main.zig:823` | Holds optional API keys for all providers; resolves `providerFor` and `defaultProvider`. |
-| `mcp.Tool` | `src/mcp.zig:16` | `{server_index, original_name, qualified_name, description, input_schema}` |
-| `mcp.Server` | `src/mcp.zig:40` | `{name, child, stdin_writer, stdout_reader, next_id, protocol_version}` |
-| `mcp.Registry` | `src/mcp.zig:46` | `{gpa, io, arena_state, mutex, servers, tools}` |
-
-### Key Functions
-
-| Function | File:Line | Description |
-|----------|-----------|-------------|
-| `main()` | `src/main.zig:3991` | Entry point: flag parsing, key loading, agent init, mode dispatch. |
-| `Agent.runTurn()` | `src/main.zig:7611` | Main loop: `request()` → `stepAnthropic`/`stepOpenAI`/`stepResponses` → `runTools` → repeat until `attempt_completion` or error. |
-| `Agent.request()` | `src/main.zig:7642` | Builds request body, retries with backoff on transport errors, calls `postStream` (live) or `postWatched` (subagent/non-streaming). |
-| `Agent.postStream()` | `src/main.zig:8760` | Streaming HTTP POST with SSE/NDJSON parsing; races reads against the stall-watchdog. |
-| `Agent.runTools()` | `src/main.zig:8081` | Dispatches tool calls: meta tools inline, external tools via `Io.async` pool. |
-| `execTool()` | `src/main.zig:10953` | Pool-thread entry point; routes to `execToolInner`. |
-| `execToolInner()` | `src/main.zig:11411` | Routes builtins (bash, read, edit, write, webfetch, codedb), meta, subagent, workflow, and MCP tools. |
-| `mcp.Registry.init()` | `src/mcp.zig:56` | Spawns MCP servers from `.mcp.json`, handshakes, collects tools. |
-| `mcp.Registry.call()` | `src/mcp.zig:224` | JSON-RPC `tools/call` over stdio; returns text + error flag. |
-| `serveMain()` | `src/main.zig:6694` | HTTP accept loop; spawns `serveConn` per connection. |
-| `serveMessage()` | `src/main.zig:6920` | Bridges one HTTP POST → child stdin, then streams child stdout NDJSON back via chunked response. |
-
----
-
-## 4. `build.zig` Configuration
-
-- **`src/main.zig`** is both the executable root and the test root (`build.zig:42`, `build.zig:59`).
-- **Executable**: named `graff` (`build.zig:42`).
-- **Version**: baked in at build time via `git describe --tags --always --dirty` (`build.zig:10`). Falls back to `0.1.0-dev`. Can be overridden with `-Dversion=X.Y.Z`.
-- **Telemetry endpoint**: hardcoded default `https://harness-telemetry.rachpradhan.workers.dev` (`build.zig:33`), overridable via `-Dtelemetry-endpoint=...` or disabled with `=""`.
-- **Options module**: `exe.root_module.addOptions("build_options", opts)` (`build.zig:47`) exposes `version` and `telemetry_endpoint` as compile-time constants.
-- **No external dependencies**: The build uses only the Zig standard library (`std`). There are no `build.zig.zon` dependencies.
-- **Build steps**:
- - `zig build run` — builds and runs the harness.
- - `zig build test` — runs inline unit tests (including `mcp.zig` tests).
-
----
-
-## 5. Protocol, Streaming, and Stall-Watchdog Logic
-
-### The Streaming Architecture
-- **Root (live) requests stream**: When `!self.sub and self.out != null and !self.stream_quiet`, `Agent.request()` calls `postStream()` instead of `postWatched()` (`src/main.zig:7664`).
-- **`postStream()`** (`src/main.zig:8760` area):
- 1. Sends the HTTP body via `std.http.Client.Request`.
- 2. Receives the response head, potentially decompressing (gzip, deflate, zstd).
- 3. Reads the SSE/NDJSON response line-by-line in a `while(true)` loop.
- 4. Each line is parsed and printed live via `printDelta()` while also being buffered into `full` for later JSON reassembly.
-
-### The Stall-Watchdog (Key Fix)
-The codebase explicitly guards against **idle-stall dead connections** (half-open sockets where the server accepts but sends no bytes). This is the "streaming-read stall-watchdog" referenced in the branch. It uses `std.Io.Select` to race I/O against a timeout.
-
-#### `WatchdogFired` enum (`src/main.zig:10587`)
-```zig
-const WatchdogFired = enum { esc, deadline };
-```
-
-#### `stream_stall_ms` (`src/main.zig:10598`)
-```zig
-const stream_stall_ms: u64 = 120 * 1000; // 2 minutes idle timeout
-```
-
-#### Guard Points in `postStream()`
-
-1. **Response-head stall guard** (`src/main.zig:8786`):
- ```zig
- var hsel: Io.Select(HeadDone) = .init(self.io, &hd_buf);
- hsel.concurrent(.head, streamHeadTask, .{&req});
- hsel.concurrent(.stall, streamStallTask, .{self.io});
- ```
- If headers don't arrive within `stream_stall_ms`, the connection is poisoned (`conn.closing = true`) and `error.HungRequest` is returned so the retry loop redials.
-
-2. **Per-line stall guard** (`src/main.zig:8846`):
- ```zig
- var rsel: Io.Select(ReadDone) = .init(self.io, &rd_buf);
- rsel.concurrent(.line, streamLineTask, .{ reader, &line.writer });
- rsel.concurrent(.stall, streamStallTask, .{self.io});
- ```
- If no `\n`-delimited SSE line arrives within 120s, the stream is treated as dead. Same for the "is there more?" peek (`streamPeekTask`) at `src/main.zig:8885`.
-
-3. **Non-streaming POST guard** (`postWatched`) (`src/main.zig:10650`):
- `postWatched` also races `postTask` against `postWatchdog` (200ms ticks, 10-minute hard deadline) so a stuck subagent request cannot wedge a workflow forever.
-
-#### Select Arm Wrappers (`src/main.zig:10609–10638`)
-| Task | Role |
-|------|------|
-| `streamLineTask` | `reader.streamDelimiterEnding(w, '\n')` |
-| `streamPeekTask` | `reader.peekByte()` — guards the "more data?" probe |
-| `streamHeadTask` | `req.receiveHead(&.{})` — guards header read |
-| `streamStallTask` | Sleeps 200ms increments; fires at `stream_stall_ms`; also checks `Agent.esc_cancel` for early Esc abort |
-
-#### Esc-Interrupt During Tools
-- `esc_cancel` is an atomic bool (`src/main.zig:8977`).
-- `escWatchTask` polls stdin for a bare Esc keypress in a background `Io.async` future while the root awaits tool results (`src/main.zig:8980`).
-- Subagents check `esc_cancel` between SSE lines and turn iterations, allowing graceful abort even when no HTTP stream is active.
-
----
-
-## Verified vs. Inferred
-
-### Verified
-- `src/main.zig:3991` is the single entry point.
-- The binary is both a **CLI/REPL** and an **HTTP server** (`serveMain`).
-- Tool dispatch goes through `Agent.runTools` → `execTool` → `execToolInner`, with MCP tools routed via `mcp.Registry.call`.
-- `build.zig` has **zero external dependencies**; only standard library.
-- The stall-watchdog uses `Io.Select` with `streamHeadTask`, `streamLineTask`, `streamPeekTask`, and `streamStallTask` at exactly the lines cited above.
-
-### Inferred
-- The "branch mentions streaming-read stall-watchdog fixes" refers to the `postStream` `Io.Select` guards at `stream_stall_ms = 120_000` and the related `postWatched` watchdog. The codebase contains the fixes; they are not on a separate branch in the current working tree.
-- `std.Io` is a custom or experimental Zig async I/O layer (not standard Zig 0.16/0.17 stdlib). The 182 uses mentioned in `docs/zig-0.17-port-plan.md` suggest this is a stable internal abstraction.
-
----
-
-## 3 Most Load-Bearing Facts
-
-1. **The binary is a self-contained AI agent harness with no external Zig dependencies.** It directly implements a full REPL, HTTP serve bridge, multi-provider LLM client, parallel tool executor, subagent/workflow engine, and MCP client—all in ~13k lines of Zig using only `std` and `std.Io`.
-2. **The stall-watchdog is load-bearing for reliability.** Every streaming read (headers, SSE lines, peek-ahead) is raced against a 120-second `Io.Select` deadline. Without it, half-open/dead TLS sockets would hang the agent indefinitely, especially in `--json` / GUI sessions where there is no TTY Esc escape.
-3. **`mcp.zig` is the gateway to external tool ecosystems.** The `Registry` spawns stdio servers, serializes JSON-RPC per server via mutex, rewrites `oneOf` to `anyOf` for OpenAI compatibility, and exposes tools to the orchestrator under qualified names (`mcp__<server>__<tool>`).
-
----
-
-## 1 Open Question
-
-**What is `std.Io` and where is it maintained?** It is referenced 182+ times (`Io.Select`, `Io.Future`, `Io.Group`, `Io.Mutex`, `Io.File.Reader/Writer`, `io.sleep`, `io.async`, etc.), but it is not part of the Zig standard library as of 0.16. It appears to be a custom async runtime layer. Is it a private fork of Zig, a vendored library, or a patched stdlib? Its stability is explicitly called out as the critical dependency for any future Zig 0.17 port.
-
-[subagent sa-000-305676f1 · inspect: .graff/subagents/sa-000-305676f1.md]
-
-### Explore GUI frontend
-# React/TypeScript Frontend Architecture Report (`gui/src/`)
-
-## 1. Main App Entry Point & Overall Architecture
-
-**Entry point:** `gui/src/main.tsx:1`
-- Renders `<App />` inside `StrictMode`.
-- Imports global styles: `dockview-react` CSS, `@codegraff/diffs` CSS, and local `index.css` / `diffs.css`.
-
-**App shell:** `gui/src/app/App.tsx:1`
-- `App` wraps `SessionProvider` → `DragDropProvider` → `AppShell`.
-- `AppShell` is the root layout: a resizable horizontal panel group (`ResizablePanelGroup`) with:
- - **Left:** `ProjectSidebar` (collapsible, animated width transitions).
- - **Right:** `WorkspaceBoard` (when no settings view), or one of `ProvidersSettingsPane` / `McpSettingsPane` / `GeneralSettingsPane`.
-- Global chrome includes:
- - Theme toggle (`AppThemeToggle`) using `useThemeStore` (`gui/src/app/themeStore.ts:1`).
- - Sidebar visibility control (`AppSidebarControl`).
- - A captured `NewChatTrigger` ref for global `Cmd/Ctrl+N` shortcut.
-- Fullscreen state is synced from Tauri’s `getCurrentWindow().isFullscreen()` via `onResized` / `onFocusChanged` listeners (`App.tsx:65`).
-
-**Verified:** The app bootstraps in `SessionProvider`, shows a spinner until `isSessionBootstrapped` is true, then renders the full shell.
-
----
-
-## 2. Sessions (`sessionStore`, `SessionProvider`, `useSession`, `sessionClientActions`)
-
-### 2.1 Store (`gui/src/app/sessionStore.ts:1`)
-- Built on **Zustand vanilla** (`createStore`), not React context, for performance.
-- Core state shape (`SessionStoreState`):
- - `selection: WorkspaceBoardSelection` — what the board shows (`empty`, `single-chat`, `workspace-draft`, `saved-workspace`).
- - `workspaces`, `workspacesByPath`, `conversationSummariesByKey`, `conversationViewsByKey`.
- - `promptDraftsByKey`, `attachmentsByKey`, `workspaceMetaByKey` (runtime status + prompt settings).
- - `requestTimingsByConversationId` — tracks start/completion times per request.
-- `applySessionSnapshot(snapshot)` is the primary reducer: it rebuilds `conversationViewsByKey`, `conversationSummariesByKey`, updates `selection`, and computes request timings by diffing `activeRequestIds` (`sessionStore.ts:315`).
-- Memoized helper selectors (`getUiActiveWorkspacePath`, `getUiActiveConversationId`, `getUiActiveBinding`) respect the `selection` override vs. the snapshot’s `activeWorkspacePath`/`activeConversationId`.
-
-### 2.2 `SessionProvider` (`gui/src/app/SessionProvider.tsx:1`)
-- Wraps children in `SessionActionsContext.Provider` with a memoized `actionState` object containing ~20 async actions.
-- Key actions:
- - `openWorkspaceByPath` — calls `desktopClient.openWorkspace`, then `applySessionSnapshot` + `syncBoardSelectionFromSnapshot`.
- - `selectConversation` — optimistic UI update (`setBoardSelection`), then fetches snapshot via `desktopClient.selectConversation`, with revert on failure.
- - `startNewChat` — reuses a “managed chat” draft if available, otherwise creates a new one.
- - `submitPrompt` — reads the draft from `sessionStore`, appends attachments, clears draft, calls `desktopClient.sendPrompt`, then migrates the draft/attachments to the new conversation key.
-- Bootstrapping: `useSessionBootstrap` (`gui/src/hooks/useSessionBootstrap.ts:1`) is used inside `SessionProvider`:
- - Listens to `SESSION_UPDATED_EVENT_NAME` (`codegraff://session-updated`).
- - Fetches `getSessionSnapshot`; if no active workspace, restores the latest from `localStorage` (`LATEST_WORKSPACE_STORAGE_KEY`), or falls back to `createManagedChat`.
-
-### 2.3 `useSession` hook (`gui/src/hooks/useSession.ts:1`)
-- Thin Zustand selectors over `sessionStore`.
-- `useConversationSession(binding?)` returns:
- - `messages`, `activeRequestIds`, `requestTimingsById`, `followupRequest`, `todos`, `workspacePath`, `isConversationLoading`, `activeWorkspaceConfigured`, etc.
-- `usePromptDraft(binding?)` returns draft state + `canCompose` (blocked by unconfigured workspace, pending followup, pending draft, or running conversation).
-- `useWorkspaceMeta(workspacePath)` auto-fetches `runtimeStatus` and `promptSettings` on mount via `ensureWorkspaceRuntimeStatusLoaded` / `ensureWorkspacePromptSettingsLoaded`.
-
-### 2.4 Client actions (`gui/src/app/sessionClientActions.ts:1`)
-- Thin async wrappers around `desktopClient` calls that also update `sessionStore` after success.
-- Examples: `runWorkspaceRuntimeStatusAction`, `updateWorkspacePromptSettings`, `submitFollowupResponse`, `openWorkspaceInTarget`.
-
----
-
-## 3. Chat / Activities Rendering
-
-### 3.1 `ChatThread` (`gui/src/components/chat/ChatThread.tsx:1`)
-- Uses `@legendapp/list/react` (`LegendList`) for virtualized rendering of `ChatThreadItem[]`.
-- **Auto-scroll logic:** tracks `isFollowingRef` / `userWantsFollowRef`. Locks to bottom while `isFollowing` is true; user scroll-up breaks the lock and shows a “Scroll to latest” pill with `pendingCount` of new items.
-- Items are built by `buildChatThreadItems(messages, activeRequestIds)` (`gui/src/components/chat/utils/chatThread.ts:1`).
-
-### 3.2 Thread item builder (`gui/src/components/chat/utils/chatThread.ts:1`)
-- Walks `TranscriptMessage[]` and groups tool calls into `ActivityItem` groups scoped by `requestId` + scope index.
-- Message kinds handled:
- - `user` / `context_compacted` → message item + starts a new scope.
- - `assistant` / `error` → message item.
- - `reasoning` → merged into a “Thinking” activity group.
- - `tool_start` → operation pushed into current group.
- - `status_output` → appended to the latest open operation’s `outputText`.
- - `tool_end` → marks operation completed, sets `isError`, `summary`, `resultDetail`.
- - `status` → displayed as standalone message (unless decorative debug).
-- Final pass inserts `request_work` items after their anchor message.
-
-### 3.3 `ChatActivityRow` (`gui/src/components/chat/ChatActivityRow.tsx:1`)
-- Renders each `ActivityItem` inside a `Collapsible`.
-- If `isThinking`, shows a “Thinking” label with optional reasoning text rendered as `ChatMarkdown`.
-- Otherwise shows a summary label (e.g., “Explored 3 files”, “Ran 2 commands”) and a list of `ActivityOperationRow`.
-- Auto-opens on running→idle transition if error; preserves user-open state otherwise.
-
-### 3.4 `ActivityOperationRow` (`gui/src/components/chat/ChatActivityRow.tsx:115`)
-- Maps `operation.detail.kind` to icons (`file_read`, `file_update`, `shell`, `search`, `fetch`, `plan`, `skill`, `task`, `todo_*`, `unknown`).
-- Expandable rows show `ActivityResultRenderer` inside `CollapsibleContent`.
-
-### 3.5 Activity results (`gui/src/components/chat/activity-results/ActivityResultRenderer.tsx:1`)
-- Two result types:
- - **`file_diff`** → `FileDiffResult` (`gui/src/components/chat/activity-results/FileDiffResult.tsx:1`):
- - Uses `useRenderableFileDiff` to parse the patch; if the patch is missing, reads the workspace file via `read_workspace_file` Tauri command to synthesize a full-file diff.
- - Renders via `@codegraff/diffs/react` `PatchDiff`.
- - Shows `+additions` / `-deletions` stats.
- - If `canOpenInEditor`, clicking the filename opens it via `openWorkspacePathInTarget` (uses `resolvedPreferredAppId`, e.g., VS Code).
- - **`content`** → `ContentResult` (plain text/card).
-
----
-
-## 4. Workspace Board Layout (`WorkspaceBoard`, `dockview`, tiles, panes)
-
-### 4.1 Outer board (`WorkspaceBoard.tsx:1`)
-- Uses `dockview-react` (`DockviewReact`) as the outer layout engine.
-- Selection kinds drive the board:
- - `empty` → `NewChatScreen`.
- - `workspace-draft` → `ConversationPanel` (single pane, no dockview).
- - `single-chat` → builds a default outer layout with one chat panel.
- - `saved-workspace` → restores layout from `layoutJson` via `applySavedWorkspaceLayout`; on failure falls back to bindings list.
-- **Chat panels:** Each panel id is `chat:<workspacePath>::<conversationId>`. Component = `OUTER_CHAT_COMPONENT` which renders `ChatTile`.
-- **Drag & drop:** Supports dragging chats between outer panels (custom MIME type `application/x-codegraff-chat-binding`). Dropping a chat on the board creates/activates it.
-- **Persistence:** Layout changes are persisted via `desktopClient.updateSavedWorkspaceLayout` for saved workspaces.
-
-### 4.2 Chat tile (`ChatTile.tsx:1`)
-- Each chat tile contains its **inner** `DockviewReact` with:
- - `INNER_CHAT_COMPONENT` → `ConversationPanel` (the actual chat + composer).
- - `INNER_PLACEHOLDER_COMPONENT` → auxiliary panes: `ChangesPane`, `TerminalPane`, or generic `PlaceholderPane`.
-- **Auxiliary panes:**
- - `changes` (right of chat) — shows workspace file changes.
- - `terminal` (bottom, spanning full width) — opens a PTY via Tauri `terminal_open`; supports multiple tabs; each tab has its own `terminalKey` and PTY session.
- - `preview` (right of chat).
-- **Header actions:** `ConversationDockviewHeaderActions` when chat is active; terminal-specific actions (new tab, restart, close) when a terminal tab is active.
-- **Constraints:** `applyChatTileLayoutConstraints` locks group headers; `autoCloseUndersizedSidePanes` closes side panes dragged below 180px.
-- **Programmatic mutation guard:** Prevents auto-close during programmatic pane open/add.
-
-### 4.3 Layout utilities (`gui/src/components/workspace-board/layout.ts:1`, `chatTileLayout.ts:1`)
-- `serializeDockviewLayout` / `parseDockviewLayoutJson` convert to/from JSON.
-- `extractBindingsFromSerializedLayout` extracts `ChatBinding[]` from persisted layouts.
-- Terminal ids are namespaced: `terminal:<workspacePath>::<conversationId>::<terminalKey>`.
-- Custom events (`PANE_CLOSE_REQUEST_EVENT_NAME`, `TERMINAL_RESTART_EVENT_NAME`) decouple close/restart requests from the UI tree.
-
----
-
-## 5. Settings & Provider Setup
-
-### 5.1 General settings (`gui/src/components/general-settings/GeneralSettingsPane.tsx:1`)
-- `themeStore` (`gui/src/app/themeStore.ts:1`) persists `mode` (light/dark) and `preset` (e.g., `warm-graphite`, `slate`) to `localStorage`.
-- `applyTheme` runs at module import (before React) to prevent flash.
-
-### 5.2 Providers settings (`gui/src/components/providers-settings/ProvidersSettingsPane.tsx:1`)
-- Uses `useProviderSetup` hook (not fully read, but it calls `listProviders`, `startProviderAuth`, etc.).
-- Lists providers from `desktopClient.listProviders(workspacePath)`.
-- Each row shows: name, configured status, auth methods, env override hint.
-- **Auth methods:**
- - `ApiKey` → dialog with key input; calls `completeProviderAuth` which runs `graff key set <provider> <key>`.
- - `CodegraffDevice` / `CodexDevice` / `KimiDevice` → launches Terminal with `graff login [target]` via a temp `.command` script (`runtime/simple.rs:1666`).
-- **Remove provider:** deletes keychain / JSON fallback / login files; surfaces an error if an env var still overrides it (`commands.rs:375`).
-
-### 5.3 MCP settings (`gui/src/components/mcp-settings/McpSettingsPane.tsx:1`)
-- Calls `listMcpServers`, `reloadMcpServers`, `removeMcpServer`, `importMcpConfig`.
-- Servers are read from workspace `.mcp.json`.
-- Supports `user` vs `local` scope import (writes to workspace `.mcp.json`).
-- `login/logout` buttons exist but are no-ops in the MVP adapter because graff only runs stdio MCP servers.
-
----
-
-## 6. State Management Patterns & Tauri Backend Bridge
-
-### 6.1 Frontend → Backend
-- **Single service file:** `gui/src/services/desktop/client.ts:1` wraps every Tauri command.
-- Uses `invoke<T>(command, args)` from `@tauri-apps/api/core`.
-- **QA mock mode:** When `import.meta.env.VITE_CODEGRAFF_QA_MOCK === "1"`, `client.ts` short-circuits to deterministic mock snapshots/responses so the UI can be tested in a browser without Tauri.
-
-### 6.2 Backend → Frontend (events)
-- `listenSessionUpdates` listens to `codegraff://session-updated` (`emitter.rs:1`).
-- `listenTerminalOutput` / `listenTerminalExit` / `listenTerminalErrors` listen to terminal-specific events.
-- `TauriEventEmitter` (`emitter.rs:20`) implements `UiEventEmitter` and pushes `SessionSnapshotDto`, `TerminalOutputEventDto`, etc. into the webview via `tauri::Emitter`.
-
-### 6.3 Backend runtime (`gui/src-tauri/src/runtime/simple.rs:1`)
-- `RuntimeManager` coordinates the GUI with a persistent `graff --json` child process per conversation.
-- **Session lifecycle:** `acquire_session_io` spawns `graff --json --yolo` (with login-shell env injection for macOS); reuses the child across turns; drops it on `stop_prompt` or error.
-- **Streaming protocol:** `stream_turn` reads JSONL events from `graff` stdout:
- - `text` → `Assistant` message (appended live).
- - `reasoning` → `Reasoning` message.
- - `tool_call` / `tool_result` → `ToolStart` / `ToolEnd`.
- - `ask_user` → creates a `FollowupRequestDto` and stores it in `pending_followups`; UI renders via `followup` in conversation view.
- - `error` / `turn` → ends the turn.
-- After each event, `emit()` calls `snapshot()` and pushes the full `SessionSnapshotDto` to the frontend, which then `applySessionSnapshot`s it.
-
-### 6.4 Persistence (backend)
-- Conversations are persisted to `~/.codegraff-gui/conversations.json` (`simple.rs:1582`).
-- Prompt settings (model/effort/fast) persisted to `~/.codegraff-gui/prompt-settings.json`.
-- Saved workspace layouts and conversation layouts stored via `ProjectStore` (`project_store.rs`).
-
----
-
-## Verified vs. Inferred
-
-| Claim | Status | Evidence |
-|-------|--------|----------|
-| Zustand vanilla store is the single source of truth | **Verified** | `sessionStore.ts:1` creates store with `createStore`; `useSession.ts:134` uses `useStore(sessionStore, selector)`. |
-| `graff --json` is spawned per conversation and reused | **Verified** | `runtime/simple.rs:1057` `spawn_graff_session`; `acquire_session_io` reuses existing sessions; `drop_session` kills on error. |
-| Session snapshots are emitted after every JSONL event | **Verified** | `simple.rs:1181` `self.emit().await?` inside the `text`, `reasoning`, `tool_call`, `tool_result`, `ask_user` branches. |
-| `login_shell_env` is used to fix macOS env isolation | **Verified** | `simple.rs:1548` `login_shell_env()` runs `env` via the user’s login shell and injects the map into the graff child. |
-| Dockview is used for both outer board and inner chat tile | **Verified** | `WorkspaceBoard.tsx:226` outer `DockviewReact`; `ChatTile.tsx:319` inner `DockviewReact`. |
-| MCP login/logout are no-ops in the current adapter | **Verified** | `simple.rs:1448` `login_mcp_server` and `logout_mcp_server` bail with “graff runs stdio MCP servers only”. |
-| `read_workspace_file` has a sandbox containment check | **Verified** | `commands.rs:539` canonicalizes workspace + path, checks `starts_with`, caps size at 512KB, rejects non-files. |
-
----
-
-## 3 Load-Bearing Facts
-
-1. **The entire frontend state is reconciled from backend-issued `SessionSnapshot` DTOs.** The `sessionStore` does not optimistically update messages; it only updates `promptDrafts` and `selection` locally. Every streaming token arrives via Tauri event → `applySessionSnapshot`, which rebuilds `conversationViewsByKey` and timing maps (`sessionStore.ts:315`). This means the frontend is essentially a reactive projection of the backend `RuntimeManager` state.
-
-2. **`WorkspaceBoard` selection state determines the Dockview outer layout, not the other way around.** The board reacts to `selection` (empty / single-chat / saved-workspace) by resetting or restoring the outer Dockview. When the user drags a chat panel in a saved workspace, the layout JSON is serialized and sent back to Tauri (`desktopClient.updateSavedWorkspaceLayout`), and the active chat binding is updated in the store (`WorkspaceBoard.tsx:127`).
-
-3. **The backend spawns a persistent `graff --json` child per conversation and streams JSONL events into `SessionSnapshotDto`s that are pushed to the frontend.** This is the primary bridge: commands are RPC via `invoke`, and live updates are events via `emit_session_updated`. The frontend has no WebSocket or SSE; it relies entirely on Tauri’s `invoke` + `listen` abstraction.
-
----
-
-## 1 Open Question
-
-- **How does the frontend handle backpressure or out-of-order `session-updated` events?** The `useSessionBootstrap` hook sets `receivedSessionUpdateRef` to avoid overwriting a newer event with an older snapshot during bootstrap, but there is no explicit sequence numbering or debouncing in `sessionStore.applySessionSnapshot`. If two events arrive close together, the Zustand store will apply both in order, but React components may re-render with intermediate states. Is this acceptable because the backend only emits snapshots sequentially from a single `RuntimeManager` mutex, or should the frontend add a generation/version counter to drop stale snapshots?
-
-[subagent sa-001-59aa643c · inspect: .graff/subagents/sa-001-59aa643c.md]
-
-### Explore Tauri Rust backend
-# Rust Tauri Backend Report — `gui/src-tauri/src/`
-
-## 1. Entry Points (`lib.rs` & `main.rs`)
-
-**`main.rs`** is a minimal 7-line launcher that prevents a console window on Windows in release builds and delegates to `codegraff_gui_lib::run()` (`gui/src-tauri/src/main.rs:4`).
-
-**`lib.rs`** is the real bootstrap (`gui/src-tauri/src/lib.rs`):
-
-- **Plugin registration** (`L50`):
- - `tauri_plugin_single_instance` — handles `codegraff <path>` cold-start so a second invocation opens the path in the running window and focuses it.
- - `tauri_plugin_dialog` — native file dialogs.
- - `tauri_plugin_log` — dev-only logging.
-- **State setup** (`L65–L88`):
- - Creates `TauriEventEmitter` (wraps `tauri::AppHandle` for typed events).
- - Initializes `forge_config_home` (copies global Forge config into the app data dir once, then sets `FORGE_CONFIG`).
- - Opens `ProjectStore` SQLite DB at `app_data_dir/projects.db` and managed-chats folder.
- - Manages `DesktopState` (the runtime + terminal manager) and `PendingOpen` (stashes CLI argv for the frontend to drain on mount).
- - In debug builds, starts `DebugBridge` (localhost HTTP server on port 9233).
-- **Invoke handler** (`L93–L180`) — registers ~45 Tauri commands from `commands.rs` plus `cg_debug_eval_result`.
-- **Window event hook** (`L89–L92`) — on `Destroyed`, cancels pending follow-ups.
-
----
-
-## 2. Commands (`commands.rs`)
-
-All commands are thin `#[tauri::command]` async wrappers that delegate to `DesktopState` (`manager` or `terminal_manager`). They transform `anyhow::Error` into a flat string via `format_error_chain`.
-
-**Categories of exposed capabilities** (`gui/src-tauri/src/commands.rs`):
-
-| Category | Key Commands |
-|----------|--------------|
-| **Workspace / Project** | `pick_workspace`, `pick_directory`, `open_workspace`, `clone_repository`, `quick_start_project`, `rename_workspace`, `archive_workspace` |
-| **Session / Chat** | `start_new_chat`, `create_managed_chat`, `select_conversation`, `ensure_conversation_view`, `send_prompt`, `stop_prompt`, `compact_conversation`, `handoff_chat`, `respond_followup`, `archive_conversation` |
-| **Prompt / Agent** | `get_prompt_settings`, `update_prompt_settings`, `set_active_agent`, `set_effort`, `set_fast`, `list_providers`, `start_provider_auth`, `complete_provider_auth`, `remove_provider` |
-| **Commands / Slash** | `list_commands`, `run_slash_command` |
-| **Workspace Search** | `workspace_sync`, `workspace_query` |
-| **Git** | `checkout_git_branch`, `create_git_branch`, `commit_git_changes`, `push_git_branch` |
-| **MCP** | `list_mcp_servers`, `import_mcp_config`, `remove_mcp_server`, `reload_mcp_servers`, `login_mcp_server`, `logout_mcp_server` |
-| **File / OS** | `read_workspace_file`, `open_path_default`, `open_path_for_edit`, `open_external_url`, `open_in_target`, `open_path_in_target` |
-| **Layout / Persistence** | `save_conversation_layout`, `get_conversation_layout`, `create_saved_workspace`, `update_saved_workspace_layout`, `get_saved_workspace`, `rename_saved_workspace`, `delete_saved_workspace` |
-| **Image** | `save_pasted_image`, `image_thumbnail` |
-| **Terminal** | `terminal_open`, `terminal_write`, `terminal_resize`, `terminal_close` |
-| **Cold start** | `drain_pending_open` |
-
-**Notable implementation details:**
-- `read_workspace_file` (`L414`) runs in `tokio::task::spawn_blocking` and performs a strict sandbox check: it canonicalizes both the workspace root and the target path, rejects empty workspace roots, verifies `starts_with`, checks `is_file`, and caps reads at 512 KiB.
-- `save_pasted_image` (`L258`) writes to a temp file under `codegraff-pasted` and returns the path.
-- `image_thumbnail` (`L275`) spawns a blocking task that opens the image, downscales it, re-encodes as JPEG quality 70, and returns a base64 data URL.
-- `clone_repository` / `quick_start_project` directly invoke `git clone` and `gh repo create` via `std::process::Command`.
-
----
-
-## 3. Runtime (`runtime/simple.rs`)
-
-This is the core orchestrator. It bridges the Tauri frontend to the Zig-native `graff` CLI by spawning persistent `graff --json` child processes per conversation.
-
-**Key structures** (`gui/src-tauri/src/runtime/simple.rs`):
-
-- **`RuntimeManager`** (`L108`) — cloneable, holds:
- - `emitter: Arc<dyn UiEventEmitter>` — pushes `SessionSnapshotDto` to the frontend.
- - `projects: Arc<ProjectStore>` — SQLite registry.
- - `state: Arc<Mutex<RuntimeState>>` — in-memory conversations, workspace list, model selection, pending follow-ups.
- - `sessions: Arc<Mutex<HashMap<String, GraffSession>>>` — live child processes keyed by `conversation_id`.
-
-- **`RuntimeState`** (`L62`) — tracks:
- - `active_workspace_path`, `active_conversation_id`
- - `conversations: HashMap<String, ConversationState>` — messages, titles, request IDs, agent IDs, plan mode, goal.
- - `selected_provider`, `selected_model`, `selected_effort`, `fast_enabled`
- - `model_catalog` — cached result of `graff --schema`
- - `pending_followups` — live `ask_user` prompts awaiting GUI answer.
-
-- **`GraffSession`** (`L97`) — a persistent `graff --json` child:
- - `child: tokio::process::Child`
- - `stdin: Arc<Mutex<ChildStdin>>` — shared so follow-up answers can be injected while a turn is streaming.
- - `reader: Option<Lines<BufReader<ChildStdout>>>` — taken during a turn and returned after.
-
-**Session lifecycle & protocol flow:**
-
-1. **`send_prompt`** (`L416`) — creates a `request_id`, appends a `User` message to `ConversationState`, then calls `stream_turn`.
-2. **`stream_turn`** (`L562`) — acquires session IO via `acquire_session_io`:
- - If no session exists, spawns `graff --json --yolo` (with model/agent/mode/effort/fast controls injected) via `spawn_graff_session` (`L1403`).
- - Writes a JSON line `{"type":"user","text":...}` to stdin.
- - Reads JSONL lines from stdout and maps them to DTOs:
- - `text` → `SessionMessageDto::Assistant` (appended incrementally)
- - `reasoning` → `SessionMessageDto::Reasoning`
- - `tool_call` → `SessionMessageDto::ToolStart`
- - `ask_user` → `SessionMessageDto::ToolStart` + stores `FollowupRequestDto` in `pending_followups`
- - `tool_result` → `SessionMessageDto::ToolEnd`
- - `turn` → ends the loop cleanly
- - `error` → pushes `SessionMessageDto::Error` and breaks
- - After each event, calls `emit()` which snapshots state and fires `codegraff://session-updated`.
-3. **`send_control`** (`L696`) — sends non-user controls (`set_model`, `set_mode`, `compact`, `set_agent`, `set_effort`, `set_fast`) and waits for an ack JSON line.
-4. **`respond_followup`** (`L943`) — writes the structured answer JSON to the session’s stdin, unblocking the streaming loop.
-5. **`stop_prompt`** (`L1036`) — kills the session child (`drop_session`), which causes `stream_turn` to hit EOF and finish.
-6. **Title generation** (`L355`) — first-turn titles are generated by a fire-and-forget one-shot `graff -p "<title prompt>" --yolo` call.
-
-**Model/provider machinery:**
-- `codegraff_binary()` (`L1506`) resolves the engine via a 5-step fallback: `CODEGRAFF_GUI_BINARY` env var → bundled sidecar next to exe → dev build `../../zig-out/bin/graff` → standard install paths (`~/bin/graff`, `/opt/homebrew/bin/graff`, etc.) → bare `graff` on PATH.
-- `login_shell_env()` (`L1351`) — on macOS, captures the user’s login shell environment (`env` from `zsh -il`) so `OPENAI_API_KEY` etc. are visible to the GUI-spawned binary.
-- `codegraff_schema_models()` (`L1427`) parses `graff --schema` JSON to populate the model picker dynamically.
-- Provider auth is handled by mapping to `graff key set`, `graff login`, or direct env var detection. Credentials are deleted from macOS Keychain, `~/.simple-harness-keys.json`, and provider-specific files (`~/.codex/auth.json`, `~/.kimi/credentials/graff-oauth.json`).
-
-**Persistence:**
-- Conversations are persisted to `~/.codegraff-gui/conversations.json` (`PersistedConversation`) at turn boundaries (`persist_conversations`, `L783`).
-- Prompt settings (provider, model, effort, fast) are persisted to `~/.codegraff-gui/prompt-settings.json` (`persist_prompt_settings`, `L375`).
-
----
-
-## 4. Bridge Modules (`bridge/*`, `desktop_open.rs`, `debug_bridge.rs`)
-
-**`bridge/emitter.rs`** (`gui/src-tauri/src/bridge/emitter.rs`) — Defines the event contract:
-
-- `UiEventEmitter` trait (`L12`) with methods:
- - `emit_session_updated(SessionSnapshotDto)`
- - `emit_terminal_output(TerminalOutputEventDto)`
- - `emit_terminal_exit(TerminalExitEventDto)`
- - `emit_terminal_error(TerminalErrorEventDto)`
- - `emit_provider_oauth_callback(...)` (unused by simple adapter)
-- `TauriEventEmitter` implements this by calling `app.emit(...)` with event names like `codegraff://session-updated`.
-
-**`bridge/followup.rs`** (`gui/src-tauri/src/bridge/followup.rs`) — A `FollowupBridge` that uses `tokio::sync::mpsc` and `oneshot` channels to turn `ask_user` prompts into async Rust futures. It stores pending resolutions by `followup_id` and maps `select_one`/`select_many`/`prompt_question` to `FollowupRequestDto`/`FollowupResponseDto`. `with_followup_context` sets a task-local context so the bridge knows the workspace/conversation/request IDs.
-
-**`bridge/desktop_infra/`** (`gui/src-tauri/src/bridge/desktop_infra/mod.rs`) — A wrapper around `forge_infra::ForgeInfra` that implements `CommandInfra`, `EnvironmentInfra`, `FileReaderInfra`, `FileWriterInfra`, `HttpInfra`, `McpServerInfra`, `UserInfra`, etc. The comments note this is “copied scaffolding; unused by the simple adapter (graff has no follow-up tool). Retained for future parity.”
-
-**`desktop_open.rs`** (`gui/src-tauri/src/desktop_open.rs`) — OS-native file/URL opening:
-- `open_external_url` → `open` (macOS) / `start` (Windows) / `xdg-open` (Linux).
-- `open_path_default` → same OS commands.
-- `open_path_for_edit` → `open -t` (macOS text editor) / `notepad` / `xdg-open`.
-- `open_path_in_target` (unused) supports IDE targets: Cursor, Zed, Xcode, Terminal, Ghostty, Warp, Android Studio.
-- `detect_available_open_targets` probes which apps are installed.
-
-**`debug_bridge.rs`** (`gui/src-tauri/src/debug_bridge.rs`) — Dev-only localhost HTTP server on `127.0.0.1:9233`:
-- `POST /eval` — injects JS into the Tauri webview via `window.eval()`, returns the result via `__TAURI_INTERNALS__.invoke('cg_debug_eval_result', ...)`.
-- `GET /screenshot` — focuses the window, runs `screencapture`, crops to window bounds.
-- `POST /eval-result` — external endpoint to resolve a pending eval.
-- Only compiled/started in `cfg(debug_assertions)`; the Tauri command is always registered but harmless in release.
-
----
-
-## 5. DTOs (`dto/*`)
-
-All data types are in `dto/` and derive `Serialize`, `Deserialize`, `PartialEq`, `Eq`, and `ts_rs::TS` for automatic TypeScript generation (`gui/src-tauri/src/dto/mod.rs`).
-
-**`dto/session.rs`** — Core conversation model:
-- `SessionMessageDto` (`L12`) — tagged enum for `User`, `Assistant`, `Reasoning`, `Status`, `ToolStart`, `ToolEnd`, `Error`, `ContextCompacted`.
-- `ConversationViewSnapshotDto` — a full conversation view (messages + active requests + followup).
-- `SessionSnapshotDto` — the root payload emitted to the frontend: active workspace, visible messages, conversation list, workspaces, saved workspaces.
-
-**`dto/activity.rs`** — Tool call / result shapes:
-- `ToolCallDetailDto` (`L22`) — `FileRead`, `FileUpdate`, `Shell`, `Search`, `CodebaseSearch`, `Fetch`, `Followup`, `Plan`, `Skill`, `Task`, `TodoWrite`, `TodoRead`, `Unknown`.
-- `ToolResultDetailDto` — `FileDiff`, `ShellOutput`, `Text`.
-- `OutputPreviewDto` — supports truncated head/tail previews.
-
-**`dto/chat.rs`** — `ChatEventKind` / `ChatEventDto` — a parallel event representation (used by the copied infrastructure, not the simple adapter’s streaming).
-
-**`dto/command.rs`** — Command system DTOs:
-- `CommandDescriptorDto`, `CommandRunResultDto`, `CommandPayloadDto`
-- `AgentsPayloadDto`, `AgentSummaryDto`
-- `WorkspaceSearchResultDto`, `WorkspaceSyncPayloadDto`, `WorkspaceStatusPayloadDto`
-- `McpServerSummaryDto`, `McpSettingsPayloadDto`, `McpImportInput`
-- `WorkflowDraftPayloadDto`, `WorkflowNodeDto`
-
-**`dto/runtime.rs`** — Settings & auth:
-- `PromptSettingsDto`, `PromptModelOptionDto`
-- `ProviderSummaryDto`, `ProviderAuthMethodDto`, `ProviderAuthSessionDto`
-- `SendPromptInput`, `CloneRepositoryInput`, `QuickStartProjectInput`, `CreateSavedWorkspaceInput`
-- `RuntimeStatusDto` — git repo/branch/workspace kind detection
-
-**`dto/followup.rs`** — Interactive prompts:
-- `FollowupKind` (`Text`, `Single`, `Multi`)
-- `FollowupRequestDto`, `FollowupResponseDto`
-
-**`dto/terminal.rs`** — Terminal DTOs:
-- `TerminalOpenInput`, `TerminalWriteInput`, `TerminalResizeInput`, `TerminalCloseInput`
-- `TerminalSessionDto`, `TerminalOutputEventDto`, `TerminalExitEventDto`, `TerminalErrorEventDto`
-
----
-
-## 6. Persistence & Terminal Handling
-
-**Persistence (`persistence/project_store.rs`)** (`gui/src-tauri/src/persistence/project_store.rs`):
-
-- Uses **SQLite** via `diesel` with `SqliteConnection`.
-- Tables managed:
- - `opened_projects` — path, last_opened_at, display_name
- - `managed_chat_workspaces` — auto-created chat folders
- - `conversation_layouts` — layout JSON per conversation_id
- - `saved_workspaces` / `saved_workspace_layouts` — user-saved workspace layouts
-- All operations are serialized through a `Mutex` (`connection_lock`) to prevent concurrent SQLite writes.
-- `add_project`, `create_managed_chat_workspace`, `list_workspaces`, `archive_workspace`, `save_conversation_layout`, `create_saved_workspace`, etc.
-- `ProjectStore` is initialized in `lib.rs` and stored as `Arc<ProjectStore>` inside `DesktopState`.
-
-**Additional file-based persistence** (in `runtime/simple.rs`):
-- `~/.codegraff-gui/conversations.json` — serialized `Vec<PersistedConversation>` so chats survive restarts.
-- `~/.codegraff-gui/prompt-settings.json` — `PersistedPromptSettings` (model, effort, fast).
-
-**Terminal Handling (`terminal.rs`)** (`gui/src-tauri/src/terminal.rs`):
-
-- Uses `portable_pty` (`native_pty_system()`) to spawn real PTY sessions.
-- `TerminalManager` (`L22`) holds a `HashMap<String, Arc<TerminalSession>>`.
-- `TerminalSession` (`L100`) wraps:
- - `master: StdMutex<Box<dyn MasterPty>>` — PTY master fd/handle
- - `writer: StdMutex<Box<dyn Write>>` — write end
- - `killer: StdMutex<Box<dyn ChildKiller>>` — process killer
- - `exit_status: StdMutex<bool>`
-- **Spawn flow** (`spawn_terminal_session`, `L172`):
- - Opens a PTY with default 80×24 or supplied cols/rows.
- - Spawns the user’s shell (`$SHELL`, default `/bin/sh`; on Windows `cmd.exe`).
- - Sets `TERM=xterm-256color`, `COLORTERM=truecolor`, `TERM_PROGRAM=codegraff-gui`.
- - For `zsh`, passes `-o NO_PROMPT_SP -o NO_PROMPT_CR` to prevent prompt spacing issues.
- - Sets `cwd` to the workspace path.
-- **Reader thread** (`spawn_reader_thread`, `L216`) — reads from the PTY master in a blocking loop, batches into ~4KB chunks, converts to string via `bstr`, and emits `codegraff://terminal-output`.
-- **Wait thread** (`spawn_wait_thread`, `L261`) — waits on the child process, then emits `codegraff://terminal-exit` with exit code / signal.
-- Commands exposed: `terminal_open`, `terminal_write`, `terminal_resize`, `terminal_close`.
-
----
-
-## Verified vs. Inferred
-
-- **Verified:** The runtime spawns `graff --json` as a persistent child and speaks a line-delimited JSON protocol (`runtime/simple.rs:1403`, `stream_turn:562`).
-- **Verified:** The `ProjectStore` uses SQLite with `diesel` and the schema includes `opened_projects`, `managed_chat_workspaces`, `conversation_layouts`, `saved_workspaces` (`project_store.rs:23–30`).
-- **Verified:** The `bridge/desktop_infra` module is explicitly marked as unused by the simple adapter and retained for future parity (`bridge/desktop_infra/mod.rs:13` comment, `lib.rs:10–15` comment).
-- **Verified:** The terminal uses `portable_pty` with separate reader and wait threads emitting Tauri events (`terminal.rs:172–299`).
-- **Inferred:** The frontend consumes the `SessionSnapshotDto` emitted on `codegraff://session-updated` to re-render the entire conversation state (inferred from the emitter pattern and the DTO structure; the frontend code was not inspected).
-
----
-
-## 3 Most Load-Bearing Facts
-
-1. **Conversation engine is a persistent `graff --json` child process.** The backend does not embed the Zig core; it shells out to the `graff` CLI, keeps one `tokio::process::Child` per conversation, and streams JSONL events over stdin/stdout. This is the central data flow for all chat (`runtime/simple.rs:1403`, `stream_turn:562`).
-
-2. **All UI state is pushed via `TauriEventEmitter` emitting `SessionSnapshotDto`.** The frontend does not poll; the backend continuously snapshots the full `RuntimeState` (conversations, workspaces, follow-ups, active requests) and pushes it through the `codegraff://session-updated` event. Commands return the same DTO to the caller, but live streaming depends on events (`bridge/emitter.rs:12`, `runtime/simple.rs:783`).
-
-3. **Terminal I/O is real PTY I/O via `portable_pty` with dedicated OS threads.** Each `terminal_id` gets a `spawn_terminal_session` that creates a PTY pair, spawns the shell, and runs two blocking threads (reader + process waiter) that emit output/exit events into the Tauri event bus. This is entirely separate from the `graff` child process system (`terminal.rs:172–299`).
-
----
-
-## 1 Open Question
-
-- **How does the frontend resume a persisted conversation after restart?** The backend loads `conversations.json` into `RuntimeState` on startup, but the comments state that “live `graff` sessions are not restored — continuing a loaded chat starts a fresh session without the model's prior context.” It is unclear whether the frontend replays the loaded messages for display only, or if there is a plan to serialize/resume the actual `graff` process state (context/KV cache) in the future.
-
-[subagent sa-002-0e4162b9 · inspect: .graff/subagents/sa-002-0e4162b9.md]
-
-### Explore SDK packages
-# SDK Analysis Report — `sdk/` directory
-
-## 1. Python SDK (`sdk/py/`)
-
-### What it does
-The Python SDK provides two transport variants for driving the harness agent:
-
-- **`Harness`** — spawns a local `graff --json` (or `harness --json`) subprocess and speaks the JSONL stdio protocol directly.
-- **`RemoteHarness`** — connects to a remote `harness serve` bridge over HTTP and exposes the same method surface (`sdk/py/harness_sdk.py:306-432`).
-
-Both classes are context managers (`__enter__`/`__exit__`) and support multi-turn stateful conversations, system-prompt mutation, evaluation scoring for the DGM loop, and OTLP telemetry reporting.
-
-### API surface
-| Method | Purpose | File:Line |
-|--------|---------|-----------|
-| `Harness(...)` | Spawn subprocess with `--json`, optional `--yolo`, `--model`, `--system-prompt`, `--append-system-prompt` | `sdk/py/harness_sdk.py:148-180` |
-| `Harness.chat(text)` | Send a user turn; yield NDJSON events (`text`, `tool_call`, `tool_result`, `turn`, `error`) until terminal | `sdk/py/harness_sdk.py:182-207` |
-| `Harness.ask(text)` | One-shot: run a turn and return just the final assistant text | `sdk/py/harness_sdk.py:209-217` |
-| `Harness.answer(...)` | Reply to an in-flight `ask_user` tool call while consuming `chat()` | `sdk/py/harness_sdk.py:219-228` |
-| `Harness.set_system_prompt(text, append=False)` | Replace or extend the system prompt between turns; blocks on harness ack | `sdk/py/harness_sdk.py:230-255` |
-| `Harness.append_system_prompt(text)` | Convenience wrapper for `set_system_prompt(..., append=True)` | `sdk/py/harness_sdk.py:257-259` |
-| `Harness.score(...)` | Write a DGM evaluation record into `harness.trajectory.jsonl` with optional HMAC provenance | `sdk/py/harness_sdk.py:261-298` |
-| `Harness.pull_elites(...)` | GET `/v1/elites` from the telemetry collector (not the subprocess) | `sdk/py/harness_sdk.py:300-323` |
-| `Harness.close()` | Close stdin, wait up to 15 s for graceful exit, then terminate | `sdk/py/harness_sdk.py:325-336` |
-| `RemoteHarness(...)` | Create or attach to a remote session via `POST /v1/sessions` | `sdk/py/harness_sdk.py:343-360` |
-| `RemoteHarness.chat(text)` | Stream NDJSON events from the bridge | `sdk/py/harness_sdk.py:380-393` |
-| `RemoteHarness.ask(text)` | One-shot remote turn | `sdk/py/harness_sdk.py:395-403` |
-| `RemoteHarness.answer(...)` | POST an answer to the bridge | `sdk/py/harness_sdk.py:405-413` |
-| `RemoteHarness.set_system_prompt(...)` | Mutate prompt remotely | `sdk/py/harness_sdk.py:415-427` |
-| `RemoteHarness.score(...)` | Write score remotely | `sdk/py/harness_sdk.py:429-445` |
-| `RemoteHarness.close()` | DELETE the remote session | `sdk/py/harness_sdk.py:452-457` |
-
-Free functions:
-- `prompt_fingerprint(text)` → SHA-256 first 8 bytes hex (`sdk/py/harness_sdk.py:103-107`)
-- `score_signature(key, ...)` → HMAC of a score record (`sdk/py/harness_sdk.py:109-122`)
-- `verify_score(key, rec)` → boolean validity check (`sdk/py/harness_sdk.py:124-137`)
-
-### How it communicates
-**Local (`Harness`):** Uses `subprocess.Popen` with `stdin=subprocess.PIPE, stdout=subprocess.PIPE` (`sdk/py/harness_sdk.py:175`). The parent writes one JSON object per line to stdin (`{"type":"user","text":"..."}`) and reads NDJSON events from stdout. If the process exits mid-turn without emitting `turn` or `error`, the SDK reports an error to OTLP telemetry and raises `RuntimeError` (`sdk/py/harness_sdk.py:205-207`).
-
-**Remote (`RemoteHarness`):** Uses stdlib `urllib.request` only—no external dependencies. It POSTs to `/v1/sessions` to create a session, then POSTs subsequent requests to `/v1/sessions/{session_id}` and yields NDJSON lines from the response body (`sdk/py/harness_sdk.py:362-378`). Authentication is via an optional `Authorization: Bearer <token>` header (`sdk/py/harness_sdk.py:365-367`).
-
-**Demo:** `sdk/py/demo.py` demonstrates one-shot `ask()`, streamed `chat()` with live tool use, multi-turn persistence, custom prompts via `AGENTS.md` in `cwd`, and full `system_prompt=` replacement (`sdk/py/demo.py:1-110`).
-
----
-
-## 2. TypeScript SDK (`sdk/ts/`)
-
-### What it does
-The TypeScript SDK mirrors the Python SDK but splits into two entry points:
-
-- **`harness.ts`** — Node.js-only client using `node:child_process` and `node:readline` to spawn the local binary.
-- **`remote.ts`** — Edge-runtime client using only `fetch` + Web Streams (no `node:` imports), runnable on Cloudflare Workers, Deno, Bun, browsers, and Node ≥ 18 (`sdk/ts/remote.ts:1-10`).
-
-Both expose identical event types (`Event` union), `ModelName`, `ToolName`, and `ProviderId` unions, plus `promptFingerprint`, `fleetSignal`, and `pullElites` helpers.
-
-### API surface
-| Export | Kind | Purpose | File:Line |
-|--------|------|---------|-----------|
-| `Harness` | class | Node stdio subprocess client | `sdk/ts/harness.ts:157-267` |
-| `Harness.init(opts)` | static | Factory alias for `new Harness(opts)` | `sdk/ts/harness.ts:172` |
-| `Harness.chat(input)` | async generator | Stream events until `turn`/`error` | `sdk/ts/harness.ts:189-205` |
-| `Harness.ask(input)` | async | Return final assistant text | `sdk/ts/harness.ts:207-215` |
-| `Harness.answer(input)` | method | Write answer to stdin for `ask_user` | `sdk/ts/harness.ts:217-223` |
-| `Harness.setSystemPrompt(text, append)` | async | Replace/extend prompt; resolves on ack | `sdk/ts/harness.ts:225-238` |
-| `Harness.score(...)` | async | Write DGM score record | `sdk/ts/harness.ts:248-261` |
-| `Harness.pullElites(...)` | async | GET `/v1/elites` from collector | `sdk/ts/harness.ts:263-281` |
-| `Harness.session()` | method | Return `HarnessSession` wrapper | `sdk/ts/harness.ts:287` |
-| `HarnessSession` | class | Thin wrapper over `Harness` for parity with codegraff’s `GraffSession` | `sdk/ts/harness.ts:291-301` |
-| `runAgent(opts)` | async generator | One-shot: spawn, chat, close | `sdk/ts/harness.ts:305-312` |
-| `RemoteHarness` | class | Fetch-based remote bridge client | `sdk/ts/remote.ts:73-181` |
-| `RemoteHarness.init(opts)` | static | Factory | `sdk/ts/remote.ts:85` |
-| `RemoteHarness.chat(input)` | async generator | Stream NDJSON from bridge | `sdk/ts/remote.ts:127-140` |
-| `RemoteHarness.ask(input)` | async | One-shot remote | `sdk/ts/remote.ts:142-150` |
-| `RemoteHarness.answer(...)` | async | POST answer to bridge | `sdk/ts/remote.ts:152-163` |
-| `RemoteHarness.setSystemPrompt(...)` | async | Remote prompt mutation | `sdk/ts/remote.ts:165-174` |
-| `RemoteHarness.score(...)` | async | Remote score write | `sdk/ts/remote.ts:176-188` |
-| `runAgentRemote(opts)` | async generator | One-shot remote | `sdk/ts/remote.ts:193-200` |
-
-### How it communicates
-**Local (`harness.ts`):** Spawns `opts.binary ?? defaultBinary()` with `spawnArgs(opts)` (always includes `--json`). Stderr is inherited (`stdio: ["pipe", "pipe", "inherit"]`) so tool progress prints directly to the terminal (`sdk/ts/harness.ts:165-167`). A `readline.Interface` pumps stdout line-by-line into an internal queue/buffer. If the process errors or closes before a terminal event, `reportError` fires OTLP telemetry and the waiting promise rejects (`sdk/ts/harness.ts:180-184`).
-
-**Remote (`remote.ts`):** Uses `fetch` exclusively. `create()` POSTs to `/v1/sessions` with `{model?, yolo?, system_prompt?, append_system_prompt?}` and stores the returned `session_id` (`sdk/ts/remote.ts:95-110`). Every turn POSTs to `/v1/sessions/{id}` and the response body is parsed via `ndjson()`, a Web-Streams reader that yields parsed JSON lines (`sdk/ts/remote.ts:47-71`). If the stream ends without a terminal event, it throws `Error: bridge stream ended mid-turn`.
-
----
-
-## 3. SDK Generation Script (`sdk/generate.py`)
-
-### What it does
-`generate.py` is a codegen tool that reads the JSON schema emitted by `graff --schema` and produces all three SDK artifacts:
-
-- `sdk/ts/harness.ts` — Node.js stdio client
-- `sdk/ts/remote.ts` — Edge-safe fetch client
-- `sdk/py/harness_sdk.py` — Python stdio + urllib client
-
-The script is the **single source of truth** for SDK types; the generated files carry the header `"AUTO-GENERATED by sdk/generate.py from \`harness --schema\`. Do not edit."` (`sdk/generate.py:1`, `sdk/ts/harness.ts:1`, `sdk/py/harness_sdk.py:1`).
-
-### How it works
-1. **Schema ingestion** (`load_schema`) accepts:
- - `stdin` (e.g. `graff --schema | python3 sdk/generate.py`)
- - `--schema FILE`
- - `--harness BIN` (runs the binary for you)
- (`sdk/generate.py:16-34`)
-
-2. **Type extraction** pulls three arrays from the schema:
- - `models` → `ModelName` union / `MODELS` constant
- - `tools` → `ToolName` union / `TOOLS` constant
- - `providers` → `ProviderId` union / `PROVIDERS` constant
- - `version` → `HARNESS_VERSION` constant
- (`sdk/generate.py:37-42`, `sdk/generate.py:44-47`, `sdk/generate.py:431-438`)
-
-3. **Template generation** uses large Python f-string templates that embed the sorted unions and version. The templates contain the full class implementations (including telemetry, prompt fingerprinting, score signing, event parsing, etc.). No logic is synthesized from the schema beyond the literal type constants and version string; the rest is static boilerplate maintained inside `generate.py` itself.
-
-4. **Output** writes all three files via `write()` and prints byte counts (`sdk/generate.py:439-445`).
-
-### CI enforcement
-The `.github/workflows/sdk.yml` workflow publishes the committed SDKs to npm and PyPI on every `sdk-v*` tag, but the generation must be run locally before tagging because the action does **not** regenerate— it ships what is committed (`sdk/README.md:11-15`, `.github/workflows/sdk.yml:1-8`). The `.github/workflows/ci.yml` also includes a `sdk` job that validates the committed SDKs without requiring a Zig build (`codedb` context for `.github/workflows/ci.yml:10`).
-
----
-
-## 4. Relationship to the Broader Project
-
-### Verified facts
-1. **The core is a Zig CLI binary.** The project’s engine lives in `src/main.zig` (~1,250 lines of Zig 0.16) and compiles to a single executable named `graff` (formerly `harness`) (`architecture.md:1-3`, `build.zig:32-35`).
-2. **The SDKs are thin clients over that binary.** They do not reimplement the agent loop, LLM provider routing, tool dispatch, or context compaction. They only wrap the `--json` stdio protocol or the HTTP bridge (`harness serve`) (`sdk/README.md:1-4`, `sdk/ts/harness.ts:155-157`).
-3. **`harness --schema` is the contract.** The Zig binary emits its own interface (models, tools, providers, event protocol, version). The generation script consumes this JSON to keep the SDK types in lockstep with the binary (`sdk/generate.py:1-8`, `sdk/README.md:11-15`).
-4. **`harness serve` is an HTTP bridge.** The remote clients do not talk to a separate server implementation. The server side of the bridge still runs the same `harness --json` child per session; one POST equals one protocol request, streamed back as NDJSON (`sdk/ts/remote.ts:1-10`, `sdk/py/harness_sdk.py:338-341`).
-5. **The DGM evolution loop is built on the SDK.** `examples/dgm_loop.py` imports `Harness`, `prompt_fingerprint`, and `verify_score` from the Python SDK to implement a Darwin Gödel Machine that mutates system prompts, scores them via a replay judge, and writes lineage into the trajectory archive (`examples/dgm_loop.py:18-20`, `examples/dgm_loop.py:101-110`).
-6. **Telemetry is shared.** Both the harness binary and the SDKs report to the same OTLP endpoint (`https://harness-telemetry.rachpradhan.workers.dev` by default) using the same opt-out environment variables (`GRAFF_NO_TELEMETRY`, `OTEL_EXPORTER_OTLP_ENDPOINT`) (`sdk/py/harness_sdk.py:54-96`, `sdk/ts/harness.ts:79-121`).
-7. **The CLI was renamed.** The default binary is now `graff`, with `harness` as a fallback compatibility name (`sdk/py/harness_sdk.py:139-142`, `sdk/ts/harness.ts:133-140`).
-
-### Inferred but not directly verified
-- The `harness serve` mode is likely implemented inside `src/main.zig` as an HTTP server (referenced in `architecture.md` under “Where this could go next” and in `sdk/ts/remote.ts` comments), but I did not read the Zig server code directly because `src/main.zig` is not indexed by `codedb` in this output.
-
----
-
-## Top 3 Load-Bearing Facts
-
-1. **The SDKs are auto-generated from `graff --schema`; the schema JSON is the only source of truth for models, tools, providers, and the event protocol.** Any drift between the binary and the SDKs is caught by regenerating via `sdk/generate.py` (`sdk/generate.py:1`, `sdk/py/harness_sdk.py:1`, `sdk/ts/harness.ts:1`).
-2. **Both Python and TypeScript SDKs are thin wrappers: they spawn the local Zig binary (`Harness`) or talk HTTP to a bridge that still spawns the binary per session (`RemoteHarness`).** They do not contain the agent loop, tool implementations, or LLM logic (`sdk/py/harness_sdk.py:148-180`, `sdk/ts/harness.ts:157-167`, `sdk/README.md:1-4`).
-3. **The `score()` and `pull_elites()` APIs exist to support the Darwin Gödel Machine evolution loop.** The SDK is not just a chat client; it is the programmatic interface for automated prompt evolution, with HMAC-signed fitness records and fleet telemetry (`sdk/py/harness_sdk.py:261-323`, `examples/dgm_loop.py:1-110`).
-
----
-
-## 1 Open Question
-
-**Does `harness serve` (the HTTP bridge) live entirely in `src/main.zig`, or is it a separate binary / wrapper?** The SDKs and docs refer to it as the server side of the remote transport, but I did not inspect the Zig source to confirm whether it is a built-in subcommand (`graff serve`) or an external component.
-
-[subagent sa-003-ca4e54cc · inspect: .graff/subagents/sa-003-ca4e54cc.md]
-
-### Explore iOS app
-# iOS Companion App (`apps/ios/`) — Structured Report
-
-## 1. Overall App Structure
-
-### Source layout
-| File | Purpose | Lines |
-|------|---------|-------|
-| `GraffApp.swift` | `@main` entry point, app-level models, sample data, Liquid Glass helpers | 165 |
-| `GraffServeClient.swift` | NDJSON-over-HTTP transport that speaks to `graff serve` | 98 |
-| `ChatView.swift` | Session detail: chat bubbles, task progress, composer, plan decision bar | 226 |
-| `SessionsListView.swift` | Root list of sessions with status chips and progress | 66 |
-| `Info.plist` | Bundle metadata, iOS 26.0 minimum, local-network ATS exception | 29 |
-
-### Entry point & launch modes
-- `GraffApp` (`GraffApp.swift:4`) is a `SwiftUI.App` whose `WindowGroup` shows either `AutoTestView` (when `CommandLine.arguments.contains("--autotest")`) or `SessionsListView`.
-- `AutoTestView` (`GraffApp.swift:19`) opens the first sample session (`sampleSessions[0]`) and passes `autoSend: "Reply with one short sentence confirming the serve transport works."` to `ChatView`. This is a CI/automation gate: it verifies the live transport on the simulator without manual tapping.
-
-### Models (all in `GraffApp.swift`)
-- **`AgentSession`** (`GraffApp.swift:101`): identity (`id`, `title`, `model`), `status: SessionStatus`, `todos: [TodoItem]`, `messages: [ChatMessage]`, `planPending: Bool`, and a computed `progress` tuple.
-- **`ChatMessage`** (`GraffApp.swift:42`): `role: Role` (`.user` / `.assistant`), `text`, optional `reasoning`.
-- **`SessionStatus`** (`GraffApp.swift:73`): `working`, `waiting`, `idle`, `done` with symbols/tints.
-- **`TodoStatus`** (`GraffApp.swift:49`): `pending`, `inProgress`, `completed` with SF Symbols.
-
-### Configuration
-- **`project.yml`** (`project.yml:1`): xcodegen spec. Target name `Graff`, iOS platform, deployment target **iOS 26.0**, Swift 6.0, `GENERATE_INFOPLIST_FILE: NO`, device family `1` (iPhone only).
-- **`Info.plist`** (`Info.plist:10`): `CFBundleIdentifier` is `com.codegraff.graff`, `MinimumOSVersion` is `26.0`, and it sets `NSAllowsLocalNetworking` to `true` under `NSAppTransportSecurity` so the simulator can reach `127.0.0.1:8787`.
-
-### Inferred design note
-The Liquid Glass extensions (`glassPanel`, `glassCapsule`) and iOS 26.0 floor suggest this UI is built for the very latest SwiftUI/iOS 26 visual language.
-
----
-
-## 2. `GraffServeClient.swift` — The NDJSON Protocol Client
-
-### Transport contract
-- The client implements the **local `serve` transport** described in `architecture.md` and the TS/Python SDKs (`sdk/ts/remote.ts`, `sdk/py/harness_sdk.py`).
-- Two HTTP calls are required per turn:
- 1. `POST /v1/sessions` → returns `{session_id}` (`GraffServeClient.swift:47`).
- 2. `POST /v1/sessions/{id}` with a JSON payload `{"type": "user", "text": text}` → streamed back as **NDJSON** (one JSON object per line) until a terminal event (`turn` or `error`) (`GraffServeClient.swift:57`).
-
-### Request builder
-- `base` defaults to `http://127.0.0.1:8787` (`GraffServeClient.swift:25`).
-- Always sends `Content-Type: application/json` and `User-Agent: Graff-iOS/0.1` (`GraffServeClient.swift:33`). The comment explicitly states the UA is required because *"CF WAF rejects empty UA on the gateway path"*.
-- Optional bearer token: `Authorization: Bearer <token>` (`GraffServeClient.swift:34`).
-
-### Event decoding
-- `GraffEvent` enum (`GraffServeClient.swift:4`) covers:
- - `.reasoning(String)`
- - `.text(String)`
- - `.toolCall(name: String)`
- - `.turn(text: String, contextTokens: Int, costUSD: Double)`
- - `.error(String)`
- - `.other(String)` (fallback for unknown types)
-- `decode(_:)` (`GraffServeClient.swift:82`) uses `JSONSerialization` to parse each line and switches on the `type` field:
- - `reasoning`, `text`, `tool_call`, `turn`, `error` are mapped explicitly.
- - Anything else becomes `.other(type)`.
-
-### Streaming implementation
-- `streamTurn(sessionID:text:)` returns an `AsyncThrowingStream<GraffEvent, Error>` (`GraffServeClient.swift:57`).
-- It uses `URLSession.shared.bytes(for:)` to get an `AsyncBytes` sequence, iterates `bytes.lines`, and yields decoded events.
-- **Termination rules**: it stops yielding and finishes the stream when it encounters either `.turn` or `.error` (`GraffServeClient.swift:69-70`).
-- Cancellation is wired up: `continuation.onTermination` cancels the `Task` reading the bytes (`GraffServeClient.swift:77`).
-
-### Inferred design note
-A code comment (`GraffServeClient.swift:23`) states: *"The `cube` transport is this same client with a different base URL + a tenant capability header."* The current struct only has `base` and `token`; the capability header is not yet implemented.
-
----
-
-## 3. Main UI: `ChatView.swift` & `SessionsListView.swift`
-
-### `SessionsListView` — Root navigation
-- Wraps a `NavigationStack` containing a `List` of `NavigationLink`s (`SessionsListView.swift:3`).
-- Each row is bound to an `AgentSession` via `ForEach($sessions)` and pushes `ChatView(session: $session)` on tap.
-- `SessionRow` (`SessionsListView.swift:28`) displays:
- - Title + `StatusChip` (tinted capsule with SF Symbol).
- - Model name, todo progress (`done/total`), and `lastActivity` timestamp.
- - A `ProgressView` tinted to the session status.
-- The toolbar has a `+` button (no-op implementation: `Button { }`).
-
-### `ChatView` — Session detail
-- Takes `@Binding var session: AgentSession` and an optional `autoSend: String?` (`ChatView.swift:3`).
-- **Layout** (top to bottom):
- 1. `TaskProgressCard` — shows todos with status symbols, pulse animation on `.inProgress`, and strikethrough for completed items (`ChatView.swift:106`).
- 2. `ScrollViewReader` + `ScrollView` with `LazyVStack` of `MessageBubble`s. Auto-scrolls to the last message when its text changes (`ChatView.swift:23`).
- 3. `PlanDecisionBar` — shown conditionally when `session.planPending` is true; has "Keep planning" and "Implement plan" buttons (`ChatView.swift:185`).
- 4. `Composer` — multiline `TextField` (axis `.vertical`, line limit 1…4) plus send button; disabled while `streaming` is true (`ChatView.swift:205`).
-
-### `MessageBubble` & assistant states
-- `MessageBubble` (`ChatView.swift:136`) left/right aligns based on role.
-- If `message.reasoning` is present, it shows a `Label` with `systemImage: "brain"` in caption italic style.
-- If the assistant message text is empty and reasoning is empty, it renders a `TypingIndicator` (three pulsing dots) so an in-flight turn never looks like a stuck empty bubble (`ChatView.swift:167`).
-
-### Turn lifecycle (`send` → `runTurn`)
-- `send()` (`ChatView.swift:64`) appends a user `ChatMessage`, sets `streaming = true`, `session.status = .working`, and kicks off `runTurn` in a `Task`.
-- `runTurn(_:)` (`ChatView.swift:75`) is `@MainActor`:
- - Lazily creates a remote session via `client.createSession(model: session.model)` if `serveSessionID` is nil.
- - Appends a blank assistant message.
- - Iterates `client.streamTurn` and mutates the message in place:
- - `.reasoning` appends to `message.reasoning`.
- - `.text` appends to `message.text`.
- - `.turn` overwrites `message.text` with the final text.
- - `.error` sets `message.text` to `"Error: " + m`.
- - `.toolCall` and `.other` are ignored (`break`).
- - On catch, appends a transport error message.
- - Always sets `session.status = .idle` in `defer { streaming = false }`.
-
-### Inferred design note
-`ChatView` is purely optimistic/in-memory: there is no CoreData, no SwiftData, no file persistence. Session state survives only while the view hierarchy retains it.
-
----
-
-## 4. Connection to the Core Harness, Data Streamed, and Protocol Handling
-
-### How it connects
-- The iOS app targets `http://127.0.0.1:8787`, which is the default address of `graff serve` (or `harness serve`) running on the host Mac.
-- Because the iOS simulator shares localhost with the host, `127.0.0.1:8787` from the simulator reaches the host's serve process (`GraffServeClient.swift:20` comment).
-
-### What data streams
-- **Request** (turn): `{"type": "user", "text": "<prompt>"}`.
-- **Response**: NDJSON lines, each a JSON object. The iOS client specifically handles:
- - `reasoning` → shown in the bubble as a brain-labeled italic caption.
- - `text` → appended to the assistant bubble.
- - `turn` → final text + metadata (`context_tokens`, `cost_usd`). The client replaces the bubble text with the final `turn.text`.
- - `error` → displayed as `"Error: ..."`.
- - `tool_call` → **ignored** (`ChatView.swift:97`).
-
-### Protocol handling characteristics
-- **Session-oriented**: A `serveSessionID` is created once per `ChatView` and reused for subsequent turns.
-- **Terminal-event driven**: The stream ends on `.turn` or `.error`. This matches the Python/TS SDK behavior (`sdk/py/harness_sdk.py:447`, `sdk/ts/remote.ts:165`).
-- **No interactive tool loop**: Unlike the Python/TS SDKs, the iOS client does not currently handle `ask_user` or multi-step `tool_call` / `tool_result` cycles. It treats the stream as a single-turn text response.
-- **NDJSON parsing**: Uses `JSONSerialization` (not `Codable`) for line-by-line decoding, which is tolerant of unknown fields.
-
-### Verified cross-reference
-The architecture document (`architecture.md`) describes the core harness as a Zig REPL/agent that can run in `--json` mode (stdio) or `serve` mode (HTTP). The iOS client consumes the *serve* bridge, where each session is a real `harness --json` child and one POST equals one protocol request, streamed back as NDJSON (`sdk/ts/remote.ts:8` comment).
-
----
-
-## 5. Build / Automation Scripts
-
-### `build-sim.sh` (`apps/ios/build-sim.sh`)
-- **No Xcode required**. Compiles the app directly with `swiftc` for the iOS simulator.
-- Key steps:
- 1. Sets `TARGET=arm64-apple-ios26.0-simulator` and fetches the iPhoneSimulator SDK path via `xcrun`.
- 2. `rm -rf build && mkdir -p build/Graff.app`.
- 3. Compiles `Graff/Sources/*.swift` into `build/Graff.app/Graff` with `-emit-executable`.
- 4. Copies `Info.plist` into the app bundle.
- 5. Boots the simulator (`xcrun simctl boot`), opens the Simulator app.
- 6. Installs and launches the bundle (`com.codegraff.graff`).
- 7. Waits 4 seconds and screenshots `build/launch.png`.
-- Default device is `iPhone 17 Pro`, overridable via `SIM` env var.
-
-### `autotest.sh` (`apps/ios/autotest.sh`)
-- **Smoke test for the live transport**.
-- Terminates any running instance of the app, then launches it with `--autotest`.
-- Waits 16 seconds for the auto-fired turn to complete.
-- Captures a screenshot to `build/autotest.png`.
-- Used to verify the full stack (simulator → `graff serve` → NDJSON stream → UI) without human interaction.
-
-### `recap.sh` (`apps/ios/recap.sh`)
-- **Multi-stage screenshot capture for documentation/demos**.
-- Launches with `--autotest`, then takes three timed screenshots:
- - `sleep 5` → `build/cap_typing.png` (should catch the `TypingIndicator` while waiting for the first token).
- - `sleep 3` → `build/cap_mid.png` (partial stream).
- - `sleep 8` → `build/cap_reply.png` (final response).
-- These screenshots are likely the ones referenced in the repo (existing `build/cap_*.png` files).
-
----
-
-## Verified vs. Inferred
-
-| Claim | Status | Evidence |
-|-------|--------|----------|
-| The app uses the same NDJSON contract as the TS/Python SDKs | **Verified** | `sdk/ts/remote.ts:8`, `sdk/py/harness_sdk.py`, `GraffServeClient.swift:20` |
-| The app ignores `tool_call` events | **Verified** | `ChatView.swift:97` (`case .toolCall, .other: break`) |
-| Build scripts require no Xcode project | **Verified** | `build-sim.sh` calls `swiftc` directly; `project.yml` is only for ongoing Xcode work (`project.yml:2`) |
-| iOS 26.0 is required | **Verified** | `project.yml:8`, `Info.plist:18` (`MinimumOSVersion` 26.0) |
-| The `cube` transport is planned but not implemented | **Inferred** | `GraffServeClient.swift:23` comment says it is the same client with different base + header, but no header field exists besides `token` |
-| `sampleSessions` is hardcoded demo data | **Verified** | `GraffApp.swift:111` static constant array |
-
----
-
-## 3 Load-Bearing Facts
-
-1. **`GraffServeClient` consumes the serve NDJSON stream via `AsyncThrowingStream`, terminating on `.turn` or `.error` events, and decodes only a subset of the full harness event contract** (`GraffServeClient.swift:57-82`, `ChatView.swift:75-104`).
-2. **The entire build/install/run cycle is scriptable without Xcode** (`build-sim.sh` compiles with `swiftc`, `autotest.sh` gates the live transport, and `recap.sh` captures demo screenshots), making the iOS app a lightweight CI-verified frontend.
-3. **The iOS app is a thin, in-memory client with no persistence layer**: sessions are hardcoded (`sampleSessions`), state lives in `@State`/`@Binding`, and the connection is to `127.0.0.1:8787` on the host Mac via the simulator's shared localhost (`GraffApp.swift:111`, `GraffServeClient.swift:25`, `Info.plist` local-network exception).
-
----
-
-## 1 Open Question
-
-**How will the iOS app handle interactive tool loops** (e.g., `ask_user`, `tool_call`/`tool_result` cycles, or multi-turn streaming) **when `ChatView.runTurn` currently breaks the stream on `.turn`/`.error` and explicitly ignores `.toolCall` events?** The full harness protocol supports these (`sdk/ts/remote.ts` Event union includes `tool_call`, `ask_user`, `tool_result`), but the current UI has no affordances for answering in-flight questions or rendering tool execution steps.
-
-[subagent sa-004-d913162c · inspect: .graff/subagents/sa-004-d913162c.md]
-
-### Explore examples and docs
-# Exploration Report: `examples/`, `docs/`, `architecture.md`, and `packages/diffs/`
-
-## 1. `architecture.md` — Overall System Architecture
-
-**`simple-harness`** (also called `graff`) is a terminal agentic loop implemented in ~1,250 lines of Zig 0.16 with **zero third-party dependencies** — only the Zig standard library (`architecture.md:1-5`). It compiles to a single self-contained executable (~1.69 MB on arm64) that talks to multiple LLM providers, runs tools (including subagents and MCP servers) in parallel, and compacts its own context.
-
-### Core loop (`Agent.runTurn`)
-The unit of execution is a single `Agent` struct that owns a message history (`std.json.Array`), a provider, an arena, and the loop methods (`architecture.md:33-37`). The root REPL agent and every subagent are the **same type**; a subagent is just an `Agent` with `sub = true`, a fresh arena, empty history, and `out = null` (`architecture.md:38-40`).
-
-`runTurn` works as follows:
-1. `buildBody` serializes the request for the current provider.
-2. `post` sends it via the thread-safe `std.http.Client.fetch`.
-3. `stepAnthropic` / `stepOpenAI` / `stepResponses` parse the response, echo the assistant turn into history verbatim, collect tool calls, dispatch them via `runTools`, append results, and return either final text (turn done) or `null` (loop again) (`architecture.md:41-48`).
-
-### Providers
-The system decouples **wire format** (`Provider.Kind`: `anthropic`, `openai`, `responses`) from **auth style** (`Provider.Auth`: `x_api_key`, `bearer`) (`architecture.md:50-54`). The `provider_specs` table is the single source of truth. Supported providers include anthropic, codegraff, deepseek, openai, minimax, xiaomi, codex (ChatGPT OAuth), and claude (Claude Code OAuth) (`architecture.md:63-73`). `Provider.context` drives per-model compaction at 80% of the context window.
-
-### Streaming
-Root-agent requests stream on **all three** wire formats using SSE. `request()` decides per call whether to stream (`live = !sub && out != null && !stream_quiet`). After streaming deltas to the user, the buffered events are **reassembled** into the exact non-streaming response shape so that `step*`, history echo, compaction, and `/save`/`/resume` are untouched (`architecture.md:97-112`).
-
-### Tools
-Three kinds, all dispatched through `runTools` (`architecture.md:141`):
-1. **Built-in** (`bash`, `read_file`, `edit_file`, `write_file`, `subagent`, `workflow`) — run on the `std.Io` thread pool. `workflow` is dynamic workflows as data: sequential phases of parallel subagents with `{{prev}}` substitution (`architecture.md:142-147`).
-2. **Meta** (`todo_write`, `todo_read`, `attempt_completion`, `ask_user`) — handled inline by the orchestrator (`handleMeta`), never on a pool thread. They act on the agent/conversation itself (`architecture.md:148-152`).
-3. **MCP** — discovered at runtime from `.mcp.json`, namespaced `mcp__<server>__<tool>`, dispatched to `mcp.Registry.call` (`architecture.md:153-154`).
-
-### Permission model
-State-changing tools run behind a shared `Approvals` struct backed by an `Io.Mutex` (`architecture.md:156-157`):
-- `gateTool` (root only) covers `bash`, `write_file`, `edit_file`, and MCP calls. Unapproved calls prompt on stdin; approval keys are the bash command's first word or the tool name (`architecture.md:159-162`).
-- Subagents are gated structurally: bash is allowlist-only, file writes are path-confined, MCP isn't exposed (`architecture.md:168-170`).
-- **Path confinement** (`confinedPath`): file tools reject absolute paths and `..`, confining them to the cwd subtree. This is **not** bypassed by `/yolo` (`architecture.md:175-176`).
-- **`/yolo`** lifts the prompt gate and the bash cwd-lock, but never lifts `confinedPath` (`architecture.md:178-179`).
-
-### Parallelism and subagents
-`runTools` separates meta calls (inline) from external calls, then fans them out with `io.async` — one `Future` per call — and awaits them in order. Because subagents are external tool calls, three subagents requested in one assistant message run concurrently on the pool, each making its own HTTPS calls through the shared client (`architecture.md:181-187`). Depth is capped at one level; subagents get only the base tool set (no `subagent`, no MCP, no meta tools) (`architecture.md:189-194`).
-
-### MCP client (`src/mcp.zig`)
-The harness is an MCP **client**. `Registry.init` reads `.mcp.json`, spawns stdio servers, performs JSON-RPC handshake (`initialize` → `notifications/initialized` → `tools/list`), and registers each tool. It sanitizes schemas by recursively renaming `oneOf` to `anyOf` because OpenAI's validator rejects `oneOf` outright (`architecture.md:224-236`). `Registry.call` serializes `tools/call` behind an `Io.Mutex` because a server is one bidirectional pipe.
-
-### KV-cache and compaction
-The loop is structured for prefix cache hits: frozen system prompt, append-only message history, comptime tool-list rendering, and explicit `cache_control: {type: ephemeral}` breakpoints for Anthropic (`architecture.md:248-252`). Compaction is client-side and provider-agnostic: at 80% of the model's context window, the harness sends history plus a handoff instruction with no tools, forces a text summary, and replaces history with one user message embedding that summary (`architecture.md:280-285`).
-
-### Other key features
-- **Session persistence**: `/save` serializes `{provider, model, strict, messages}` to `<name>.session.json`; `/resume` parses it back (`architecture.md:257-261`).
-- **Lifecycle hooks**: `pre_tool`, `post_tool`, `turn_end` configured in `.harness/settings.json`. `pre_tool` is the only hook with power: exit 2 blocks the call (`architecture.md:290-327`).
-- **Tracing**: One shared `Tracer` writes to `harness.trace.jsonl` — one JSON line per event, flushed immediately (`architecture.md:329-334`).
-- **Strict mode**: `/strict` forces `tool_choice` so the model must call a tool every turn. Combined with `ask_user` and `attempt_completion`, *every* message is a tool call or tool result (`architecture.md:196-210`).
-
----
-
-## 2. `examples/` Scripts — What They Demonstrate
-
-### `dgm_loop.py` — The minimal Darwin Gödel Machine loop
-This is a ~110-line runnable proof of the DGM checklist using the Python SDK (`examples/dgm_loop.py:1-12`). It demonstrates:
-- **Genome**: a system prompt (auto-captured as `kind:"prompt"` in `harness.trajectory.jsonl`).
-- **Archive + lineage**: loaded from `harness.trajectory.jsonl` with `prompt_sha` parent-child edges.
-- **Modify**: the harness's own model mutates the parent prompt via `h.ask()`.
-- **Evaluate**: uses `replay_eval()` (Step 1 primary gradient) and `llm_tiebreak()` (secondary, capped).
-- **Select**: DGM parent selection via `sigmoid(score − frontier) × 1/(1+children)` (`examples/dgm_loop.py:72-84`).
-- **Score write-back**: `h.score()` with signed provenance (`judge_id`, `artifact_sha`, `eval_set_hash`) and HMAC verification when `GRAFF_SCORE_KEY_FILE` is set (`examples/dgm_loop.py:144-148`, `148-161`).
-
-It uses `Harness(yolo=True)` from `sdk/py/harness_sdk.py` and spawns subagents with per-child `system_prompt` overrides.
-
-### `replay_judge.py` — Step 1: Grounded, out-of-process evolution judge
-This is the primary fitness gradient. It runs a candidate system prompt against a held-out eval set of tasks with **deterministic assertions** — a shell command's exit code or a golden substring in the final report (`examples/replay_judge.py:1-12`). Key properties:
-- **Custody**: the eval set lives outside the editable tree (`GRAFF_EVAL_SET_FILE`); its sha256 is pinned (`GRAFF_EVAL_SET_HASH`). Hash mismatch → exit 3, fail-closed (`examples/replay_judge.py:35-51`).
-- **Hermetic**: each task runs in a fresh scratch directory so file assertions are isolated (`examples/replay_judge.py:93-96`).
-- **Speaks `--json` directly**: dependency-free, no SDK import; it drives `graff --json --yolo` as a subprocess and parses the NDJSON stream (`examples/replay_judge.py:55-91`).
-- **Efficiency gradient**: counts `tool_calls` and `cost` so once all tasks pass, economy (fewer tool calls) discriminates winners (`examples/replay_judge.py:123-130`).
-
-### `test_step1.py` — Proof obligations for the grounded judge
-Offline tests (no model calls) verify structural invariants (`examples/test_step1.py:1-12`):
-1. **Score-band invariant**: a variant failing ANY held-out task can never reach the promotable band (≥ 0.9). The worst gap is verified to be > 0 (`examples/test_step1.py:38-42`).
-2. **Fail-closed**: replay judge missing → score 0.0 (`examples/test_step1.py:44-48`).
-3. **Integrity exits**: missing eval set → exit 2; hash-pin mismatch → exit 3 (`examples/test_step1.py:56-64`).
-4. **Live Goodhart rejection**: a sabotage variant that claims success but does nothing gets a high `h.ask` score, yet `judge()` pins it ≤ 0.8 because the replay suite fails. An honest seed reaches ≥ 0.9 (`examples/test_step1.py:67-86`).
-
-### `edge-worker/` — Remote SDK in Cloudflare Workers
-Proof that the remote SDK runs in the real Workers runtime (`workerd`), where the native harness binary cannot run (`examples/edge-worker/README.md:1-4`). It demonstrates:
-- `src/remote.ts` is a vendored copy of `sdk/ts/remote.ts` (auto-generated from `harness --schema`), using **fetch + Web Streams only** — no `node:` imports (`examples/edge-worker/src/remote.ts:1-5`).
-- `src/index.ts` shows two modes: a default multi-turn session + one-shot, and a streamed one-shot turn via `?q=` query param (`examples/edge-worker/src/index.ts:12-36`).
-- The bridge is `harness serve` running elsewhere; `BRIDGE_URL` and `BRIDGE_TOKEN` are configured via env/secrets.
-
----
-
-## 3. `docs/` — Design Decisions and Future Plans
-
-### `hyperagents.md` — Swarm trajectories & the path to hyperagents
-- **Prompt heterogeneity**: the swarm now supports per-child `system_prompt` overrides (precondition for DGM-style evolution) (`docs/hyperagents.md:1-18`).
-- **Trajectory mapping**: `harness.trajectory.jsonl` holds DGM-archive-tree nodes (`kind:"turn"`, `"subagent"`, `"prompt"`, `"score"`) with `parent`, `prompt_sha`, `prompt_mutated`, and `task` fields (`docs/hyperagents.md:19-42`).
-- **Internal DGM-H design**: the loop itself belongs in SDK code (Python/TS), not the harness. The harness exposes primitives: editable program (`set_system_prompt`), modify (`subagent`/`workflow` with override), evaluate (driver-owned judge), archive (`trajectory.jsonl` + scores), and selection (`sigmoid(...) × 1/(1+children)`) (`docs/hyperagents.md:43-82`).
-- **MAP-Elites**: niches = agent types (e.g. reviewer, researcher). Elites live at `.harness/agents/<niche>.md` — one markdown per cell with frontmatter (`name`, `description`, `score`). The driver promotes challengers that beat the incumbent score (`docs/hyperagents.md:83-112`).
-- **Step 0 — Signed fitness channel**: HMAC-SHA256 over a canonical message (`v1\n{prompt_sha}\n{parent_sha}\n{score:.6f}\n...`) so forged score rows are detectable. Key lives outside cwd; verification is fail-closed (`docs/hyperagents.md:113-145`).
-- **Step 1 — Grounded replay judge**: held-out replay eval with deterministic assertions. Score bands: fail → 0.0; pass_rate < 1.0 → capped at 0.8; all pass → 0.9 + 0.1×efficiency. LLM tie-break only reorders already-passing variants (`docs/hyperagents.md:146-173`).
-- **Step 2 — Federated fleet evolution**: scaffolded but not fully built. The fleet is the archive. Thousands of installs generate/evaluate variants on their own providers. Central infra (`harness-telemetry` worker) does only cheap work: HMAC-verify, artifact re-check, SQL-aggregate, serve elites. Data model includes `harness_elites` table and `GET /v1/elites` endpoint (`docs/hyperagents.md:174-258`).
-
-### `install-flow.md` — Diagnosis & fix
-Documents a bug in the `curl | sh` install path (`docs/install-flow.md:1-3`):
-- **Root cause 1**: tarball layout mismatch. CI nests the binary under `graff-<target>/`, but hand-repacked macOS tarballs ship it flat. `fetch_release` assumed nested, failed with `No such file`, and because it ran inside `if ...`, `set -e` was suppressed, so it returned `rm -rf`'s status (0) and falsely reported "ok" (`docs/install-flow.md:20-28`).
-- **Root cause 2**: companion step called `codegraff.com/install-graff.sh` (the harness installer) instead of `codegraff.com/install.sh` (the tools installer), causing infinite recursion and hang (`docs/install-flow.md:29-33`).
-- **Fix**: robust binary location handling both flat and nested layouts, explicit `return 1` if binary didn't land, correct companion URL, and `curl --max-time 120` bound (`docs/install-flow.md:35-43`).
-
-### `memory-architecture.md` — First-class, evolvable memory layer
-- **Hard constraint**: memory must be **append-only context**, never prefix mutation, to preserve the KV-cache (`docs/memory-architecture.md:1-22`).
-- **MemoryDesign interface**: the evolvable unit with `retrieve`, `update`, and optional `eval` vtable. Fingerprinted (`memory_sha`) like prompts (`docs/memory-architecture.md:23-38`).
-- **Built-in designs**: `null`, `scratchpad`, `episodic`, `structured`, `engram`, `summary-tree`. File-backed under `.harness/memory/` by default; `engram` is an optional MCP upgrade (`docs/memory-architecture.md:39-58`).
-- **Scopes**: `session` (arena), `project` (cwd), `user` (`~/.simple-harness/memory/`), `fleet` (shared, evolved). Fleet scope requires a **code-execution gate** because an evolved memory Design is code that runs (`docs/memory-architecture.md:59-82`).
-- **Evolution**: coordinate-ascent with DGM (mutate persona) and ALMA (mutate memory design). Memory designs are evaluated on long-horizon tasks with outcome-only credit (`docs/memory-architecture.md:83-95`).
-
-### `zig-0.17-port-plan.md` — Zig 0.17 migration plan
-- **Status**: not started; graff stays on Zig 0.16 stable (`docs/zig-0.17-port-plan.md:1-3`).
-- **Dry run result**: the scary part — **182 `std.Io` uses** — showed **no breakage**. Mechanical fixes needed: `b.build_root` removed, `std.ascii.indexOfIgnoreCase` removed, `**` array-repeat operator in flux. Estimated effort: an afternoon (`docs/zig-0.17-port-plan.md:8-14`, `27-30`).
-- **Validation checklist**: `zig build`, `zig build test`, `test-json-controls.py`, real streaming call, GUI smoke test, README badge bump last (`docs/zig-0.17-port-plan.md:75-82`).
-
----
-
-## 4. `packages/diffs/` — What It Does and GUI Integration
-
-### Package purpose
-`@codegraff/diffs` is a **lightweight, dependency-free diff and file-change rendering package** with no Shiki dependency (`packages/diffs/package.json:1-4`). It is built as an ESM module with TypeScript, managed by bun.
-
-### Core modules
-- **`parse.ts`** (`packages/diffs/src/parse.ts`): Parses git-style unified diffs into a structured `ParsedPatch` model (`FileDiff[]`, `DiffHunk[]`, `DiffLine[]`). Tolerant of partial/synthetic patches; normalizes CRLF; handles `diff --git`, `new file mode`, `deleted file mode`, binary files, and hunk headers (`@@ -l,s +l,s @@`). Tracks per-file and total `additions`/`deletions` stats.
-- **`highlight.ts`** (`packages/diffs/src/highlight.ts`): A tiny, dependency-free syntax tokenizer per line. Supports 11 languages (`ts`, `js`, `py`, `rs`, `go`, `zig`, `json`, `css`, `shell`, `md`, `plain`). Tokenizes into `keyword`, `string`, `comment`, `number`, `punct`, `plain`. Per-line only — multi-line strings/comments are not tracked.
-- **`wordDiff.ts`** (`packages/diffs/src/wordDiff.ts`): Intra-line word diff using LCS (longest common subsequence). Splits lines into word-ish tokens, then computes `DiffSegment[]` (`same`/`added`/`removed`). Has a **200,000 cell budget**; if the LCS table would exceed that, it bails out to a single removed/added segment to avoid hanging/OOMing the tab during render.
-- **`types.ts`** (`packages/diffs/src/types.ts`): Shared TypeScript interfaces for `DiffLine`, `DiffHunk`, `FileDiff`, `ParsedPatch`, `DiffSegment`, `DiffStats`.
-
-### React components
-- **`PatchDiff.tsx`** (`packages/diffs/src/react/PatchDiff.tsx`): Top-level component. Takes a raw git patch string, parses it with `useMemo(parsePatch)`, and renders a list of files with optional file headers and stats badges (`added`/`deleted`/`renamed`).
-- **`DiffBody.tsx`** (`packages/diffs/src/react/DiffBody.tsx`): Renders the body of a single file. Applies **word-level intra-line diffing** by pairing consecutive deletion/addition runs and running `diffWords()` on each pair. Renders hunks with line numbers, `+`/`-`/`` signs, and syntax-highlighted content via `tokenizeLine`. For `DiffSegment` lines, it renders only the side that owns the change (e.g., `removed` spans only on the before side, `added` only on the after side).
-- **`FilesChanged.tsx`** (`packages/diffs/src/react/FilesChanged.tsx`): A collapsible file list. Each row shows path, badge, stats, and a toggle caret. Clicking expands to show the `PatchDiff` for that file. Uses `memo` for row performance.
-
-### Styling
-- `src/style.css` provides the base CSS classes (`cgd-root`, `cgd-file`, `cgd-line`, `cgd-gutter`, `cgd-word`, `cgd-tok`, etc.) (`packages/diffs/src/style.css`).
-- The GUI imports the style in `gui/src/main.tsx` (`import '@codegraff/diffs/style.css'`) and binds theme tokens in `gui/src/styles/diffs.css` so diffs adapt to light/dark mode.
-
-### GUI integration
-The package is used in two main GUI locations:
-
-1. **Chat activity results** (`gui/src/components/chat/activity-results/FileDiffResult.tsx:3`): Imports `PatchDiff` from `@codegraff/diffs/react`. Displays a file diff inside an `ActivityResultCard` with an "open in editor" button. Uses `options={{ lineDiffType: "word", showFileHeader: false }}` (`gui/src/components/chat/activity-results/FileDiffResult.tsx:91-95`).
-2. **Workspace changes pane** (`gui/src/components/workspace-board/ChangesPane.tsx:11`): Imports `PatchDiff` to render session file changes in a collapsible sidebar. Each `ChangeRow` uses `Collapsible` to expand/collapse the diff. Also uses `lineDiffType: "word"` and `showFileHeader: false` (`gui/src/components/workspace-board/ChangesPane.tsx:88-94`, `176-180`).
-
-The GUI's `package.json` declares `"@codegraff/diffs": "workspace:*"` and has a `"build:deps"` script that builds the diffs package first (`gui/package.json:11`, `20`).
-
----
-
-## Verified vs. Inferred
-
-| Claim | Status | Evidence |
-|---|---|---|
-| The harness is a single Zig binary with zero third-party deps | **Verified** | `architecture.md:1-5`, `build.zig` |
-| `dgm_loop.py` uses the Python SDK's `Harness` class and `h.score()` | **Verified** | `examples/dgm_loop.py:16`, `144-148` |
-| `replay_judge.py` speaks `--json` directly without SDK imports | **Verified** | `examples/replay_judge.py:55-91` (no `harness_sdk` import) |
-| `test_step1.py` verifies fail-closed behavior and score-band invariant | **Verified** | `examples/test_step1.py:38-64` |
-| `edge-worker` uses fetch + Web Streams with no node: imports | **Verified** | `examples/edge-worker/src/remote.ts:1-5`, `src/index.ts:12-36` |
-| `@codegraff/diffs` is used in GUI chat results and changes pane | **Verified** | `gui/src/components/chat/activity-results/FileDiffResult.tsx:3`, `gui/src/components/workspace-board/ChangesPane.tsx:11` |
-| The DGM federated fleet loop (Step 2) is fully implemented | **Inferred** | `docs/hyperagents.md:174-258` says "scaffolded" — migration and endpoints exist, but LCB + anomaly-ejection + auto-promote logic are TODO. |
-| The `MemoryDesign` interface is already in the Zig source | **Inferred** | `docs/memory-architecture.md:23-38` proposes the shape; it is a design document, not yet implemented code. |
-
----
-
-## 3 Most Load-Bearing Facts
-
-1. **The harness is a single ~1.7 MB Zig binary with zero dependencies** that runs an agentic loop with streaming, multi-provider support, parallel subagents, MCP client, and client-side compaction — all in ~1,250 lines of Zig 0.16 (`architecture.md:1-5`, `build.zig`).
-2. **The DGM evolution loop is closed and grounded** through a signed fitness channel (HMAC-SHA256) and a held-out replay judge with deterministic assertions, so that an LLM cannot "charm" its way to a high score without actually passing the tasks (`docs/hyperagents.md:113-173`, `examples/replay_judge.py:1-12`, `examples/test_step1.py:38-64`).
-3. **`@codegraff/diffs` is a zero-dependency diff rendering package** used by the GUI in both chat activity results and the workspace changes pane, featuring git patch parsing, per-line syntax highlighting, and LCS-based intra-line word diffing with a render-time cell budget to prevent tab hangs (`packages/diffs/src/parse.ts`, `packages/diffs/src/wordDiff.ts`, `gui/src/components/workspace-board/ChangesPane.tsx:11`).
-
----
-
-## 1 Open Question
-
-**How does the GUI plan to handle the federated fleet evolution telemetry and elite pulling?** The docs scaffold `GET /v1/elites` and SDK `pull_elites()` methods, but the GUI code (React + Tauri) does not yet appear to call these. Is the GUI intended to remain a passive consumer of the local harness binary, or will it eventually participate in the fleet loop by prompting users to opt-in and surfacing evolved personas?
-
-[subagent sa-005-47447216 · inspect: .graff/subagents/sa-005-47447216.md]
-
-## report
-
-# Unified Codebase Overview: `graff` / `simple-harness`
-
-## 1. Project Identity and Purpose
-
-**`graff`** (formerly `simple-harness`) is a self-contained AI agent harness implemented as a single Zig executable with **zero third-party dependencies**. It solves the problem of running a fast, portable, multi-provider LLM agent loop that can be driven from a terminal, a native GUI, language SDKs, or a mobile companion.
-
-The core binary (`src/main.zig`, `src/mcp.zig`) implements the full agentic loop—message history, streaming HTTP/SSE to Anthropic/OpenAI/Responses APIs, parallel tool execution, subagents, MCP client discovery, context compaction, and permission gating—all in one monolithic file. Every other component in the repository is a thin transport or presentation layer around this binary.
-
----
-
-## 2. High-Level Architecture
-
-```
-┌─────────────────────────────────────────────────────────────────────┐
-│ Presentation Layer │
-│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌────────────┐ │
-│ │ GUI (React) │ │ Python SDK │ │ TS SDK │ │ iOS (Swift)│ │
-│ │ + Tauri │ │ (sdk/py) │ │ (sdk/ts) │ │ App │ │
-│ └──────┬──────┘ └──────┬──────┘ └──────┬──────┘ └─────┬──────┘ │
-│ │ │ │ │ │
-│ └────────────────┴────────────────┘ │ │
-│ │ │ │
-│ ┌───────────────────────┴───────────────────────┐ │ │
-│ │ Transport / Bridge │ │ │
-│ │ ┌─────────────────────┐ ┌──────────────────┐ │ │ │
-│ │ │ Tauri Rust Backend│ │ HTTP Server │ │ │ │
-│ │ │ (gui/src-tauri/src)│ │ (graff serve) │ │ │ │
-│ │ │ • RuntimeManager │ │ • 127.0.0.1:8787│ │ │ │
-│ │ │ • ProjectStore │ │ • NDJSON sessions│ │ │ │
-│ │ │ • TerminalManager │ │ • CORS + Bearer │ │ │ │
-│ │ └─────────┬──────────┘ └────────┬─────────┘ │ │ │
-│ └────────────┼──────────────────────┼────────────┘ │ │
-│ │ │ │ │
-│ └──────────┬───────────┘ │ │
-│ │ │ │
-│ ┌──────────┴──────────┐ │ │
-│ │ graff --json │◄─────────────────────┘ │
-│ │ (Zig Core Engine) │ (SDK Local / Tauri) │
-│ │ src/main.zig │ │
-│ │ src/mcp.zig │ │
-│ └──────────┬──────────┘ │
-│ │ │
-│ ┌──────────┴──────────┐ │
-│ │ LLM Provider APIs │ │
-│ │ (Anthropic / OpenAI) │ │
-│ └─────────────────────┘ │
-└─────────────────────────────────────────────────────────────────────┘
-```
-
-**Key architectural boundary:** The Zig core is the only place where LLM APIs, tool logic, and the agent loop live. The Tauri backend, SDKs, and iOS app do not reimplement any agent logic; they only marshal bytes into and out of the core's JSONL/NDJSON protocol.
-
----
-
-## 3. Data Flow / Protocol
-
-### Universal Protocol: JSONL / NDJSON
-Whether over stdio or HTTP, the protocol is line-delimited JSON. A parent sends a user turn as one JSON object (`{"type":"user","text":"..."}`) and reads a stream of events until a terminal `.turn` or `.error`.
-
-**Event kinds** (consumed by all frontends):
-- `text` → assistant token delta
-- `reasoning` → thinking block
-- `tool_call` / `tool_result` → tool lifecycle
-- `ask_user` → interactive follow-up prompt
-- `turn` → turn complete (final text + metadata)
-- `error` → fatal turn error
-
-### Mode 1: Local stdio (GUI, Python/TS `Harness`, SDK local)
-1. Parent spawns `graff --json --yolo` as a persistent child (`gui/src-tauri/src/runtime/simple.rs:1403`, `sdk/py/harness_sdk.py:175`, `sdk/ts/harness.ts:165`).
-2. Parent writes one JSON line to `stdin`.
-3. Child streams NDJSON lines to `stdout`.
-4. Parent parses lines into DTOs and either emits Tauri events (GUI) or yields to the caller (SDKs).
-
-### Mode 2: HTTP bridge (`graff serve`, Remote SDKs, iOS)
-1. `graff serve` binds an HTTP/1.1 server (`src/main.zig:6694`).
-2. Client `POST /v1/sessions` → receives `session_id`.
-3. Client `POST /v1/sessions/{id}` with one JSON payload.
-4. Server forwards to a spawned `graff --json` child and streams the child's stdout back as NDJSON over chunked transfer encoding (`src/main.zig:6920`).
-5. CORS is enabled only when a `--token` bearer is configured (`src/main.zig:6740`).
-
-### Mode 3: Internal LLM streaming (Zig core)
-Inside `Agent.runTurn()`, the core POSTs to the provider via `std.http.Client` and parses SSE/NDJSON responses. Every streaming read is raced against a **120-second stall-watchdog** using `Io.Select` to poison half-open connections (`src/main.zig:8786`, `src/main.zig:8846`, `src/main.zig:10598`).
-
-### GUI-specific push flow
-The Tauri `RuntimeManager` emits a full `SessionSnapshotDto` on **`codegraff://session-updated`** after every single JSONL event (`gui/src-tauri/src/runtime/simple.rs:1181`, `gui/src-tauri/src/bridge/emitter.rs:12`). The React frontend listens to this event and calls `applySessionSnapshot()`, which rebuilds the entire Zustand conversation state from scratch (`gui/src/app/sessionStore.ts:315`). The frontend never holds authoritative message state.
-
----
-
-## 4. Component Deep-Dives
-
-### 4.1 Zig Core (`src/main.zig`, `src/mcp.zig`)
-
-**Responsibilities**
-- CLI/REPL, one-shot (`-p`), and HTTP server (`serve`) entry points.
-- Multi-provider LLM client (Anthropic Messages, OpenAI Chat Completions, OpenAI Responses).
-- Built-in tool execution (`bash`, `read_file`, `edit_file`, `write_file`, `webfetch`, `codedb`).
-- Meta-tool orchestration (`todo_write`, `todo_read`, `ask_user`, `attempt_completion`).
-- Subagent and `workflow` fan-out (parallel phases with `{{prev}}` substitution).
-- MCP client over stdio (`src/mcp.zig`).
-- Permission gating (`Approvals`), path confinement (`confinedPath`), and `/yolo` mode.
-- Client-side context compaction at 80% of model window.
-- Tracing to `harness.trace.jsonl`.
-
-**Entry points**
-- `pub fn main(init: std.process.Init) !void` — `src/main.zig:3991`
-- `fn serveMain(...)` — `src/main.zig:6694`
-
-**Key modules**
-- `Agent` struct (`src/main.zig:7461`) — owns history, provider, streaming state, and MCP registry pointer.
-- `Agent.runTurn()` (`src/main.zig:7611`) — the main loop.
-- `Agent.postStream()` (`src/main.zig:8760`) — streaming POST with stall-watchdog.
-- `execToolInner()` (`src/main.zig:11411`) — routes builtins, meta, subagent, workflow, and MCP tools.
-- `mcp.Registry` (`src/mcp.zig:46`) — spawns `.mcp.json` servers, JSON-RPC handshake, schema rewriting (`oneOf` → `anyOf`).
-
-**Build**
-- `build.zig` compiles executable `graff` with no `build.zig.zon` dependencies.
-- Version baked via `git describe --tags --always --dirty` (`build.zig:10`).
-- Telemetry endpoint compile-time constant (`build.zig:33`).
-
-### 4.2 GUI Frontend (`gui/src/`)
-
-**Tech stack**
-- React 18 + TypeScript, bundled by Vite.
-- `dockview-react` for outer (`WorkspaceBoard`) and inner (`ChatTile`) panel layouts.
-- `@legendapp/list` for virtualized chat threads.
-- Zustand vanilla store (`sessionStore.ts`) for state.
-
-**Key state management**
-- `sessionStore.ts` (`gui/src/app/sessionStore.ts:1`) is the single source of truth. It stores workspaces, conversation views, prompt drafts, and request timings.
-- `applySessionSnapshot(snapshot)` (`gui/src/app/sessionStore.ts:315`) is the only reducer that mutates conversation messages; it is called after every backend event.
-- `SessionProvider` (`gui/src/app/SessionProvider.tsx:1`) memoizes ~20 async actions (`openWorkspaceByPath`, `submitPrompt`, `selectConversation`, etc.) and wraps children in a context.
-- `useSessionBootstrap` (`gui/src/hooks/useSessionBootstrap.ts:1`) hydrates the store on mount, restoring the last workspace from `localStorage` if needed.
-
-**Main views**
-- `AppShell` (`gui/src/app/App.tsx:1`) — resizable left sidebar + right board.
-- `WorkspaceBoard` (`gui/src/components/workspace-board/WorkspaceBoard.tsx:1`) — `DockviewReact` outer layout; renders `ChatTile` panels.
-- `ChatTile` (`gui/src/components/workspace-board/ChatTile.tsx:1`) — inner `DockviewReact` with `ConversationPanel` and auxiliary panes (`ChangesPane`, `TerminalPane`).
-- `ChatThread` (`gui/src/components/chat/ChatThread.tsx:1`) — virtualized message list with auto-scroll and `ChatActivityRow` grouping.
-- `ProvidersSettingsPane` / `McpSettingsPane` / `GeneralSettingsPane` — settings sub-views.
-
-### 4.3 Tauri Backend (`gui/src-tauri/src/`)
-
-**Commands**
-- `commands.rs` (`gui/src-tauri/src/commands.rs`) exposes ~45 `#[tauri::command]` async wrappers: workspace/project ops, session/chat lifecycle, prompt settings, provider auth, MCP management, file I/O, layout persistence, and terminal control.
-- `read_workspace_file` (`gui/src-tauri/src/commands.rs:414`) runs in `spawn_blocking` and enforces strict sandbox containment (canonical path check, 512 KiB cap).
-
-**Runtime management**
-- `RuntimeManager` (`gui/src-tauri/src/runtime/simple.rs:108`) holds `RuntimeState` (conversations, workspaces, pending follow-ups) and a `HashMap<String, GraffSession>` of live child processes.
-- `acquire_session_io` (`gui/src-tauri/src/runtime/simple.rs:1057`) spawns `graff --json --yolo` with login-shell env injection on macOS (`gui/src-tauri/src/runtime/simple.rs:1548`).
-- `stream_turn` (`gui/src-tauri/src/runtime/simple.rs:562`) writes a JSON line to the child's stdin, reads NDJSON stdout, maps events to `SessionMessageDto`, and emits a snapshot after every event.
-- `codegraff_binary()` (`gui/src-tauri/src/runtime/simple.rs:1506`) resolves the Zig binary via 5-step fallback: env var → bundled sidecar → dev build path → standard install paths → PATH.
-
-**Bridge to Zig core**
-- The backend does not link the Zig core; it shells out to it. Every conversation has its own persistent `tokio::process::Child`.
-- `TauriEventEmitter` (`gui/src-tauri/src/bridge/emitter.rs:20`) pushes typed DTOs into the webview via `tauri::Emitter`.
-- `ProjectStore` (`gui/src-tauri/src/persistence/project_store.rs`) uses SQLite (`diesel`) for workspace metadata, saved layouts, and managed chats.
-
-### 4.4 SDKs (`sdk/`)
-
-**Generation**
-- `sdk/generate.py` is the single source of truth. It reads `graff --schema` JSON and produces `sdk/ts/harness.ts`, `sdk/ts/remote.ts`, and `sdk/py/harness_sdk.py` (`sdk/generate.py:1`).
-- SDK files carry an auto-generated header and should not be edited manually.
-
-**Python SDK (`sdk/py/harness_sdk.py`)**
-- `Harness` — spawns local `graff --json` via `subprocess.Popen`. Supports multi-turn `chat()`, one-shot `ask()`, `answer()` for `ask_user`, `set_system_prompt()`, `score()`, and `pull_elites()`.
-- `RemoteHarness` — speaks to `graff serve` via `urllib.request` (zero external deps).
-- Telemetry reporting to OTLP endpoint via stdlib `http.client`.
-
-**TypeScript SDK (`sdk/ts/`)**
-- `harness.ts` — Node-only client using `node:child_process` and `node:readline`.
-- `remote.ts` — Edge-runtime client using only `fetch` + Web Streams (no `node:` imports), runnable in Cloudflare Workers, Deno, Bun, and browsers.
-- Exports identical event unions, `ModelName`, `ToolName`, `ProviderId`, plus `promptFingerprint` and `fleetSignal`.
-
-**DGM evolution**
-- Both SDKs support `score()` with HMAC-SHA256 provenance and `pull_elites()` from the telemetry collector, enabling the Darwin Gödel Machine loop (`examples/dgm_loop.py:144`, `docs/hyperagents.md:113`).
-
-### 4.5 iOS App (`apps/ios/`)
-
-**Structure**
-- SwiftUI app targeting iOS 26.0 (`project.yml:8`, `Info.plist:18`).
-- `GraffApp.swift` (`GraffApp.swift:4`) — entry point with `AgentSession`, `ChatMessage`, and `TodoItem` models.
-- `SessionsListView.swift` — root list with status chips and progress.
-- `ChatView.swift` — session detail with scrollable bubbles, `TaskProgressCard`, `PlanDecisionBar`, and composer.
-
-**Protocol client**
-- `GraffServeClient.swift` (`GraffServeClient.swift:25`) targets `http://127.0.0.1:8787` (the Mac host from the simulator).
-- `createSession()` → `POST /v1/sessions`.
-- `streamTurn()` → `POST /v1/sessions/{id}`, returns `AsyncThrowingStream<GraffEvent, Error>` parsing NDJSON via `JSONSerialization`.
-- Terminates stream on `.turn` or `.error` (`GraffServeClient.swift:69`).
-- Ignores `.toolCall` events currently (`ChatView.swift:97`).
-
-**UI**
-- `MessageBubble` shows reasoning with a `brain` SF Symbol caption.
-- Empty assistant messages show a `TypingIndicator` (pulsing dots) instead of a blank bubble (`ChatView.swift:167`).
-- No persistence layer; all state is in-memory `@State`/`@Binding`.
-
----
-
-## 5. Key Patterns and Design Decisions
-
-| Pattern | Description | Evidence |
-|---|---|---|
-| **Zero external dependencies (core)** | The Zig binary uses only `std` (and an internal `std.Io` abstraction). SDKs use only language stdlibs. | `build.zig` (no `build.zig.zon`), `sdk/py/harness_sdk.py` (no `requests`), `sdk/ts/remote.ts` (no `node:`) |
-| **Backend owns state; frontend is reactive** | The GUI does not optimistically update messages. It waits for `SessionSnapshotDto` and rebuilds. | `gui/src/app/sessionStore.ts:315`, `gui/src-tauri/src/runtime/simple.rs:1181` |
-| **Schema-driven SDK lockstep** | `graff --schema` is the API contract. SDK types are regenerated so they never drift from the binary. | `sdk/generate.py:1`, `sdk/README.md:11` |
-| **Persistent child-per-conversation** | The Tauri backend and local SDKs keep one `graff --json` subprocess alive per conversation, reusing it across turns. | `gui/src-tauri/src/runtime/simple.rs:1057`, `sdk/py/harness_sdk.py:175` |
-| **Stall-watchdog on every streaming read** | `Io.Select` races HTTP response headers, SSE lines, and peek-ahead probes against a 120-second deadline. | `src/main.zig:8786`, `src/main.zig:8846`, `src/main.zig:10598` |
-| **Path confinement + permission gating** | File tools are confined to cwd; bash and MCP require user approval unless `/yolo` is active. | `architecture.md:175`, `src/main.zig:10695` |
-| **DGM evolution primitives** | The binary exposes `set_system_prompt`, `subagent`, and `score()`. The DGM loop lives in SDK driver code, not the core. | `docs/hyperagents.md:43`, `examples/dgm_loop.py:1` |
-| **Auto-compaction with handoff** | At 80% context window, the harness forces a summary turn and replaces history with it to preserve KV-cache prefix. | `architecture.md:280`, `src/main.zig:7461` |
-
----
-
-## 6. Notable Files and Their Roles
-
-| If you want to understand... | Read this file |
-|---|---|
-| The agent loop, streaming, and tool dispatch | `src/main.zig` (especially `Agent.runTurn` at `:7611`, `postStream` at `:8760`, `execToolInner` at `:11411`) |
-| MCP client and external tool discovery | `src/mcp.zig` (`Registry.init` at `:56`, `Registry.call` at `:224`) |
-| How the GUI backend bridges to the Zig binary | `gui/src-tauri/src/runtime/simple.rs` (`stream_turn` at `:562`, `acquire_session_io` at `:1057`) |
-| How the GUI frontend receives and renders state | `gui/src/app/sessionStore.ts` (`applySessionSnapshot` at `:315`) and `gui/src/app/SessionProvider.tsx` |
-| Chat virtualization and activity grouping | `gui/src/components/chat/ChatThread.tsx` and `gui/src/components/chat/utils/chatThread.ts` |
-| Diff rendering in the GUI | `packages/diffs/src/parse.ts`, `packages/diffs/src/wordDiff.ts`, and `gui/src/components/chat/activity-results/FileDiffResult.tsx` |
-| SDK generation and the API contract | `sdk/generate.py` and `sdk/ts/remote.ts` (for the edge-runtime fetch client) |
-| The DGM evolution loop and grounded judge | `examples/dgm_loop.py`, `examples/replay_judge.py`, `docs/hyperagents.md` |
-| iOS transport and UI | `apps/ios/GraffServeClient.swift` and `apps/ios/ChatView.swift` |
-| Build configuration of the core | `build.zig` |
-
----
-
-## 7. Tech Stack Summary
-
-| Component | Languages | Frameworks / Libraries | Build Tools |
-|---|---|---|---|
-| **Zig Core** | Zig 0.16 | Standard library only (`std`, `std.Io`) | `zig build` |
-| **GUI Frontend** | TypeScript, React | Zustand, dockview-react, @legendapp/list, Tailwind CSS | Vite, Bun |
-| **Tauri Backend** | Rust | Tauri, tokio, diesel (SQLite), portable-pty | `cargo tauri` |
-| **SDKs** | Python 3, TypeScript | Standard library / `fetch` + Web Streams only | `generate.py`, `bun` (for TS pkg) |
-| **iOS App** | Swift, SwiftUI | URLSession, `JSONSerialization` | `swiftc`, `xcodegen`, shell scripts (`build-sim.sh`) |
-| **Shared Diff Package** | TypeScript | None (zero-dependency) | Bun (`packages/diffs/`) |
-
----
-
-## Verified vs. Inferred
-
-**Verified**
-- The Zig core is a single executable with no external Zig dependencies (`build.zig`, `src/main.zig`).
-- The Tauri backend spawns `graff --json` per conversation and speaks JSONL over stdio (`gui/src-tauri/src/runtime/simple.rs:562`, `simple.rs:1403`).
-- The GUI frontend rebuilds state exclusively from `SessionSnapshotDto` pushed by the backend (`gui/src/app/sessionStore.ts:315`, `gui/src-tauri/src/bridge/emitter.rs:12`).
-- The SDKs are auto-generated from `graff --schema` (`sdk/generate.py:1`, `sdk/ts/harness.ts:1`).
-- The iOS app consumes the HTTP `serve` bridge and ignores `tool_call` events (`GraffServeClient.swift:69`, `ChatView.swift:97`).
-
-**Inferred**
-- The `std.Io` abstraction used for async I/O in the Zig core is a custom/patched runtime layer, not standard Zig 0.16/0.17 (`docs/zig-0.17-port-plan.md:8`). Its exact origin and maintenance plan are undocumented in the repo.
-- The DGM federated fleet loop (Step 2) is scaffolded in docs and SDKs but not yet fully implemented (`docs/hyperagents.md:174`).
-- The `MemoryDesign` interface described in `docs/memory-architecture.md` is a design proposal; it is not yet implemented in the Zig source.
-
----
-
-## 3 Most Load-Bearing Facts
-
-1. **The entire system is a thin wrapper around a single self-contained Zig binary.** The GUI, SDKs, and iOS app all consume the same JSONL/NDJSON protocol emitted by `graff --json` (stdio) or `graff serve` (HTTP). The core itself has zero external dependencies and implements the full agentic loop, multi-provider streaming, parallel tool execution, and MCP client discovery.
-2. **The GUI frontend is a stateless reactive projection of the Tauri backend.** The React Zustand store never optimistically updates conversation state; it only applies `SessionSnapshotDto` payloads pushed via `codegraff://session-updated`. The backend, in turn, only wraps a persistent `graff --json` child process per conversation. This means the frontend is effectively a remote renderer for the Zig core's stdout.
-3. **The project embeds a full Darwin Gödel Machine (DGM) evolution loop** with schema-driven SDK generation, HMAC-signed fitness scores, and a grounded replay judge that uses deterministic assertions to prevent LLM "charming." However, the GUI and iOS app do not yet consume the federated fleet telemetry endpoints (`pull_elites`, `score`), leaving the visual layer disconnected from the evolution infrastructure.
-
----
-
-## 1 Open Question
-
-**What is `std.Io` (the custom async I/O runtime used 182+ times throughout the Zig core), and what is its maintenance path for the Zig 0.17 port?** It is referenced as `Io.Select`, `Io.Future`, `Io.Mutex`, `io.async`, etc., but it is not part of the upstream Zig standard library. The port plan notes that these 182 uses showed no breakage in a dry run, yet the stability of the entire streaming, subagent, and tool-execution stack depends on this abstraction. Is it a private fork, a vendored patch, or a planned stdlib proposal?
diff --git a/.graff/subagents/sa-007-89e9eb9c.md b/.graff/subagents/sa-007-89e9eb9c.md
deleted file mode 100644
index d7f9664f..00000000
--- a/.graff/subagents/sa-007-89e9eb9c.md
+++ /dev/null
@@ -1,573 +0,0 @@
-# subagent sa-007-89e9eb9c
-
-- label: Root cause synthesis
-- kind: workflow_task
-- status: ok
-- elapsed_ms: 31115
-- tools: (none)
-
-## task
-
-Synthesize these parallel findings into a concise root-cause answer for the user. Include confidence level, whether ultracode caused it, what branch/binary state likely explains it, and the safest next fix/verification steps. Previous phase results:
-### TUI prompt provenance
-## Verified
-
-### 1) Current checkout still has workspace/folder data, but it is `g_cwd_display`, not `folder_name`
-
-- `src/main.zig` defines a global display string: `g_cwd_display`, documented as “Human-facing current workspace folder shown in the REPL prompt.” (`src/main.zig:2557-2560`)
-- At startup, it is populated from `Io.Dir.cwd().realPath(...)`, falling back to `$PWD` or `"."`; this means it is the full cwd path, not a basename/folder-name-only value. (`src/main.zig:4573-4577`)
-- The startup banner also prints it as `folder: <g_cwd_display>`. (`src/main.zig:4579-4580`)
-- I found no current `folder_name` symbol via codedb (`codedb search "folder_name"` returned no results), and the current code path uses `g_cwd_display`.
-
-### 2) Current prompt-rendering function would show the cwd if it were called
-
-`Agent.prompt()` renders the TUI prompt. In the current checkout:
-
-- It early-returns in JSON mode, so GUI/SDK `--json` sessions never get the human prompt. (`src/main.zig:8226-8228`)
-- It computes mode/cost/cache suffixes. (`src/main.zig:8229-8242`)
-- With context tokens, it prints:
-
- ```text
- [<model><flags> · cwd <g_cwd_display> · <tokens>k tok ...] ›
- ```
-
- (`src/main.zig:8243-8251`)
-
-- Without context tokens, it prints:
-
- ```text
- [<model><flags> · cwd <g_cwd_display><cost>] ›
- ```
-
- (`src/main.zig:8252-8258`)
-
-So the current intended prompt shape is **not** `[gpt-5.5]({folder_name})`; it is closer to:
-
-```text
-[gpt-5.5 · cwd /full/path] ›
-```
-
-or, once token metadata exists:
-
-```text
-[gpt-5.5 · cwd /full/path · 123/217k tok (56%)] ›
-```
-
-### 3) The likely bug: the main REPL loop no longer calls `root.prompt()` before reading input
-
-In the current checkout, the REPL loop starts at `while (true)` and immediately drains steering input / reads a line:
-
-- Current loop begins with steering-drain setup. (`src/main.zig:4904-4911`)
-- It then sets `raw_line` from queued steering input, `readLine(...)`, or stdin delimiter. (`src/main.zig:4912-4923`)
-- There is **no** `try root.prompt();` at the top of this loop. (`src/main.zig:4904-4923`)
-
-The only current `root.prompt()` calls I found are inside `readLine` feedback paths after clipboard/image/drop messages:
-
-- Clipboard-image feedback redraws by calling `root.prompt()`. (`src/main.zig:3670-3675`)
-- Drag/drop image feedback redraws by calling `root.prompt()`. (`src/main.zig:3850-3855`)
-
-That means normal interactive input can miss the model/cwd prompt entirely, even though `Agent.prompt()` still exists and contains cwd rendering.
-
-### 4) Git history points to `1f54380` as the likely regression
-
-Before the steering feature, the loop explicitly rendered the prompt before reading input:
-
-- In `91a7c2e:src/main.zig`, the main loop had:
-
- ```zig
- while (true) {
- try root.prompt();
- const raw_line = if (interactive)
- (try readLine(...))
- ```
-
- (`91a7c2e:src/main.zig:4539-4544`, viewed via `git show 91a7c2e:src/main.zig | nl -ba`)
-
-The steering commit changed that loop:
-
-- In `1f54380:src/main.zig`, the loop begins with steering-drain code and then reads either a queued steer line or `readLine(...)`; the `try root.prompt();` line is gone. (`1f54380:src/main.zig:4774-4789`, viewed via `git show 1f54380:src/main.zig | nl -ba`)
-- The commit is titled `feat: Codex-style steering — queue follow-up prompts while a turn streams`, and its diff shows the removal of `try root.prompt();` in the loop (`git show 1f54380 -- src/main.zig`, diff hunk around old loop).
-
-So the most likely cause is: **the steering-followup change accidentally removed the normal prompt render call from the top of the REPL loop.**
-
-### 5) Current installed/built binaries may also be behind the current checkout
-
-In this environment:
-
-- `git describe` reports the checkout as `v0.0.161-24-g85ccf25`.
-- `./zig-out/bin/graff --version` reports `simple-harness v0.0.14-7-g782e707-dirty`.
-- `graff --version` from PATH reports `graff v0.0.161-18-g7bea7e7`.
-
-So a user testing “current binary” may not actually be running the exact current checkout. However, `7bea7e7` also lacks the normal loop `root.prompt()` call and still has only the redraw-path calls, so the missing TUI prompt is consistent with both the installed PATH binary and the current checkout.
-
-## Inferred
-
-- The old UX remembered as `[gpt-5.5]({folder_name})` does not match the exact current or recent source format I verified. The verified current format would be `[gpt-5.5 · cwd <full path>] ›`, not `[gpt-5.5](folder)`.
-- If a user sees no model/folder prompt at all, the likely reason is not that folder data disappeared; it is that the main interactive loop stopped invoking `Agent.prompt()` before `readLine`.
-- If a user sees only the startup `codegraff · folder: ...` banner but not per-turn `[model · cwd ...] ›`, that is exactly what the current control flow predicts.
-
-## 3 most load-bearing facts
-
-1. `Agent.prompt()` still contains cwd rendering using `g_cwd_display`. (`src/main.zig:8226-8258`)
-2. `g_cwd_display` is still populated from the current real cwd at startup. (`src/main.zig:4573-4577`)
-3. The current main REPL loop reads input without calling `root.prompt()`, whereas pre-steering history did call `try root.prompt();` before `readLine`. (`src/main.zig:4904-4923`; `91a7c2e:src/main.zig:4539-4544`; `1f54380:src/main.zig:4774-4789`)
-
-## Open question
-
-Was the desired UX supposed to be the remembered compact basename form `[gpt-5.5]({folder_name})`, or is the intended current design the checked-in full-path form `[gpt-5.5 · cwd /full/path] ›` once the missing `root.prompt()` call is restored?
-
-[subagent sa-004-7c59681c · inspect: .graff/subagents/sa-004-7c59681c.md]
-
-### Branch binary mismatch
-## Verified findings
-
-### 1) Current worktree is **not** `feat/ios-companion-app`; it is `chore/release-0.0.161-sdk-login-assets`
-
-Command:
-
-```sh
-cd /Users/blackfloofie/codegraff &&
-pwd &&
-git status --short --branch &&
-git branch --show-current &&
-git rev-parse HEAD
-```
-
-Output:
-
-```text
-/Users/blackfloofie/codegraff
-## chore/release-0.0.161-sdk-login-assets...origin/chore/release-0.0.161-sdk-login-assets
-?? .graff/
-?? apps/
-chore/release-0.0.161-sdk-login-assets
-85ccf25a29a5e9fd78c492a3ff13c5c002144ad6
-```
-
-So the checkout is clean with respect to tracked files, but has untracked `.graff/` and `apps/`.
-
-`git worktree list --porcelain` confirms this worktree is on `refs/heads/chore/release-0.0.161-sdk-login-assets` at `85ccf25`, while `release/0.0.161` is checked out separately at `/Users/blackfloofie/codegraff-rel017`.
-
----
-
-### 2) Branch comparison: `feat/ios-companion-app` lacks the current-folder prompt UX; current branch has it
-
-Command:
-
-```sh
-git log --oneline --decorate --left-right --cherry-pick \
- chore/release-0.0.161-sdk-login-assets...feat/ios-companion-app --max-count=80
-```
-
-Relevant output:
-
-```text
-< 85ccf25 (HEAD -> chore/release-0.0.161-sdk-login-assets, origin/chore/release-0.0.161-sdk-login-assets) fix(gui): handle expired provider auth
-< 5d0e374 fix(gui): auto-detect CLI provider login
-...
-> f278fed (origin/feat/ios-companion-app, feat/ios-companion-app) feat(gui): surface ultracode mode
-> 904bfa8 feat: add ultracode mode and trajectory usage
-> 782e707 docs(AGENTS): GUI and engine must stay in lockstep — rebuild + redeploy graff on protocol changes
-...
-< ba861df Add pwd command and show workspace folder
-< 00e281a fix: label cwd in repl prompt
-```
-
-Command:
-
-```sh
-git branch -a --contains ba861df | grep -E 'chore/release|feat/ios|release/0.0.161|HEAD|main'
-git branch -a --contains 00e281a | grep -E 'chore/release|feat/ios|release/0.0.161|HEAD|main'
-```
-
-Output:
-
-```text
-* chore/release-0.0.161-sdk-login-assets
-+ release/0.0.161
- remotes/origin/HEAD -> origin/main
- remotes/origin/chore/release-0.0.161-sdk-login-assets
- remotes/origin/main
- remotes/origin/release/0.0.161
-* chore/release-0.0.161-sdk-login-assets
-+ release/0.0.161
- remotes/origin/chore/release-0.0.161-sdk-login-assets
- remotes/origin/release/0.0.161
-```
-
-Notably, `feat/ios-companion-app` is absent from both `--contains` results.
-
-Current branch source contains current-folder state and prompt rendering:
-
-- `src/main.zig:2559-2560` defines `g_cwd_display` as “Human-facing current workspace folder shown in the REPL prompt.”
-- `src/main.zig:4573-4580` populates it from real cwd / `PWD` and prints startup `folder: ...`.
-- `src/main.zig:8247-8255` renders the prompt with `· cwd {g_cwd_display}` beside the model.
-
-Evidence excerpt from current `src/main.zig`:
-
-```text
-8247 try w.print("\n{s}[{s}{s}{s}{s}{s} · cwd {s}{s}{s} · {d}/{d}k tok ...
-8248 style.reset, g_cwd_display, ...
-8253 try w.print("\n{s}[{s}{s}{s}{s}{s} · cwd {s}{s}{s}{s}]{s} ...
-8255 style.reset, g_cwd_display, ...
-```
-
-By contrast, `feat/ios-companion-app` prompt rendering lacks cwd/folder:
-
-Command:
-
-```sh
-git show feat/ios-companion-app:src/main.zig | nl -ba | sed -n '7738,7767p'
-```
-
-Relevant output:
-
-```text
-7749 const plain = std.fmt.bufPrint(&pbuf, "[{s}{s} · {d}/{d}k tok ({d}%){s}{s}] › ", .{
-7750 self.provider.model, flag, self.last_context_tokens, threshold / 1000, pct, cached, cost,
-...
-7760 const plain = std.fmt.bufPrint(&pbuf, "[{s}{s}{s}] › ", .{ self.provider.model, flag, cost }) catch "";
-...
-7762 try w.print("\r\n{s}[{s}{s}{s}{s}{s}{s}]{s} {s}›{s} ", .{
-7763 style.dim, style.reset, style.cyan, self.provider.model, flag, style.dim, cost,
-```
-
-So yes: a build from downstream `feat/ios-companion-app` can explain missing `[gpt-5.5] + folder/cwd` prompt UX. The current checkout source cannot, because it has the cwd prompt code.
-
----
-
-### 3) Built binary provenance is mixed/stale relative to current checkout
-
-Command:
-
-```sh
-command -v graff
-which -a graff
-ls -l ./zig-out/bin 2>/dev/null
-./zig-out/bin/graff --version 2>&1 || true
-graff --version 2>&1 || true
-```
-
-Output:
-
-```text
-/Users/blackfloofie/bin/graff
-/Users/blackfloofie/bin/graff
-total 14680
--rwxr-xr-x@ 1 blackfloofie staff 7514632 21 Jun 17:07 graff
-simple-harness v0.0.14-7-g782e707-dirty
-graff v0.0.161-18-g7bea7e7
-```
-
-Detailed binary metadata:
-
-```sh
-for b in ./zig-out/bin/graff /Users/blackfloofie/bin/graff; do
- ls -l "$b"
- stat -f 'mtime=%Sm size=%z inode=%i' "$b"
- shasum -a 256 "$b"
- "$b" --version
-done
-```
-
-Output:
-
-```text
---- ./zig-out/bin/graff
--rwxr-xr-x@ 1 blackfloofie staff 7514632 21 Jun 17:07 ./zig-out/bin/graff
-mtime=Jun 21 17:07:52 2026 size=7514632 inode=35841595
-cd06953adc3a814f39103e489b66f625c99978f5e0be227c952f5325da5590d6 ./zig-out/bin/graff
-simple-harness v0.0.14-7-g782e707-dirty
-
---- /Users/blackfloofie/bin/graff
--rwxr-xr-x@ 1 blackfloofie staff 7630808 21 Jun 13:57 /Users/blackfloofie/bin/graff
-mtime=Jun 21 13:57:14 2026 size=7630808 inode=35694914
-0b4b58e6d1aafda389006bd04b90e7d205bcd356f6d52c3605b4647ad714f961 /Users/blackfloofie/bin/graff
-graff v0.0.161-18-g7bea7e7
-```
-
-Command:
-
-```sh
-git name-rev --name-only 782e707 7bea7e7 85ccf25 f278fed
-git show --no-patch --format='%h %D %s' 782e707 7bea7e7 85ccf25 f278fed
-```
-
-Output:
-
-```text
-remotes/origin/feat/ios-companion-app~2
-feat/live-agent-tree~4
-chore/release-0.0.161-sdk-login-assets
-remotes/origin/feat/ios-companion-app
-
-782e707 docs(AGENTS): GUI and engine must stay in lockstep — rebuild + redeploy graff on protocol changes
-7bea7e7 Merge release/0.0.16 into release/0.0.161
-85ccf25 HEAD -> chore/release-0.0.161-sdk-login-assets, origin/chore/release-0.0.161-sdk-login-assets fix(gui): handle expired provider auth
-f278fed origin/feat/ios-companion-app, feat/ios-companion-app feat(gui): surface ultracode mode
-```
-
-The important point: `./zig-out/bin/graff` is stamped from `782e707-dirty`, i.e. close to downstream `feat/ios-companion-app`, and that branch lacks the cwd prompt. The installed CLI `/Users/blackfloofie/bin/graff` is stamped from `7bea7e7`, which does have the cwd prompt:
-
-Command:
-
-```sh
-git grep -n 'g_cwd_display\|cwd {s}\|folder:' 7bea7e7 -- src/main.zig
-```
-
-Output:
-
-```text
-7bea7e7:src/main.zig:2560:var g_cwd_display: []const u8 = ".";
-7bea7e7:src/main.zig:4573: g_cwd_display = if (Io.Dir.cwd().realPath(io, &cwd_buf)) |n|
-7bea7e7:src/main.zig:4579: try out.print("{s}codegraff{s} · folder: {s}{s}{s} ...
-7bea7e7:src/main.zig:8246: try w.print("\n{s}[{s}{s}{s}{s}{s} · cwd {s}{s}{s} ...
-7bea7e7:src/main.zig:8252: try w.print("\n{s}[{s}{s}{s}{s}{s} · cwd {s}{s}{s}{s}]{s} ...
-```
-
----
-
-### 4) GUI binary resolution can prefer stale `./zig-out/bin/graff` over installed `~/bin/graff`
-
-The GUI runtime resolver first checks an explicit `CODEGRAFF_GUI_BINARY`, then bundled sidecar, then dev `../../zig-out/bin/graff`, then known install locations like `~/bin/graff` and `~/.local/bin/graff`:
-
-- Explicit override: `gui/src-tauri/src/runtime/simple.rs:3240-3254`
-- Bundled sidecar next to app executable: `gui/src-tauri/src/runtime/simple.rs:3255-3266`
-- Dev build `../../zig-out/bin/graff`: `gui/src-tauri/src/runtime/simple.rs:3269-3274`
-- Known install locations including `~/bin/graff`: `gui/src-tauri/src/runtime/simple.rs:3276-3288`
-
-This means a dev-launched GUI from this checkout can select the stale `./zig-out/bin/graff` before the newer installed `/Users/blackfloofie/bin/graff`.
-
-That is a strong explanation path for missing folder/cwd prompt UX despite the current source having the feature.
-
----
-
-## Inference
-
-- If the missing `[gpt-5.5]({folder_name})` UX was observed in a GUI/dev run from `/Users/blackfloofie/codegraff`, the most likely cause is **binary provenance**, not tracked source state: the GUI resolver can prefer `./zig-out/bin/graff`, and that binary is built from `782e707-dirty`, near `feat/ios-companion-app`, where prompt rendering lacks cwd/folder.
-- If the missing UX was observed from terminal `graff`, then `/Users/blackfloofie/bin/graff` should be checked interactively, because its stamped commit `7bea7e7` contains cwd prompt code. The non-interactive `--version` evidence alone says it should have the feature, but I did not run an interactive TTY capture.
-
----
-
-## Bottom line
-
-Yes, `chore/release-0.0.161-sdk-login-assets` vs downstream `feat/ios-companion-app` **can explain** missing folder-name prompt UX **if the binary being run came from the downstream/stale lineage**. The current checkout source has the cwd/folder prompt; the downstream branch does not. The local `./zig-out/bin/graff` is in fact stamped `v0.0.14-7-g782e707-dirty`, and GUI dev resolution can prefer that stale binary over installed `~/bin/graff`.
-
-## 3 load-bearing facts
-
-1. Current worktree is `chore/release-0.0.161-sdk-login-assets` at `85ccf25`, not `feat/ios-companion-app`; tracked files are not dirty.
-2. `feat/ios-companion-app` lacks the cwd/folder prompt code; current branch contains it in `src/main.zig:2559-2560`, `src/main.zig:4573-4580`, and `src/main.zig:8247-8255`.
-3. `./zig-out/bin/graff` is stale/downstream-adjacent: `simple-harness v0.0.14-7-g782e707-dirty`, and GUI dev resolver checks `../../zig-out/bin/graff` before `~/bin/graff` per `gui/src-tauri/src/runtime/simple.rs:3269-3288`.
-
-## Open question
-
-Which exact executable did the observed failing UX use at runtime: bundled app sidecar, `./zig-out/bin/graff`, `/Users/blackfloofie/bin/graff`, or a `CODEGRAFF_GUI_BINARY` override?
-
-[subagent sa-005-4f629496 · inspect: .graff/subagents/sa-005-4f629496.md]
-
-### Ultracode interaction audit
-I used codedb first:
-
-- `codedb search ultracode` found the relevant docs/GUI/runtime hits and pointed to `src/main.zig`.
-- `codedb outline src/main.zig` failed because `src/main.zig` is not indexed in codedb in this checkout, so I fell back to git/file inspection.
-
-## Current TUI prompt format
-
-Current `src/main.zig` prints the REPL prompt in `Agent.prompt` as:
-
-- `src/main.zig:8248` for context-token prompt:
- ```zig
- "\n{s}[{s}{s}{s}{s}{s} · cwd {s}{s}{s} · {d}/{d}k tok ..."
- ```
-- `src/main.zig:8255` for normal prompt:
- ```zig
- "\n{s}[{s}{s}{s}{s}{s} · cwd {s}{s}{s}{s}]{s} {s}›{s} "
- ```
-
-So the current format is effectively:
-
-```text
-[gpt-5.5 · cwd /path/to/folder] ›
-```
-
-not:
-
-```text
-[gpt-5.5](folder_name) ›
-```
-
-## Did ultracode remove/overwrite `[gpt-5.5]({folder_name})`?
-
-I do **not** see a defensible current-branch regression caused by the ultracode commits.
-
-Concrete history:
-
-1. `ba861df Add pwd command and show workspace folder` added the folder display to `Agent.prompt`, but it added it **inside the square brackets** with a middle-dot separator:
- ```diff
- - [{model...}]
- + [{model...} · {g_cwd_display}]
- ```
- It did not implement `[model](folder)`.
-
-2. `00e281a fix: label cwd in repl prompt` changed that same display to include the literal label `cwd`:
- ```diff
- - [model · /path]
- + [model · cwd /path]
- ```
-
-3. The current-branch ultracode TUI commits I inspected:
- - `529c65a feat: shine the ultracode codeword banner`
- - `b0a0de4 feat: shine the ultracode codeword on the input line too`
- - `9104c87 feat: wave the ultracode input shine across letters over time`
- - `91a7c2e feat: softer ultracode wave — gentler pulse + smooth interpolated hues`
- - `460a400 feat: /ultracode slash command for persistent ultracode mode`
-
- do **not** rewrite the prompt badge format in `Agent.prompt`. `460a400` adds `/ultracode`, `root.ultracode_mode`, JSON control handling, and codeword behavior, but the shown diff does not touch the prompt-printing hunk.
-
-## Suspicious non-current ultracode branch
-
-There is one ultracode-related commit in `--all` history that *would* be suspicious if someone were auditing a different branch:
-
-- `904bfa8 feat: add ultracode mode and trajectory usage`
-
-That commit rewrites `Agent.prompt` to add an ultracode flag and prompt-width bookkeeping. Its parent did **not** have the cwd prompt changes, so its prompt hunk has no folder/cwd display. However:
-
-```text
-git merge-base --is-ancestor 904bfa8 HEAD
-# exit 1
-```
-
-So `904bfa8` is **not an ancestor of the current HEAD** I audited. It is not the cause of the current checkout’s prompt format.
-
-## More likely culprit
-
-If the expected format was specifically:
-
-```text
-[gpt-5.5]({folder_name})
-```
-
-then the likely culprit is not ultracode. The repo history I checked does not show that exact format ever existing in `src/main.zig`.
-
-The current visible behavior is more directly explained by:
-
-- `ba861df` introducing folder display as `[model · /path]`, and then
-- `00e281a` changing it to `[model · cwd /path]`.
-
-Those commits changed the prompt badge shape around the workspace display; ultracode did not.
-
-## Verdict
-
-No defensible defect found that current-branch ultracode changes removed or overwrote `[gpt-5.5]({folder_name})`. The more likely culprit is the folder-prompt work itself, especially `ba861df`/`00e281a`, which implemented/labeled cwd inside the bracketed badge rather than using a parenthesized folder suffix.
-
-[subagent sa-006-5eefb3a1 · inspect: .graff/subagents/sa-006-5eefb3a1.md]
-
-## report
-
-## Root cause
-
-The missing folder/model TUI prompt is **not caused by ultracode**. The strongest explanation is a combination of:
-
-1. **A real REPL-loop regression:** the normal interactive loop no longer calls `root.prompt()` before reading input.
- `Agent.prompt()` still knows how to render the model + cwd prompt, but the main loop stopped invoking it after the steering/follow-up prompt change around commit `1f54380`.
-
-2. **Possible stale/downstream binary confusion:** the binary being run may not match the current checkout.
- The current checkout is on `chore/release-0.0.161-sdk-login-assets` at `85ccf25`, but:
- - `./zig-out/bin/graff` is stamped `782e707-dirty`, near `feat/ios-companion-app`, which lacks the cwd prompt code.
- - PATH `graff` is `7bea7e7`, which has cwd prompt code, but likely still has the missing `root.prompt()` call regression.
- - GUI dev resolution can prefer `./zig-out/bin/graff` before `~/bin/graff`, so the GUI may be running the stale/downstream binary.
-
-## Confidence
-
-**High** that ultracode did not cause this.
-**High** that the current/recent source has cwd data and prompt-rendering code.
-**Medium-high** that the observed missing prompt is primarily from the removed `root.prompt()` call, with stale binary provenance as an additional likely factor depending on how the app was launched.
-
-## Did ultracode cause it?
-
-**No.**
-
-The current-branch ultracode commits did not remove the cwd prompt. The suspicious ultracode commit `904bfa8` is on a different/downstream lineage and is not an ancestor of the audited current HEAD. Also, the exact remembered format:
-
-```text
-[gpt-5.5]({folder_name})
-```
-
-does not appear to be the current implemented design. The current source intends something more like:
-
-```text
-[gpt-5.5 · cwd /full/path] ›
-```
-
-## Likely branch/binary state
-
-The source tree is currently:
-
-```text
-chore/release-0.0.161-sdk-login-assets @ 85ccf25
-```
-
-But the local binaries are mixed:
-
-```text
-./zig-out/bin/graff -> 782e707-dirty, stale/downstream-adjacent
-~/bin/graff / PATH graff -> 7bea7e7
-```
-
-So if the failure was seen in the GUI/dev app, the GUI may have picked the stale `./zig-out/bin/graff`, which comes from a lineage where cwd prompt code is missing.
-
-If the failure was seen in terminal `graff`, then the binary likely has the cwd prompt code but still does not display it because the REPL loop no longer calls `root.prompt()` normally.
-
-## Safest next fix
-
-1. **Patch the REPL loop to call `root.prompt()` again before interactive input.**
- Reinsert it at the top of the main loop, but be careful with steering queued input. Likely shape:
-
- ```zig
- while (true) {
- if (interactive and steering_queue_empty_or_not_auto_draining) {
- try root.prompt();
- }
-
- // then drain queued steering input / readLine(...)
- }
- ```
-
- The key is: normal user input should get the prompt; queued steering follow-ups probably should not double-print prompts.
-
-2. **Rebuild from the intended branch.**
-
- ```sh
- git branch --show-current
- git rev-parse HEAD
- zig build
- ./zig-out/bin/graff --version
- ```
-
-3. **Ensure the GUI uses the rebuilt binary.**
- Either remove/replace stale `./zig-out/bin/graff`, or explicitly set:
-
- ```sh
- CODEGRAFF_GUI_BINARY=/Users/blackfloofie/codegraff/zig-out/bin/graff
- ```
-
- Then relaunch the GUI.
-
-4. **Verify in an actual interactive TTY.**
- Expected current prompt should be closer to:
-
- ```text
- [gpt-5.5 · cwd /full/path] ›
- ```
-
- not:
-
- ```text
- [gpt-5.5](folder_name)
- ```
-
-## Final verdict
-
-**Refuted:** ultracode is not the root cause.
-
-The root cause is most likely the steering change that accidentally removed the normal `root.prompt()` call from the REPL loop, compounded by stale/mismatched binaries in `zig-out` and PATH that can make the GUI run a different branch than the checked-out source.