# Design — Koda

> Design principles, architecture, and key decisions for contributors
> and maintainers.

---

## Vision

Koda is a personal AI assistant that you own. Not a product from a large
company. Not a platform that locks you into one provider. A tool built for
one person — the author — that works with any API and any local model.

Koda is three things: a coding agent shaped for one person, a platform for
trying agentic-framework ideas and measuring them, and a Rust development
platform where agents do much of the work. It works with local models and
remote APIs alike.

The goal is a Claude Code shaped for one person, not a product. Claude
Code, Codex and Cursor are designed for broad adoption with configuration
surfaces for many users. Koda is the opposite: hyper-specific, opinionated,
and changeable with a few prompts and a recompile.

What koda specifically rejects from existing tools:

- **Cursor/Windsurf**: Extension and plugin systems, marketplace
  ecosystems, multi-user configuration surfaces. These create complexity
  that serves breadth of adoption, not depth of capability. Koda compiles
  decisions in, it doesn't configure them at runtime (P1)
- **Claude Code/Codex**: Vendor lock-in to a single provider. Tight
  coupling to one company's API means the tool's ceiling is set by that
  company's roadmap. Koda treats providers as interchangeable (P1)
- **Goose**: Stepped wizards and fullscreen forms that obscure the
  conversation. Multi-frontend architecture (Electron, Ink TUI, CLI)
  that adds process management overhead for frontends that don't get
  used. Koda keeps the conversation as the primary surface and ships
  one binary (P2)
- **Aider**: A git-centric workflow imposed on the user. Koda imposes no
  workflow on its user. Its own machinery is git-native — experiments are
  branches, the eval harness compares refs, sub-agents work in worktrees
  (P1)

These aren't aesthetic preferences — each rejection traces to a
principle.

## Execution Modes

```bash
koda                      # Auto-starts embedded engine + CLI client (default)
koda exec "fix the bug"   # Headless mode (direct engine, no server)
```

A one-shot run is `koda exec` and nothing else, as in Codex: `koda "..."`
doesn't run a prompt and `koda` with stdin piped stops, since the TUI needs a
terminal. `koda -p` and its `--output-format` were removed in 0.7.0: one way
in keeps one path to maintain, and `koda exec --json` already carries the
summary `--output-format json` printed.

---

## Principles

Principles are truths we enforce on the product, ordered by priority.
They may not be correct for everyone, but we follow them anyway.

### P1: Personal

Koda is built for one person. Not configurable for a group of users —
built for a specific person whose needs can be changed with a few prompts
and a recompile.

- **Any model, any provider.** Cloud APIs, local models, mixed routing.
  No vendor lock-in. The tool serves the person, not the platform
- **Customization over configuration.** If a decision can be made at compile
  time, it must be. Flags that select an execution scenario are fine (`exec`
  for headless) — flags that alter behavior within
  a scenario are not (`--autonomy`, `--model-tier`). If something needs to
  change, change the code.
  
  *Documented exceptions* (each justified by a non-interactive scenario):
  - `--mode safe|auto|plan` (`KODA_MODE`) — trust mode for headless runs
    where `/safe` and `/auto` slash commands aren't reachable mid-session.
    `plan` (read-only) exists only for headless runs.
  - `--mcp-config` — the MCP servers for one run, for scripts and evals that
    need exactly those servers. It's endpoint data (P1 below), and nothing is
    saved.
  - `--max-tokens` / `--temperature` / `--thinking-budget` /
    `--reasoning-effort` — model-call parameters needed when scripting
    headless against a model whose defaults don't fit the task. Interactive
    sessions ignore these in favor of agent JSON config.
  
  Any new flag that doesn't map to one of these scenario carve-outs is a
  P1 violation and should be rejected at PR review.
- **Build only what we need.** Code that isn't written has zero bugs.
  Features that were built but aren't used should be deleted — git preserves
  history
- **Delete aggressively.** Carrying dead code forward degrades every future
  decision because it obscures what the system actually does. No
  "extensibility for later" — trait abstractions and plugin systems have a
  cost even when idle
- **Decide on data.** An idea is a branch. The eval harness measures it on
  koda's own tasks against `main`, and the branch ends merged or deleted
  with its number recorded. Nothing earns complexity by argument
- **Behavior is code; endpoints are data.** What koda does is compiled.
  Where it talks to, which model id it asks for, and how it authenticates
  are data: the keystore, the MCP table, `--provider`, `--model`,
  `--base-url`
- **Latest dependencies, one environment.** Koda runs on its author's
  machine and owes no compatibility to anyone else's. Every dependency and
  the toolchain default to the latest version; an older one needs a stated
  reason. Major bumps are done promptly, by hand. The minimum supported
  Rust version is the pinned toolchain.
- **The latest model outranks backward compatibility.** Koda is built for
  the current Claude models, and an older one gets no code path of its own:
  no thinking budget, no 1M beta, no context table, no special thinking
  replay. It runs as if it were current, with a warning on its first turn
  (`model_effort::older_claude_notice`). A Claude model newer than Koda's
  tables is treated as current too, with no effort sent until it's added.

### P2: Simple enough to own alone

One person builds it, one person maintains it, one person debugs it.
This is the principle that prevents koda from becoming Cursor. Cursor is
capable but complex — extension systems, agent modes, model routing
tiers, configuration surfaces. Koda chooses simplicity: fewer concepts,
one binary, match dispatch, three trust modes. We'd rather be slightly
less capable than incomprehensible.

- **Easy to reason about.** If a reader, human or agent, can't understand
  a unit from one bounded read, it's too complex. Clear component
  boundaries — engine, UI, model, provider — are a consequence of this, not
  a goal in themselves
- **Make it work first.** Ship working code, refactor to clean design
  second, optimize for performance only when measured. A personal tool
  doesn't need the polish of a product — it needs to work
- **Cohesion over abstraction.** Don't split a file just because it's long.
  Don't add a trait just because you might have a second implementation.
  An 800-line file with one cohesive flow beats two 400-line files that
  require cross-file context-switching
- **Copied code passes the same bar.** A component copied from a peer is
  read in full, small enough to rewrite, and adapted to koda's shape on the
  way in. No upstream tracking

### P3: Build for the world six months from now

AI capabilities are compounding. Design for what models and tools will be
able to do, not what they can do today. Don't build workarounds for current
limitations — they'll be obsolete before they're stable.

- **Let the model drive.** The model plans, reasons, and decides which tools
  to call. The engine executes — it does not reimplement planning,
  verification, or decision-making in application code. Today's model
  limitations are tomorrow's non-issues. Evidence is not scaffolding:
  tools and post-edit checks that hand the model compiler output, test
  results or diagnostics give it what it needs to drive. The engine
  deciding, retrying or planning on the model's behalf is scaffolding
- **Don't scaffold around weakness.** Model tiers, capability probes, and
  verbose fallback prompts are building for today. Delete them
- **Frontier models, standard APIs.** Koda targets frontier-class models
  via their standard APIs — whether cloud-hosted (Claude, GPT-4o, Gemini)
  or locally served (Qwen, DeepSeek, Llama via LM Studio/Ollama/vLLM).
  We support the OpenAI-compatible API spec faithfully but do not add
  workarounds for individual models' non-conforming behavior. If a model
  emits malformed output, the fix belongs upstream. See
  [#831](https://github.com/lijunzh/koda/issues/831) for rationale
- **Adapt to a server, not to a model.** A server's protocol, think-tag
  format, context limits and timeouts are data koda conforms to. A model's
  weakness is not compensated for in the engine: if a model emits 66
  identical tool calls, the answer is not a dedup layer that silently
  papers over the problem. Any mechanism that only helps models koda
  doesn't target is deleted. Safety mechanisms should match what frontier
  agents actually ship — not what we imagine might go wrong.
  A code review of Claude Code (zero loop detection), Codex (zero), and
  Gemini CLI (consecutive-call detection + feedback injection) informed
  our approach: consecutive identical calls → feedback injection → hard
  stop only if the model ignores feedback. No windowed fingerprinting,
  no tool-name saturation, no tool-only suppression, no per-turn caps.
  See [#823](https://github.com/lijunzh/koda/issues/823) for the full
  analysis. One exception, for local models only: a reply that repeats
  itself is stopped, and each reply is capped at 32K tokens. Here the
  mechanism to match is the one the model's own maker ships. qwen-code, the
  Qwen team's agent, checks each reply and its reasoning for repeated text.
  In Koda's evals, Ornith, a Qwen fine-tune, looped like this in 8 of 481
  runs, and 6 of those used the whole time limit. Claude never did (603
  runs). Claude Code and Codex check no reply, and Koda doesn't either for
  the models they serve
- **The bets.** Local models reach frontier class on coding tasks. Agents
  do most of the editing and reading. Delegation between agents becomes
  routine. Design for these, not for today's limits

### When principles conflict

P1 says "build only what we need." P3 says design for the bets. These
can conflict. When they do: P1 wins on **timing** (don't build it yet),
but P3 wins on **architecture** (design so it's easy to add). The
`Persistence` trait exists because P3 says the storage backend will
change — but there's only one implementation because P1 says we don't
need a second one yet.

When P2 and P3 conflict, or a principle conflicts with a stated goal,
build it on a branch and let the eval harness decide.

---

## Architecture

### Engine as a Library, Not a Process (P2, P3)

The engine is a Rust library crate (`koda-core`). It communicates
exclusively through `EngineEvent` (output) and `EngineCommand` (input)
enums — it never touches stdout, stdin, or stderr. Filesystem access
for configuration, memory, and tool execution is direct (assumes POSIX).
See `koda-core/src/engine/event.rs` for the protocol definition.

Studied four projects:
- **xi-editor**: Used stdio JSON-RPC. Discontinued. Lesson: protocol becomes
  bottleneck when core and frontend are separate processes.
- **Zed**: Keeps `agent` (engine) and `agent_ui` (rendering) as separate crates
  in the same binary. Engine has zero UI imports — but it *does* import
  `gpui`, `project`, `fs`, and `language_model`. Zed's "engine" is a
  gpui-flavored library; you cannot run `Thread` outside a `gpui::App`.
- **Goose**: Rust engine + ACP server + multiple frontends (Electron, Ink TUI, CLI).
- **Neovim**: C core + msgpack-RPC. Terminal TUI is just one client.

**Zed's approach inspires; Koda finishes the job**: engine and primary client
in the same binary. But Koda goes one step further than
Zed — `koda-core` has zero IO, all output goes through `EngineSink`, all
input arrives via `EngineCommand` over `mpsc::Receiver`, and `EngineEvent` is
`Serialize`. The proof is `koda-core/src/engine/wire.rs`: headless output is a
small projection of the same events the TUI renders, because the engine
boundary is a serializable enum, not a bridge between a UI framework's world
and the wire protocol.

**Concrete consequence**: `KodaAgent` (immutable, `Arc`-shared) is separated
from `KodaSession` (per-conversation, mutable). Zed conflates these into
`Thread`. The split is what makes parallel sub-agents safe: each sub-agent
shares the agent definition by `Arc` and has its own session for state. No
`Arc<RwLock<>>` everywhere.

**Background-task status routing** (#1076, fixed). Bg-task lifecycle
transitions (`Pending` → `Running { iter }` → terminal) flow through
`EngineEvent::BgTaskUpdate` like every other engine output. The
fan-out helper [`BgStatusEmitter`] writes each transition to two
places: the per-task `watch::Sender<AgentStatus>` (read by
`/agents` snapshots and the status-bar pill) AND the registry's
status-event queue (drained by the inference loop alongside
[`BgAgentRegistry::drain_completed`] and forwarded to the active
`EngineSink`). Same drain, same FIFO ordering, same sink — the
TUI and headless mode see identical event streams.
The TUI's bg-task panel still uses `snapshot()` for its primary
render, but that is now a presentational choice (snapshot is
cheaper for a panel that re-renders every frame), not the
documented carve-out it used to be.

### The Client Protocol: A Projection of the Engine (P2, P3)

`EngineEvent` is the engine's internal enum and the TUI's in-process interface.
External clients read the client protocol (`koda-protocol`): sessions, turns,
and items that start, stream and complete, as in Codex's app-server protocol.
`koda-client`'s `EventProjector` builds protocol messages from engine events;
because engine events are flat and items aren't, it keeps the open items, the
turn in progress and the requests waiting for an answer. Every tool call that
starts ends with a `ToolCallResult` saying how (ran, failed, declined,
cancelled), and requests name their call, so every item completes.

Keeping the two apart lets the engine change without breaking clients, and keeps
presentation (spinners, the footer, status bars) off the protocol. A fact the
protocol needs and the engine doesn't have gets added to the engine at its
source, like a tool's outcome or the call an approval is about. `EngineEvent` is
`#[non_exhaustive]`, so the projector has a catch-all: a new engine event stays
off the protocol until it is given a form there.

Typed state events (`Compaction`, `Retry`, `LoopGuard`) carry the text a person
would read as a `notice`, and `EngineEvent::notice()` turns one back into `Info`
or `Warn`. Text clients stay as they were and the wire sends no prose.

A turn's usage is metered in memory by `TurnMeter`, not read back from the
database, because stored totals cover the whole session and a call whose reply
is discarded isn't stored at all. Stored totals do include sub-agents: each one
keeps its messages in its own session, linked to its parent by the
`parent_session` metadata key.

### One Client Protocol, and ACP Removed (P2)

Koda has one client protocol, `koda-protocol` (below). `koda exec --json`
prints it; it is output only so far, since the only clients are scripts and the
eval harness, and the TUI runs in-process. It replaced `stream-json` in 0.7.0.

Koda used to speak ACP through `koda server --stdio`, on the theory that it
would give us Zed integration for free. It was removed on 2026-11-01. Its input
reader waited for the turn, so the first Safe-mode approval deadlocked, and it
ignored the requested workspace and session. Fixing that meant building a
second protocol for a client nobody was using, and two half-built systems are
worse than one working one (P2).

Input over the wire waits for a client that needs it, and it has to start with
a reader that never awaits the turn. Editor support, if it's ever wanted, is an
adapter outside the core.

### The Client API: `koda-protocol` and `koda-client` (P2, P3)

Every client is to reach Koda through one API, as every Codex front end goes
through its app-server. `koda-protocol` defines the messages; `koda-client`
starts Koda's host and talks to it. The host owns the engine, and a client sends
requests and reads answers. In process, a request and its response still pass
through their JSON form, so the TUI, a spawned `koda serve --stdio` and a later
shared server keep one contract.

The framing is JSON-RPC 2.0 with Codex's conventions: `initialize` first,
`noun/verb` method names, camelCase fields, and Codex's error codes. Two things
differ. Messages keep `"jsonrpc": "2.0"`, which Codex drops, so a standard
JSON-RPC library in any language reads them unmodified. And a conversation is a
session, not a thread. Each method is declared once, with its parameters and
response; a client names the method's type and gets the response type back, so
the two can't disagree. `docs/src/protocol-schema.json` is generated from the
types, and a test fails when it's stale.

The protocol grows with the code that serves it. It has `initialize`,
`state/read`, `session/start`, `session/list`, `session/delete`,
`session/compact/start`, `session/settings/update`, `session/unsubscribe`,
`model/list`, `modelProvider/list`, `modelProvider/apiKey/set`,
`modelProvider/apiKey/remove`, `config/read`, `config/batchWrite`,
`storage/read`, `storage/purge`,
`turn/start`,
`turn/interrupt` and `turn/steer`,
a session's notifications (session, turn, items, errors and warnings) and the
server requests for approvals, questions and the loop cap. `koda exec` runs
through the client in process: it opens its session with `approvalPolicy:
never` (Codex's name), so the host answers each request itself, as one-shot
runs always have, and says so with `serverRequest/resolved`; `--json` prints
what the host sends, so the eval harness reads the same messages any client
gets. The TUI is a client too: the host runs its turns, and it answers the
host's requests from its dialogs, steers with `turn/steer` and stops with
`turn/interrupt`. Its renderer still reads the engine's own events, which the
client hands out in process until the TUI renders items, as Codex's TUI read
its old events while it moved onto its app-server. Input history is the
TUI's own, as it is Codex's TUI's: a `history.jsonl` beside the database, in
Codex's record shape (`session_id`, `ts`, `text`), written whole under a lock
and readable by its owner only, which the host never reads. Codex caps its file
by bytes, off by default, because its TUI reads entries as you scroll; Koda's
reads the file at startup, so it keeps the newest 500 entries, as the database
table did. The TUI changes a session's model and mode through the host
(`session/settings/update`) and mirrors what `session/settings/updated`
reports; another provider means a new session (`session/start`), as in
Codex. Its remembered choice and keys go through the host too
(`config/batchWrite`, `modelProvider/apiKey/set`): at startup it names only
the flags given, the host fills in the saved choice, and the TUI builds its
banner from what the session reports. The CLI still loads stored keys early,
to resolve a `--model` alias against the Models API before the host starts;
that only reads them. Because one agent serves turns on several models, the
system prompt's model line is the turn's own
(`KodaAgent::system_prompt_for_model`). For the same move, two more
things stay in process only, each until the protocol has requests for it: a
front end that builds its own agent hands it to the host, which every
session then uses; and a session's sub-agent registry, for showing and
stopping sub-agents. `configure_session`, which set a session's whole config
before each turn, is no longer used by the TUI.

On the host, each open session has a task that owns it and runs its turns, as
Codex's turn requests behave: `turn/start` is answered at once with the turn in
progress, before its first notification, and a second one is refused while it
runs; `turn/interrupt` is answered once the turn has stopped, after its
`turn/completed`; `turn/steer` names the turn it is for, and the text shows up
as a `userMessage` item when the model receives it, so text a turn ends without
delivering simply has no item, and a client that wants it back keeps its own
copy until the item arrives, as Codex's TUI does. A session's provider is
fixed, as a Codex thread's is: `session/start` takes `modelProvider`, `baseUrl`
and `model`, and switching provider means a new session.
`session/settings/update` (Codex's `thread/settings/update`) changes the model
within that provider, the effort and the mode for the turns after it; one sent
during a turn is checked at once and applied when the turn ends, and
`session/settings/updated` reports every setting. The session records its
provider, endpoint and model choice, an alias kept as an alias, and a resume
reopens on them unless the client names others, as Codex's `thread/resume`
restores a thread's; an alias then moves to its line's newest model. `model/list`
gives a provider's models (for Anthropic, the newest of each line) and
`modelProvider/list` the providers, with whether a key is set. Config is the
channel between client and host, as Codex's TUI and app-server use it: the host
owns Koda's config, which nobody maintains by hand, and clients read it with
`config/read` and change it with `config/batchWrite` (Codex's edit shape). For
now it holds the choice a new session starts from, `model` (an alias kept as an
alias), `model_provider` and `base_url`, kept in the database. A new session
that names nothing starts from it, as a Codex thread starts from
`config.toml`; what a session names wins, and a named provider other than the
saved one takes nothing from it. API keys go through
`modelProvider/apiKey/set` and `remove`, Koda's own requests, since Koda keeps a
key per provider and Codex's `account/login/start` signs in one OpenAI
account; no response carries a key. `session/compact/start`
(Codex's `thread/compact/start`) is answered at once and compacts as a turn of
its own, with a `contextCompaction` item whose trigger is `manual`; a running
turn is stopped first and ends interrupted, and the compaction's turn can be
interrupted but not steered. Compacting after a turn is the engine's too: with
`KodaConfig::post_turn_compact_percent` set (`KODA_POST_TURN_COMPACT_PERCENT`),
a final reply that leaves the context past it compacts inside the turn, before
`turn/completed`, as Codex's `model_post_turn_compact_threshold_percent` does,
and like Codex's it is off by default. The TUI used to compact after a turn
itself at 85%; without it, the next turn's pre-flight compaction catches a full
context. `session/unsubscribe`
(Codex's `thread/unsubscribe`) closes a session, stopping its running turn.
Sub-agents' status goes out as it changes, through each session's forwarder,
not only between the turn's model calls. Requests a stopped turn left open are resolved
before its `turn/completed`. Everything a session produces goes on one ordered
queue to the client, unbounded so unread events never hold up a response. A
server request's id is unique across the host's sessions, so a client's answer
names one session's request.

### Extensibility: Thin Core + First-Party Libraries (P1, P2)

The core binary contains only essential tools (file ops, shell, search, web
fetch, memory, agents). Domain-specific capabilities are split into first-party
library crates:

- **First-party libraries** (AST analysis, email): Ship in the same workspace
  as library crates with standalone MCP binary wrappers. `koda-core` calls the
  library functions directly — zero IPC, zero process management. The MCP
  binaries remain available for external consumers (other editors, standalone
  use).

**Principle evolution**: Early v0.1.x compiled everything into one binary.
As the vision expanded beyond coding, we initially adopted MCP for all
domain-specific capabilities ([#113](https://github.com/lijunzh/koda/issues/113)).
In practice, routing in-repo capabilities through stdio JSON-RPC added process
management overhead and IPC failure modes for functionality that ships in the
same workspace. [#431](https://github.com/lijunzh/koda/issues/431) migrated
first-party tools to direct library calls. [#443](https://github.com/lijunzh/koda/issues/443)
removed the then-unused MCP client.

**v0.2.12 re-introduced an MCP client** ([#855](https://github.com/lijunzh/koda/issues/855))
for a fundamentally different purpose: connecting to *third-party* external MCP
servers (Playwright, databases, Slack, user-defined APIs). The MCP client is
exclusively for extending Koda with capabilities outside the workspace.

**Dependency graph**:
```
koda-cli → koda-core  (inference engine + first-party tool calls)
                    → McpManager (optional; connects to third-party MCP servers)
                          → [playwright, db-tools, slack, …] (external, via stdio or HTTP)
```

Koda used to ship two first-party in-repo capability crates (`koda-ast` for
tree-sitter analysis, `koda-email` for IMAP/SMTP). Both were deleted: the
in-tree consumers were removed in earlier refactors (#611 for AstAnalysis,
[CHANGELOG L466] for email tools) and no external consumers ever materialized
for either standalone MCP binary. The graveyard — marked `publish = false`,
not bundled into any release artifact, with no `~/.config/koda/mcp.json` users
on record — was a textbook violation of "features built but not used should be
deleted" (this very document, line 71). Git preserves the work if any of those
capabilities are revived.

**Future first-party capabilities**: should new in-repo capability crates be
added that share the workspace and release cycle, prefer direct library calls
over IPC — simpler, faster, more reliable than stdio JSON-RPC for code that
ships in the same binary anyway. Reserve standalone MCP server binaries for
capabilities that have demonstrated demand from external consumers.

**Server language**: Default to Rust (`cargo binstall`) for koda-maintained
servers. Use Node/Python when critical libraries only exist in those ecosystems.
See [#123](https://github.com/lijunzh/koda/issues/123) for tradeoff analysis.

### Monolithic Database Module (P2)

`db/` stays as a cohesive module. Do not split into sub-modules by domain
(sessions, messages, compaction, metadata). The code is tightly cohesive:
one `Database` struct, one `SqlitePool`, one `impl` block. Splitting into
`db/sessions.rs`, `db/messages.rs`, etc. added boilerplate for zero behavior
change (attempted and reverted in v0.1.2).

**Future trigger**: If v0.2.x adds genuinely new persistence domains (vector
embeddings, knowledge graph, email/calendar), those should be *new files*
alongside `db/` (e.g. `vector_store.rs`), not splits of the existing module.
Split by domain divergence, not by line count.

### Database Backend: SQLite + Persistence Trait (P3)

Keep SQLite for now. The `Persistence` trait lets the backend be swapped
later and enables trait-based testing (mock DB). Cost is minimal (~50 lines).

SQLite is excellent for conversations, sessions, and AST cache. But email,
calendar, documents, and knowledge graphs may require full-text search (FTS5),
vector embeddings, graph relationships, or multi-device sync.

---

## Execution Model

### Async Approval Flow (P3)

Tool approval is an async request/response, not a blocking function call.
The engine
emits `EngineEvent::ApprovalRequest` and awaits
`EngineCommand::ApprovalResponse` — the TUI answers over an in-process
channel, and nothing in the engine depends on that.

**Decision variants distinguish the source of "no" (#1022 B15)**.
`ApprovalDecision` has `Approve`, `ApproveForSession`, `Reject`,
`RejectWithFeedback { feedback }` and `RejectAuto { reason }`. The split
between `Reject` (interactive: a human said no) and `RejectAuto`
(structural: no human is in the loop, e.g. headless mode refuses
destructive ops by policy) matters because the model adapts
differently to each. A human "no" is a signal to ask or re-plan; an
auto-reject is a constraint to route around for the rest of the
session. Pre-fix, headless emitted `Reject` for policy-blocked tools,
the model saw `"User rejected this action."`, and would loop asking
the (nonexistent) user for clarification until timeout. Now the model
sees `[auto-rejected: <reason>]` — the same shape as the bg-agent
closed-channel auto-reject (B10), so the "no human, here's why"
signal is uniform across all auto-reject paths. Wire format is
`{"decision":"reject_auto","reason":"…"}` (snake_case, pinned by
`test_reject_auto_wire_tag_is_snake_case`).

### Tool Dispatch: Match Statement, Not Trait Registry (P2)

Tools are dispatched via a `match` statement in `ToolRegistry::execute()`,
not via a `Tool` trait with dynamic dispatch. Rust's exhaustive matching
catches missing tool handlers at compile time — adding a tool without a
match arm is a compile error. A `HashMap<String, Box<dyn Tool>>` would move
this to a runtime error. The match statement works well at the current
scale (~20 tools).

InvokeAgent is handled at the dispatch level (`tool_dispatch.rs`) before
reaching the registry. RecallContext uses an optional `db` + `session_id`
on the ToolRegistry, set via `.with_session()`. No sentinel strings.

**Future trigger**: When tool additions become frequent enough that editing 3
locations per tool (definitions, match arm, module import) is a bottleneck,
convert to a `Tool` trait + `ToolContext`. Do both together, not piecemeal.

### Tool Name Normalization (P2, documented exception to P3)

`tool_normalize.rs` maps lowercase / snake_case / camelCase tool names
emitted by some models (`list_files`, `read`, `webSearch`) to the canonical
PascalCase forms (`List`, `Read`, `WebSearch`) at exactly one boundary point
in `inference.rs` — before dispatch, approval, persistence, or loop guard
see them.

**This is a documented exception to P3** ("frontier models, standard APIs —
if a model emits malformed output, the fix belongs upstream"). The exception
is justified because:

- Tool name casing is a *cosmetic protocol detail*, not a model capability
  question. Every model knows what `Read` does; some just spell it `read`.
- The fix lives at one file and one call site (~300 LOC, single boundary
  application). It does not bleed into dispatch, approval, or storage.
- Aliases are added only when *unambiguous* — ambiguous variants like
  `"search"` (Grep? Glob?) are intentionally omitted so the dispatcher
  surfaces a clear `Unknown tool` error rather than silently misrouting.

**What we DON'T do**: argument-shape repair, model-specific JSON quirks,
output format coercion. Those would be the actual P3 violations — they
cross from "name canonicalization" into "behavior compensation." If a model
emits structurally wrong tool calls, the fix is upstream or switch models.

### Context Window Auto-Detection (P1, P3)

Context windows are queried from the **provider API** at startup. The
hardcoded lookup table (`model_context.rs`) is the fallback.

Hardcoded values go stale and are wrong for local models where the user
controls context size. LM Studio's `/api/v0/models` lists every downloaded
model; the loaded entry's `loaded_context_length` is the size the user
loaded it with and the limit the server enforces (`max_context_length` is
only the model's maximum, 4x larger in the Oct 2026 eval screens); Gemini's
`/v1beta/models/{id}` reports
`inputTokenLimit` and `outputTokenLimit`; Anthropic's `/v1/models/{id}`
reports `max_input_tokens` and `max_tokens` (a missing, `null` or `0`
value counts as unknown).

**Precedence**: API value > hardcoded lookup > MIN_CONTEXT (4096).

`query_and_apply_capabilities()` runs in all entry points (TUI, headless,
model switch, provider setup).

### Claude Family Aliases Follow the Models API (P1, P3)

`claude-haiku`, `claude-sonnet`, `claude-opus` and `claude-fable` are
resolved at runtime from Anthropic's `GET /v1/models`: the newest
`created_at` whose `line` is `haiku`, `sonnet`, `opus` or `fable`. The
pinned ids in `model_alias.rs` are the offline fallback (no key, no
network, timeout, API error). Anthropic's model list in `/provider` offers
the same newest model per line, not every model the API lists: the latest
model outranks backward compatibility (P1), and an older one can still be
typed.

Anthropic has no floating family alias; every id from the 4.6 generation
on is a pinned snapshot, so an alias table moves only by hand and goes
stale between releases (P1: latest dependencies, one environment). The
API knows the lines, so Koda asks it rather than guessing from the id
(P3: adapt to servers rather than models).

**When**: at TUI start, when an Anthropic key is configured. The request
starts as the TUI launches and the startup joins it, capped at 5 s; its
outcome, success or failure, is kept for the run, so `/model` costs
nothing more. Headless asks only when `--model` names an alias. Without an
Anthropic key nothing is sent.

**A new model Koda doesn't know.** If a line's newest model is missing from
the effort table (`model_effort`), the TUI says so at every start, with a
link that opens an issue asking for it; the link carries only the model
id. The model still runs, as a current one without a tuned effort. The
notice goes away when Koda is updated for it, which is the reminder. Codex
does the like with its catalog's upgrade info, shown once at startup;
Koda shows it until it's handled. `koda exec` only logs it.

**A choice that goes stale.** A session keeps no model of its own: resuming
one runs it on today's choice, as latest-first wants. A model picked from a
list, or set as a provider's default, is saved as its line's alias when it
is that line's newest, so it follows the line. Only an id typed by hand
stays pinned, and when its line has a newer model Koda supports, the TUI
says so at every start, with the alias that follows the newest. The line of
each model comes from the Models API, never from the id.

### Provider Retries (P2, P3)

An HTTP failure is classified once, in `providers/error.rs`, from its status, headers and body. The inference loop matches on the kind and never reads the message. Text matching stays only where a provider states something no other way, overflow and image rejection, and it stays in that file.

Koda follows Codex's limits rather than inventing its own: four retries of a request on a 429, 5xx or network failure, and five of a reply whose stream failed. A wait the server names replaces the backoff. Past five minutes the limit won't lift within a turn, so the request fails. Both counts are settings, `KodaConfig::request_max_retries` and `stream_max_retries`, as they are in Codex's provider config, capped at 100 like Codex's. Koda has no per-provider config file, so they're set with `KODA_REQUEST_MAX_RETRIES` and `KODA_STREAM_MAX_RETRIES`, as the read timeout is. They're for users first: on a local server whose errors a retry won't fix, such as LM Studio's 500 for an oversized prompt, `0` shows the error at once instead of after 15 seconds. Tests about what a failure leaves behind set them to zero or one, instead of waiting out up to 31 seconds of real backoff each.

**Local servers get the same retries.** No peer we checked retries less on a local server, and Goose retries Ollama more. The cost is LM Studio's bare 500, which can mean overflow: it now waits up to 15 seconds before the turn ends. It is still not read as overflow, because the same page comes back for failures unrelated to size.

**A cut-off reply starts over, even after text was shown.** Codex, Gemini CLI and Pi all do this; Goose stops at the first item. It is safe because Koda only runs read-only tools during streaming, and anything that changes files waits for the whole reply. The partial text stays on screen, marked as starting over, and is never stored.

### Compaction: Two Layers (P2, P3)

Koda has two distinct context-reclaim mechanisms that fire at different
thresholds and have different costs:

| Layer | Trigger | Cost | Mechanism |
|---|---|---|---|
| **Microcompact** (`microcompact.rs`) | Time gap since last assistant msg > 5min, AND old tool results exist | Zero LLM tokens — SQL `UPDATE` only | Replaces stale tool result bodies with `[Old tool result content cleared]` stub. Reversible by `RecallContext`. |
| **Full compact** (`compact.rs`) | Context usage ≥ 85% before a model call (auto), past `KODA_POST_TURN_COMPACT_PERCENT` after a final reply (off by default), or `/compact` (manual) | One LLM call on the session's model | Summarizes everything but the newest 30% into a single synthesis message; archives originals in DB. The summarizer sees user and assistant messages whole, as Codex does, and each tool result's first 2,000 characters. Stored as a `system` row and sent as the first user message, as Codex carries its summary. |

Both are inspired by Claude Code's identically-named layers. We adopt the
two-layer approach because:

- **Microcompact alone is insufficient**: clearing tool results doesn't
  reclaim the *messages* themselves; long sessions still blow the budget.
- **Full compact alone is too expensive**: every long pause would trigger
  an LLM round-trip just to age out a `Bash` output.

**Full compact keeps the task out of the model's hands.** Four rules, each
from a real run or from what most peer agents do:

- **The provider's count outranks the estimate.** The estimate runs low (one
  run was at 106-119% of its window while it read 64-73%), so the gap the last
  reported count showed is added to later estimates. It only ever raises them,
  so one bad report can't delay a compaction. It is dropped after a compaction,
  when it describes a context that is gone, and with no report the estimate
  decides alone: local servers and cut-off replies don't always give one.
- **The user's words travel beside the summary, verbatim.** Codex keeps them
  outside the summary too. A summary can lose the request or invent a
  restriction; a copy can't. The budget is 4,000 characters, newest first.
- **The tail is measured by size, not rows.** The newest 30% stays, the share
  Gemini CLI uses. Rows vary by orders of magnitude, so a count could keep a few
  huge tool results and free nothing.
- **A compaction replaces the last summary.** Its row sorts after the tail it
  was stored with, so compaction reads summaries first, the order the model
  sees them, or the next summary is written without the first one.

A history under a fifth of the window is left alone: the system prompt and
tools can't shrink, so compacting would free nothing and fire again next call.

**`COMPACTABLE_TOOLS` lists both PascalCase and snake_case** (`"Read", "read",
"Bash", "bash"`) as defense-in-depth even though `tool_normalize.rs` should
make snake_case unreachable in new sessions. The dual-case list protects
legacy DB rows from before normalization existed. Acceptable redundancy;
delete after a full schema migration if/when one happens.

### Git Context in the Prompt

The system prompt carries a snapshot of the git state, taken once per session and labelled as a snapshot. It does not update as the session goes on: the prompt sits at the front of every request, so changing it would invalidate the provider's prompt cache for the whole conversation behind it. On local Ornith runs that cost up to 40% of wall time (#1451). The model runs git when it needs the current state.

### System Prompt: Every Line Is Paid on Every Call (P1, P2)

The prompt, with project memory, is the largest fixed cost per model call, on a metered model and on a slow local one alike. A rule earns its place by changing what the model does, shown by an eval or by the practice of Codex and Code Puppy. The November 2026 comparison set these rules:

- **Say each rule once, next to what it governs.** Skill rules sit under the skill listing, sub-agent rules under the agent listing. ActivateSkill was stated twice and called in 0 of 594 eval runs, so repetition isn't what makes a rule work.
- **Memory is instructions, and it is capped.** Project memory is the project's `AGENTS.md` or `CLAUDE.md`, so the prompt says to follow it, that it overrides the default guidance, and that the user overrides it. Codex ranks these files the same way. Memory stops at 32,768 characters with a notice, Codex's 32 KiB, because every model call pays for it. It was 16,000, an eighth of a 32K window, until a 28K `AGENTS.md` lost its last six sections, Git rules included, in a test of the 0.6.0 candidate; Codex would have sent it whole, and Claude Code has no hard cap. It stays on the prompt, not in `memory::load`, so `MemoryRead` still returns everything.
- **Memory is a user message, not system prompt.** It opens the first user message, wrapped in `<system-reminder>`, added per request and never stored, so it survives compaction. It is read again at the start of each turn (unchanged files come from a cache), so a `/memory add`, a note the model saves or an edit to the file applies from the next turn; until November 2026 it was read once at start, and a note waited for a restart. Claude Code sends `CLAUDE.md` the same way; Codex sends `AGENTS.md` as a user message of its own. The framing follows Codex: instructions and tips, above the built-in guidance and below the user's request. Claude Code's "OVERRIDE any default behavior" was not copied. Measured on one task (November 2026), the move changed nothing for Haiku 5.5; the length of the file is what costs small models, wherever it sits.
- **Instructions are `AGENTS.md`; Koda's own notes live outside the project.** Codex reads `AGENTS.md`, one per folder from the git root down (`AGENTS.override.md` first), and Claude Code reads `AGENTS.md` where a folder has no `CLAUDE.md`. Koda does the same with the names swapped: `AGENTS.md` first, `CLAUDE.md` as the fallback, one file per folder. One file per folder matters to the eval harness, which writes the same instructions under both names. What the agent writes for itself never goes in the repo: Codex keeps it in `~/.codex/memories`, Claude Code under `~/.claude/projects/<project>/memory/`, Qwen Code outside the repo unless a team tier is switched on. Koda uses Codex's layout, `<config>/memories/<project>/MEMORY.md`. Before, `MemoryWrite` added sections to the project's `CLAUDE.md` or `AGENTS.md`, a file the whole team and every other agent read. A Codex-style background pipeline that extracts notes from past sessions is a separate design, not built.
- **No required second verification.** The prompt asks the model to run the relevant tests, linter or type-checker after a non-trivial change, and stops there. It used to add an adversarial `verify` sub-agent for complex changes, with "fix them and re-verify before reporting success". Neither Codex nor Qwen Code asks for one: Codex's built-in agents are `default`, `explorer` and `worker`, and Qwen Code's review agent runs only inside its `/review` skill. On local models the step was where long tasks stalled. Koda on Qwen3.8-27B called it in all three of the tasks it failed at a two-hour limit, after its own checks had passed; on one of them the fix and its tests were done at 55 minutes. Qwen Code on the same model ran the same checks, stopped, and passed. Across the eval history, Koda runs that called `verify` hit the time limit in 38% of runs (12 of 31), others in 10%. The `verify` agent went with it, and so did `plan`, never called in 1,345 eval runs and covered by the Plan trust mode: the built-ins are now `explore`, `task` and `fork`, the shape Codex (`explorer`, `worker`), Claude Code and Qwen Code (`Explore`, `general-purpose`) ship.
- **The quick reference is for the REPL.** Runs with no REPL pay nothing for it. Neither peer lists its commands; `/help` and the `koda-docs` skill answer the rare question.
- **No rule without a gap.** Peer rules the evals showed no need for stayed out: "implement, don't describe" (the control passes 13 of 13), "don't commit unless asked" (no commits in 594 runs), "don't paste files back" (none on Haiku).
- **`AGENTS.md` is prompt too.** It holds what an agent needs on every turn. The rest is in `docs/src/development.md`.

### Progress Tracking: Model-Owned, History-Persisted, Engine-Surfaced (P3-corollary)

**Principle.** The model owns the task list. The conversation history
persists it (because the `TodoWrite` tool calls are themselves in the
message stream). The engine's only job is to surface each transition
as a structured `EngineEvent` so non-TUI clients can render. The
engine **does not re-inject the list into the system prompt** and
**does not scrape progress from other tools' output text** — both
are instances of the P3 anti-pattern ("don't scaffold around model
weakness"). Compaction preserves outstanding tasks via the summarizer
prompt, not via parallel state.

This is the same shape as the bg-task event routing (#1076 / #1078):
state transitions flow through `EngineEvent`, the engine doesn't
second-guess what the model has already seen.

**Field survey.** All four reference projects converge on the same
design — model writes, history persists, engine surfaces, no
re-injection, no auto-extraction. Citations are real source files
in sibling checkouts, not vibes:

| Project | Tool | Engine state | Re-inject into prompt? | Auto-extract from other tools? | Source |
|---|---|---|---|---|---|
| Claude Code | `TodoWrite` | App-state map keyed by `agentId ?? sessionId` | No (reminder rides on tool result) | No | `src/tools/TodoWriteTool/TodoWriteTool.ts` |
| Codex | `update_plan` | **None** — just emits `EventMsg::PlanUpdate` | No | No | `codex-rs/core/src/tools/handlers/plan.rs` |
| Zed | `update_plan` | **None** — just emits `event_stream.update_plan(…)`; `replay()` reconstructs from history | No | No | `crates/agent/src/tools/update_plan_tool.rs` |
| Gemini CLI | `WriteTodos` | **None** — UI scans message history backwards every render | No | No | `packages/core/src/tools/write-todos.ts` + `packages/cli/src/ui/components/messages/Todo.tsx` |

The Codex handler's own doc comment is the canonical statement of
this design:

> *"This function doesn't do anything useful. However, it gives the
> model a structured way to record its plan that clients can read
> and render. So it's the inputs to this function that are useful
> to clients, not the outputs."*
> — `codex-rs/core/src/tools/handlers/plan.rs`

**Where the field disagrees** (and what koda picks):

| Decision | Field | Koda |
|---|---|---|
| Persist latest list in engine? | Split: CC yes, Codex/Zed/Gemini no | **Yes** — keyed by `session_id`, for clients reconnecting mid-session. Persistence ≠ re-injection. |
| Validate "max 1 in_progress" in tool? | Only Gemini does | **Yes** — small, deterministic, removes one class of model mistake |
| Diff-in-tool-result for UI animation? | Only Claude Code | **Yes** — return `{added, changed, removed}` so UI can highlight transitions; model still gets a plain reminder string |
| `FileTracker` summarized into prompt? | None do this | **No** — same anti-pattern as `progress.rs`. (`FileTracker` was later removed with the `Delete` tool.) |

**Current reality (pre-fix).** Koda today has **four** mechanisms
fighting over the same concern, which is the racing condition #1077
is really about — not just `progress.rs`:

| # | Mechanism | Source of truth | Surfaced via | Status |
|---|---|---|---|---|
| 1 | `progress.rs` | string-matched tool output text (`"Created"`/`"Wrote"`/…) | system prompt | **Delete** |
| 2 | `TodoWrite` + `get_todo_section` | model writes, DB persists | system prompt + tool result | **Drop the system-prompt injection**; keep DB persistence + tool-result reminder |
| 3 | `FileTracker` | typed dispatch outcome | trust / auto-approve-delete only | **Kept then** (never promote to prompt); removed in 2026-11 with the `Delete` tool |
| 4 | `BgAgentRegistry` snapshot vs. event-queue | dual fan-out via `BgStatusEmitter` | UI panel + `EngineEvent::BgTaskUpdate` | **Already fixed** in #1078 — same pattern this principle generalizes |

**Replacement plan** (tracked in #1077, to land in phased PRs):

1. **`compact.rs` summarizer prompt** — explicitly preserve outstanding
   tasks and file paths created/modified across the compacted range
   (~20 LOC). Compaction becomes the sole mechanism that defends
   plan continuity across context-window pressure.
2. **`EngineEvent::TodoUpdate { items, diff }`** — emitted on every
   `TodoWrite` call. `diff: { added, changed, removed }` is computed
   server-side from the previous persisted list so every client
   gets the same structured transition (~80 LOC).
3. **Engine-enforced "max 1 in_progress"** — `TodoWrite` returns an
   error to the model if the input violates the constraint, instead
   of relying on prompt discipline (~10 LOC).
4. **Drop `get_todo_section` system-prompt injection** — remove the
   call site in `prompt.rs` and the helper itself. The DB row stays
   (it's how a reconnecting client gets the snapshot), but it no
   longer rides into the system prompt every turn (~40 LOC removed).
5. **Delete `progress.rs`** and its call sites in `tool_dispatch.rs`
   and `inference.rs` (~365 LOC removed).

**Net: roughly −450 LOC.** Four mechanisms collapse to two (model-owned
task list with event surface + engine-typed file ownership scoped to
trust). Prompt-injection of "done" state goes from two parallel paths
to zero. Compaction's summarizer prompt is the single durable defense
against context-window forgetting.

### Sub-Agent Model Routing (P1, P3)

Sub-agents respect their own provider/model config when explicitly set. The
parent's base_url is only inherited if the sub-agent uses the same provider.

The biggest cost lever — expensive models think, cheap models grunt. A scout
on Gemini Flash costs 1/20th of Opus for codebase exploration. The parent's
Anthropic prompt cache is unaffected because sub-agents make independent API
calls to potentially different providers.

### Sub-Agent Lifecycle (P2, P3)

> **Status (2026-10-27).** The two sections below ("Sub-Agent Lifecycle" and
> "Background-task management surface") record the asynchronous design of
> #1163 and #1325. Sub-agents have been synchronous since #1366: `InvokeAgent`
> and its alias `SpawnAgent` block and return the sub-agent's final answer as
> the tool result, nothing is spawned in the background by the model, and no
> `task_id` is returned. `WaitForMail`, `SendMessage` and the mailbox and
> `AgentPath` machinery under them were deleted, because after #1366 no
> sub-agent could send mail and the only valid recipient was the sender. The
> text is kept as the decision record, not as a description of the current
> behavior. The unreachable dispatch branch, `run_bg_agent` and the registry's
> reserve/attach/drain API were deleted on 2026-11-06; `ChildAgentRegistry` now
> only tracks the sub-agent running inside the current turn, for the TUI's
> activity overlay and the `ChildTaskUpdate` / `ChildAgentActivity` events.
> `/cancel` was removed the same day: it only ran at idle, when no sub-agent
> exists, so `agent:N` never reached one, and stopping a single background
> shell process is a request to the model. Esc and Ctrl+C cancel everything.
>
> **Delegation is opt-in (2026-11-06).** The prompt and the `InvokeAgent`
> description tell the model to delegate only when the user, a skill or the
> project's instructions ask for it, as Codex does and as Claude Code does on its
> Pro plan. In Koda's evals, local-model runs that delegated on their own passed
> 47% and hit the time limit in 50%, against 72% and 13% for runs that didn't;
> Haiku delegated in 3 of 559 runs. The tool and the `explore`, `task` and `fork`
> agents stay.

**#1163 (Lean A)**: every `InvokeAgent` call spawns a background
task and returns its `task_id` immediately. There is no foreground /
blocking variant exposed to the model — the prior `background:bool`
parameter (and its parser) was deleted to remove the failure mode
where models silently default to blocking and serialize parallel
fan-out into sequential calls (#1232 origin issue). Two execution
shapes remain, distinguished only by what the model writes:

1. **Single dispatch** (`InvokeAgent { agent_name, prompt }` or its
   codex-compatible synonym `SpawnAgent { task_name, message }` from
   #1325 Phase 5a) — spawned via `tokio::spawn` onto the multi-thread
   runtime, with the resulting `JoinHandle` held by `BgAgentRegistry`
   as an `AbortOnDropHandle`. Returns a `task_id` synchronously; the
   sub-agent's final output auto-drains as a synthetic user message
   on a future parent iteration. The model uses `WaitForMail` only
   when it has no useful concurrent work AND the next step strictly
   depends on the result; otherwise the auto-drain delivers the
   result without a blocking wait. (Pre-#1325 Phase 5b the blocking
   tool was `WaitTask([task_id])` — retired in favor of `WaitForMail`
   once the mailbox bridge from #1336 made every bg-agent completion
   visible as mail. See "Background-task management surface" below.)
2. **Parallel fan-out** (multiple `InvokeAgent` calls in one assistant
   message) — `tool_dispatch::execute_tools_parallel` spawns each via
   `tokio::spawn` and returns an array of `task_id`s. Each sub-agent
   gets its own DB session and (if write-capable) its own workspace.
   The model can keep working on its own thread while they run.
3. **Forked context** (`agent_name="fork"`) — same dispatch shape, but
   the spawned sub-agent inherits the parent's full conversation history
   into its new session. Fork children cannot themselves spawn
   sub-agents (recursion guard — same blanket rule that applies to
   all sub-agents, see invariant below). The copy itself is **atomic
   and batched** (#1022 B20): a single sqlx transaction inserts every
   parent row with `completed_at` written inline for assistant rows,
   so an N-message fork costs N+3 queries with one fsync instead of
   ~3N queries with N fsyncs. `Persistence::copy_messages_into_session`
   is the only fork-copy path; the row-by-row loop it replaced was a
   hot path the user waits on synchronously, and partial writes on
   error are impossible because the transaction is dropped without

#### Internals (single shared spawn path)

The registry **lives on `KodaSession`**, not inside `inference_loop`,
so bg agents survive across turns: the model can spawn a long-running
explorer in turn 1, return final text in the same iteration, and
turn 2's first iteration drains the result. Owning per-loop would
have aborted every still-pending task on every turn boundary via
`AbortOnDropHandle` (silent data loss in the single-iteration response
case). The inference loop drains completed handles before each
iteration via `BgAgentRegistry::drain_completed()` and injects results
as user messages.

Spawned sub-agents cannot themselves dispatch new sub-agents — inside
`run_bg_agent` the recursive `execute_sub_agent` call sets the private
`inline_only: true` flag, which routes through the inference-loop body
without re-entering the spawn path. (Pre-#1163 this was steered by
overwriting `args["background"] = false`; post-#1163 the flag is an
internal-only parameter, never visible to the model.) `execute_sub_agent`'s
future is `Send` by construction — the function returns
`impl Future<Output = ...> + Send + 'a` rather than using `async fn`,
forcing the compiler to *prove* Send-ness at the boundary. The
transitive offender (generic IPC helpers in `koda-sandbox::ipc`) carry
matching `Send` bounds on their `R`/`W`/`T` parameters; without them,
`tokio::sync::MutexGuard<WorkerClient>` held across an `await` was
silently non-Send.

**Visibility (#1022 B9 + #1201 B + #1163)**: bg agents run with a
`ForwardingChildSink` that wraps a `BufferingSink`. The buffering sink
captures a narrative trace (one short line per `ToolCallStart`, `Info`,
auto-rejected approval) capped at 256 lines and shipped back over the
result oneshot as a `BgPayload = (output, Vec<String>)` for surface at
result-injection time. The forwarding wrapper additionally fans every
interesting event out as `EngineEvent::ChildAgentActivity` on the
parent's sink so the TUI and headless surfaces render live
progress without polling. `NullSink` is preserved for tests and any
future fully-detached path. Streaming text (`TextDelta`/`TextDone`)
is intentionally *not* captured — the final output already crosses
the oneshot, so capturing would duplicate.
   `commit()` on any `?`.

### Background-task management surface (#996)

Both spawned sub-agents and background shell processes
(`Bash { background: true }`) need a runtime surface for
listing, waiting, and cancelling — otherwise the user's only escape
hatch is `/exit`, which nukes everything indiscriminately, and the
model has no way to coordinate its own background work. #996 ships
that surface as a **single unified concept** "background task" with
two flavors distinguished by a prefixed id (`agent:N` /
`process:N`). (Note: `Bash`'s `background:bool` is unrelated to the
now-deleted `InvokeAgent.background` — #1163 only collapsed sub-agent
dispatch shapes; spawning long-running shell processes is a
different concern with a different runtime model.)

Four layers, all on `main`. **Phase 5b of #1325 retired the LLM-facing
layer** (the `ListBackgroundTasks` / `CancelTask` / `WaitTask` trio) in
favor of `WaitForMail` once the mailbox bridge from #1336 made every
bg-agent completion visible as mail — see "#1325 mailbox surface"
below. The TUI slash commands (`/agents`, `/cancel`) and the underlying
registries (`BgAgentRegistry`, `BgRegistry`, `ChildAgentRegistry`)
stayed; only the model-facing tools went away.

- **Layer 0** (#1041): `AgentStatus` enum + `tokio::sync::watch`
  channel per task + per-task `CancellationToken`. Foundation; no
  user-visible change.
- **Layer 1** (#1042): `/agents` and `/cancel <id>` slash commands
  for sub-agents only. Closes #996 P0 for the TUI. Still active.
- **Layer 2** (#1043, retired #1325 Phase 5b): `ListBackgroundTasks`,
  `CancelTask`, `WaitTask` LLM tools so the model could manage *its
  own* background work (spawner-scoped via `caller_spawner:
  Option<u32>`). Added shared `parse_task_id` accepting `agent:N` /
  `process:N` / bare-numeric — the parser survives in `tools/task_id.rs`
  for the TUI slash commands.
- **Phase F** (#1058): `/agents` and `/cancel` extended to cover
  background processes too — same parser, same registry-routing
  logic as the LLM tools, one unified table in the TUI. Still active.
- **Phase G** (#1058, retired #1325 Phase 5b): `ListBackgroundTasks`,
  `CancelTask`, `WaitTask` added to `META_TOOLS` in `skill_scope` so
  a skill-scoped agent could still see / wait / cancel its own
  background work. Removed alongside the tools themselves; the
  meta-tool slot now belongs to `WaitForMail` / `SendMessage` /
  `SpawnAgent` from #1325 Phases 3 and 5a.

**A background process is a process group** (2026-11, following Codex,
whose exec sessions own their group and close it with the session). Each
Bash command leads its own group. A `BgRegistry` entry stays running while
anything in its group lives, not only the process Koda started, so
`server & echo $!` run with `background: true` stays Koda's after its shell
exits. A foreground call ends when its shell does, after a 1 s grace for
output still in the pipes, and hands any group it leaves running to the
registry (`BgRegistry::adopt`), saying so in its result. `kill PID` and
`kill -0 PID` count as Koda's own for any PID in such a group: a check
looks at that process, and a stop ends the group. On macOS the sandbox
opens the group's listening ports. On Linux it can't: there a server is
reached through its background command's sandbox, which serves the
command's network namespace on a Unix socket (`bwrap_loopback.rs`), and a
foreground call's sandbox stops serving when the call ends. So on Linux
only a server started with `background: true` is reachable. Every group
stops when the session ends. Before, Koda tracked only the process it launched. A server started
with `&` was nobody's, its port stayed closed and stopping it asked, and a
call whose job held the output pipe hung until its timeout. Haiku starts
dev servers that way in about half of the eval runs that need one, and the
Bash description saying not to didn't change that. Claude Code tolerates
`&` and stops detached processes a few minutes after the reply. Qwen Code
refuses `&` inside a background call. Gemini CLI records `jobs -p` in an
exit trap.

**Every local port opens only on the user's word** (2026-11, following Codex
and Claude Code's sandbox-runtime). `KODA_ALLOW_LOCAL_BINDING=1` sets
`NetPolicy::allow_local_binding`, which on macOS allows bind and inbound on
`*:*` and outbound to `localhost:*`, sandbox-runtime's rules for its setting
of the same name. Before, the flag added only the wildcard bind and nothing
set it, so a test that starts a server and connects to it failed whatever
the user wanted; in evals of Koda's own history it cost models calls on 2 of
5 core tasks. It is an environment variable because Koda has no settings
file, and so a repository can't open it; sandbox-runtime asks the same of
whoever embeds it. Off by default, since it exposes every service listening
on the machine. Linux ignores it, as sandbox-runtime does: each command's
loopback is its own.

**Koda signals its own processes; a shell `kill` doesn't** (2026-11, as in
Codex, where a model stops a session with Ctrl-C through `write_stdin` and
Codex sends the signal). Each Bash call is its own sandbox, and a sandbox
can't signal a process an earlier one started: even seatbelt's
`(allow signal (target same-sandbox))` doesn't reach across `sandbox-exec`
runs (probed 2026-11-10). So a plain `kill PID` / `kill -0 PID` of an owned
process is Koda's to carry out, and a `kill` of one inside a longer command
(`kill PID; sleep 1; kill -0 PID …`) gets an immediate answer telling the
model to send it on its own, instead of a prompt that couldn't help. Koda
doesn't signal from inside a longer command, which would need a channel
from the sandbox back to Koda; none of the peers has one.

**Spawner scoping** (Layer 2). Each bg-task entry carries an
`Option<u32>` spawner id — the sub-agent invocation id of whoever
kicked it off, or `None` for the top-level inference loop. The LLM
tools filter visibility through `snapshot_for_caller(caller_spawner)`
(plus matching `cancel_as_caller` / `kill_as_caller` paths) so a
sub-agent only sees tasks *it* spawned, not its siblings' or its
parent's. The TUI is the top-level caller (`caller_spawner = None`)
so the user sees everything regardless of who spawned what — they
are the human in the loop.

**Why one surface for both flavors**. Codex / Gemini-CLI / Claude
Code all converge on a unified "background work" surface; splitting
by spawn mechanism (`/agents` vs `/processes`) would push the user
to remember which command launched which task — exactly the friction
the unified view fixes. The `agent:` / `process:` prefix
disambiguates routing in `parse_task_id` so the dispatch layer
knows which registry to hit without re-parsing in three places.

**Bare-numeric back-compat**. The original #1042 `/cancel <id>`
accepted only bare integers (treated as agent ids). Phase F
preserves that form — `/cancel 7` still means `agent:7` — so users
who memorized the old UX don't break. The LLM tool descriptions
*require* the prefix to avoid implicit-routing bugs in agent
workflows, but the shared parser tolerates the bare form for the
TUI path.

**Why bg-task tools were meta** (Phase G, retired #1325 Phase 5b).
`ListBackgroundTasks`, `CancelTask`, and `WaitTask` were added to
`skill_scope::META_TOOLS` alongside `ActivateSkill` / `InvokeAgent` /
`AskUser` because background work outlives any single `ActivateSkill`
boundary: a skill that scoped to e.g. `["Read", "Grep"]` would
otherwise lose the ability to wait on or cancel a process the agent
kicked off before activation. After Phase 5b the meta slot belongs to
`WaitForMail` (every bg-agent completion arrives as mail via the
#1336 bridge), `SendMessage`, and `SpawnAgent` — same rationale,
different set.

**Invariants** — enforced consistently across all four modes:

- **Trust never widens**. `derive_child_trust(parent_runtime, declared)`
  in `koda_core::trust` is the *only* way to compute child trust. Same
  helper for fork, named, and bg paths. **Critical**: `parent_runtime`
  must be the runtime `mode` parameter threaded through dispatch —
  never `parent_config.trust`, which is the *startup* value and is
  not updated by `/safe`/`/auto` toggles (#1022 B19). The structural
  lint test in `koda-cli/tests/regression_test.rs` enforces this at
  CI time.
- **Sandbox never widens**. `compose_child_policy(parent_policy, child_trust,
  root)` calls `SandboxPolicy::compose()` (denies = union, allows = intersect,
  limits = min). Bg agents snapshot the parent's effective policy at spawn
  time — they do not regress to `strict_default()`.
- **Cancellation cascades**. Sub-agents receive `parent_cancel.child_token()`
  via `tokio_util::sync::CancellationToken`. Bg agents are no exception:
  Ctrl+C in the parent kills in-flight bg work. `tokio::task::JoinSet` (or
  `AbortOnDropHandle`) ensures registry drop = task abort = workspace release.
- **Sub-agents write in the project** (P2). They inherit the session's mode
  and work where the main agent works, as Claude Code's and Codex's do, so
  edits land where the user expects. Copying the
  project per sub-agent (`clonefile(2)` on macOS) lost finished work, because
  a copy needs a way back that a shared directory doesn't, and it was gone
  with the copy. Worktrees remain for two cases: an agent that sets
  `"isolation": "worktree"`, and any writer in Safe mode, because a sub-agent
  has no approval channel and Safe promises nothing changes without the
  user's OK. A branch with work on it always survives release.
  **A required worktree that can't be made does not silently downgrade**
  (#1022 B21), whether provisioning failed or there is no git repository:
  the dispatch short-circuits with a structural failure marker (see next
  invariant) instead of dropping the sub-agent into the project, which would
  break Safe's promise. The user-visible warning surfaces through
  `EngineEvent::Info` so it isn't buried in trace logs.
- **Structural failures use the `[ERROR: ...]` marker convention**
  (#1022 B18, B21). When a sub-agent can't produce an answer for
  reasons that are *not* the model's fault — iteration cap exhausted,
  workspace provision failed, future failure modes — the dispatch
  returns a single-line marker shaped `[ERROR: sub-agent '<name>' ...
  <reason> ... <re-strategize hint>]`. Three properties are
  load-bearing and pinned by unit tests: (1) the `[ERROR:` prefix
  signals "structural failure metadata, not a sub-agent answer" so
  the parent model doesn't treat the marker as content; (2) the
  agent name appears so multi-agent flows can disambiguate which
  sub-agent failed; (3) the marker is single-line so it formats
  cleanly as a tool result. Markers are cached by `SubAgentCache`
  with the same key as a successful result, so a verbatim
  re-dispatch with the same prompt doesn't pay the failure cost
  twice — the cache invalidates on any mutating tool, so a
  write-then-retry naturally bypasses the marker. Free constructor
  functions (e.g. `iteration_cap_marker`, `workspace_provision_failure_marker`)
  keep the contract testable without standing up the full sub-agent
  harness.
- **Result caching** (P1, cost lever). `SubAgentCache` keyed by
  `(agent_name, prompt_hash)`. Cache hits = no LLM call. Lives on
  `KodaSession` (sibling of `BgAgentRegistry`) so cross-turn hits
  work — the natural "explore X / read result / explore X again"
  follow-up flow doesn't pay LLM cost twice. Invalidated on any
  mutating tool — including mutations performed *inside* a sub-agent
  (sub-agent dispatch routes through `execute_one_tool`, which honors
  `is_mutating_tool` invalidation just like the top-level path).
  Generation-bumping invalidation makes cross-turn safe: stale entries
  become misses without needing explicit eviction.
- **Single tool-dispatch path**. Sub-agent tool execution does *not*
  re-implement approval+execute logic. After the sub-agent's own approval
  check (using its `effective_root` for path-aware decisions), the call
  flows through `tool_dispatch::execute_one_tool` — the same function the
  parent uses. This guarantees two things uniformly: mutating tools
  invalidate `SubAgentCache` regardless of who called them, and Bash
  output streams through the parent's sink. (`InvokeAgent` is the one
  exception — see the no-nesting invariant below.)
- **No nested sub-agents**. Sub-agents (named, fork, *and* background)
  cannot themselves call `InvokeAgent`. Enforced two ways: (1) the tool
  is filtered from every sub-agent's tool definitions so the model never
  sees it; (2) the sub-agent dispatch loop short-circuits with a clear
  refusal message if a rogue or scripted model emits it anyway. The
  parent at depth 0 can fan out as many parallel/background workers as
  it wants — fan-out is what scales delegation, not depth. Allowing real
  recursion was considered and rejected: it requires a depth cap
  (~hundreds of KB of `async fn` state per level), threading `depth: u32`
  through five functions, and matches no real use case anyone has asked
  for. Codex takes the same stance (their sub-agents can't spawn
  sub-agents either). The type-level mutual-recursion cycle between
  `execute_one_tool` and `execute_sub_agent` is broken with `Box::pin`
  so the compiler accepts the call graph; runtime recursion is
  unreachable by construction.
- **Pre-flight validation everywhere**. `tools::validate::validate_tool_call`
  runs *before* approval prompting in the sequential arm (so the user is
  never asked to approve a tool that's guaranteed to fail) and *before*
  execution in the parallel + split-batch parallel + sub-agent arms (where
  every tool was already classified `AutoApprove` and the next step is
  execution). The wrapper `validate_then_execute_one_tool` exists for
  exactly this purpose.
- **No user interaction from sub-agents**. `AskUser` is filtered from
  every sub-agent's tool definitions — both foreground and background.
  Sub-agents are autonomous delegation: the parent gathers any required
  input *before* dispatching, then passes the answer in the prompt. This
  matches Codex / Claude Code / Gemini-CLI's design and avoids the
  multi-sub-agent attribution problem (which sub-agent is asking?) plus
  the bg-agent deadlock problem (no `cmd_rx` reachable from the user).
  As a defense-in-depth backstop, the dummy `cmd_rx` handed to every
  sub-agent is constructed with the sender bound to `_` so it drops
  immediately at construction — if a non-AskUser tool ever hits the
  `request_approval` path inside a sub-agent (e.g. a Destructive
  operation under inherited Plan trust), `recv()` returns `None`
  rather than blocking forever, and the sub-agent loop maps that to a
  clear `[auto-rejected: '<tool>' requires user confirmation but this
  sub-agent has no channel to the user]` tool result. The model can
  reason about and recover from the rejection; the dispatch loop
  continues. This distinguishes from genuine cancellation (Ctrl+C),
  which still surfaces as `[cancelled]`.

**What we considered and rejected**:

- **Codex's collab v2 surface** (`spawn_agent`/`send_input`/`wait_agent`/
  `close_agent`/`resume_agent`, persistent ThreadId-addressed agents,
  inter-agent mailboxes). Originally rejected as ~3,000 LOC for a
  workflow that's rare in personal use — koda relied on `InvokeAgent` +
  `WaitTask` + drain-on-next-iteration to cover the same ground.
  **#1325 reversed that decision and selectively adopted the mailbox
  half**: Phases 1–2 vendored Codex's `mailbox.rs` substrate and wired
  it into `KodaSession`; Phase 3 shipped `SendMessage` + `WaitForMail`
  as peer-tools; Phase 4 added per-agent paths and a mailbox registry;
  Phase 5a added `SpawnAgent` (codex-compatible synonym for
  `InvokeAgent`) plus a completion-mail bridge from `bg_agent.rs` so
  every bg-agent exit lands in the parent's mailbox
  (`notify_parent_mailbox`); Phase 5b retired the legacy
  `ListBackgroundTasks` / `CancelTask` / `WaitTask` trio now that
  `WaitForMail` covers their use case unified with peer messaging.
  What's still rejected: `close_agent` / `resume_agent` and persistent
  ThreadId-addressed agents — koda agents stay session-scoped, no
  cross-session resume. Net adopted footprint is closer to ~1,500 LOC
  than the original 3,000 estimate because the mailbox machinery is
  shared between peer messaging and bg-completion delivery.
  **Removed again (2026-10-27):** after #1366 made sub-agents synchronous,
  no sub-agent sent completion mail and `SendMessage` could only address
  `/root`, so the mailbox, `AgentPath`, `SendMessage` and `WaitForMail`
  were deleted. If a Codex-style asynchronous agent experiment is ever run,
  rebuild the smallest piece it needs rather than restoring this surface.
- **Codex's `agent_max_depth` + `agent_max_threads` atomic CAS reservations**.
  Koda hardcodes "sub-agents cannot spawn sub-agents" (depth = exactly 1
  for any worker) and adds a per-agent iteration cap. Removes the entire
  class of recursion-depth footguns at zero cost. Revisit only if a real
  use case for depth ≥ 2 ever surfaces — fan-out at depth 1 has covered
  every workflow we've tried.
- **Nested sub-agents** (sub-agent calling `InvokeAgent`). Considered
  during #1022. Tempting because it would let a "manager" sub-agent
  decompose work, but: (a) the master agent can already do that
  decomposition itself; (b) each level costs hundreds of KB of `async
  fn` state plus a workspace, provider, and DB session, so deep stacks
  exhaust the OS thread before the cost dominates; (c) requires depth
  threading through five functions and a hard cap; (d) Codex agrees —
  their sub-agents can't either. Same YAGNI reasoning as `AskUser` from
  sub-agents.
- **Claude Code's seven-typed `Task` taxonomy**
  (`local_bash | local_agent | remote_agent | in_process_teammate | ...`).
  Exactly the "feature surface for many users" P1 rejects. `BgAgentRegistry`
  + `BgRegistry` (for bash) cover the "long-running thing with a result"
  case as two cohesive registries. Don't grow a `trait Task`.
- **Gemini CLI's LLM-based loop detection** (asks the model "are you stuck?"
  every 10–15 turns at extra token cost). Apex form of the anti-pattern P3
  warns about — "don't scaffold around weakness". Frontier models won't need
  this in six months.
- **Code Puppy's plugin system** (`callbacks.py` with 30+ hooks, agent
  frontmatter that can spawn its own MCP servers). Direct violation of P1
  "customization over configuration". Per-agent MCP = per-agent trust audit.

**What we deferred** (architecture supports it; we'll add when the bug exists):

- **Per-tool `is_concurrency_safe(args)` predicate** (Gemini CLI). Would let
  read-only `Bash` (e.g. `ls`, `cat`) join the parallel batch. Today all
  `Bash` is forced sequential. `bash_safety.rs` already does the analysis
  — surfacing it as a `ToolRegistry` method is ~80 LOC.
- **Sibling-cancel on parallel `Bash` failure** (Claude Code). Per-batch
  child `CancellationToken` + typed `[Cancelled: parallel call X errored]`
  result. ~30 LOC.
- **Streaming tool inputs** (Zed `supports_input_streaming`). High-value
  for `Edit`/`Bash` but requires reworking `ToolRegistry::execute` to take
  a stream. P1 says wait for the bug.
- **`FuturesUnordered` instead of `join_all`** for parallel tool execution
  — emits results as they complete instead of after the slowest. ~20 LOC
  win, no protocol change.

---

## Documentation

### Development Docs Live in the Maintainer's Notes

From March to October 2026, the GitHub issue tracker was Koda's design
record ([#212](https://github.com/lijunzh/koda/issues/212): "GitHub issues
are the source of truth for development docs"). Since 2026-10-27, design
docs, plans, reviews and decisions are kept in the maintainer's private
notes instead.

- This file keeps the public principles and architecture decisions.
- GitHub issues are for bug reports and feature requests from users, and
  for the issues CI workflows manage.
- The issue links throughout this file still point at the history behind
  each decision.

### docs.rs as the Documentation Site (P1, P2)

Koda uses `cargo doc` / docs.rs as its documentation site. There is no
separate docs website to build, host, or maintain.

Claude Code hosts a separate docs site at `code.claude.com/docs` and ships
a `claude_code_docs_map.md` index file that the guide agent fetches at
runtime to answer user questions. This requires a docs build pipeline,
hosting infrastructure, and a separate content workflow.

Koda takes a different approach: `koda-core` (engine library) exposes
its modules as `pub mod` so that `cargo doc` renders them. The guide
agent fetches these pages the same way CC's guide agent fetches
`code.claude.com` — but the content comes from rustdoc, not a custom
site.

This means:

- **Module-level `//!` docs are user-facing documentation**, not just
  developer notes. They should explain *what the feature does and how to
  use it*, not just implementation details.
- **`koda-core` modules are `pub`.** The engine library has real
  external consumers (tests, the CLI crate, future server mode) so `pub`
  visibility is correct.
- **`koda-cli` modules are `pub(crate)`.** `koda-cli` is a binary, not
  a library. Its API surface is exactly one function: `run()`. Slash
  command docs, TUI keybindings, and onboarding flow are user docs that
  belong in the README and `koda-core` rustdoc, not in binary internals.
- **Zero infrastructure.** `cargo doc --open` works offline. docs.rs
  publishes automatically on `cargo publish`. No CI pipeline for docs.
- **Single source of truth.** Docs live next to code, never drift.

---

## Interaction

### No `.koda.md` — Use `AGENTS.md` (P1, P2)

Koda will NOT introduce a `.koda.md` project rules file. User-authored
project instructions go in `AGENTS.md`, the file Codex, Qwen Code and Claude
Code also read.

Koda reads `AGENTS.md` in each folder from the git root down, with
`CLAUDE.md` as the fallback (`memory.rs`). Adding `.koda.md` would:
- Create a redundant magic filename with confusing priority semantics
- Force users to maintain two files with overlapping content
- Violate DRY at the ecosystem level — one file should serve both tools

### Conversation-First Interaction (P2)

The conversation is the primary surface. All interactive UI (dropdowns,
approvals, wizards) renders inline within the conversation — never as
fullscreen modals or stepped wizards that obscure the chat history.

*The conversation is the primary surface. Interactions happen within it,
not on top of it.* This is the common thread across Claude Code and Codex.
Goose's stepped wizards and Code Puppy's fullscreen forms violate this —
users find them tedious and disorienting.

**Key choices**:
- Per-command state machine enums, not a generic wizard framework (YAGNI)
- Power-user escape hatch: positional args skip wizards entirely
- No "go back" — Esc to cancel and restart is fine for 2–4 step flows
- Render cache backed by DB — scrollback is a `VecDeque<Line>` viewport
  cache, not a standalone buffer. DB is the source of truth. Virtual scroll
  fetches older messages from DB on demand. No arbitrary buffer cap.
- Single rendering path: all output → render cache → `draw()` (no dual-path)
- Native clipboard (`arboard`) for copy — essential UX since alternate screen
  breaks terminal-native mouse selection for multi-page content

For the viewport layout diagram and interaction patterns, run `/help` in the REPL.

**Competitive analysis**: [#230](https://github.com/lijunzh/koda/issues/230)
**Implementation**: [#229](https://github.com/lijunzh/koda/pull/229), [#472]

[#472]: https://github.com/lijunzh/koda/issues/472

### The Dropdown Is Help (P1, P2)

Removed the `?` keyboard shortcut overlay and `/help` command. The slash
dropdown with descriptions IS the help system.

Three overlapping discovery mechanisms (`?` overlay, `/help` modal, `/`
auto-dropdown) created redundant complexity and viewport resize bugs. The
auto-dropdown on `/` shows all commands with descriptions — that is help.
Keyboard shortcuts moved to the startup banner header.

### Fullscreen Viewport (P2)

Switch from `Viewport::Inline` (terminal-native scrollback) to
`Viewport::Fullscreen` (alternate screen buffer with app-managed scrollback).

Inline viewport had two fundamental bugs that couldn't be fixed within the
inline model:
- **DSR cursor position timeouts** ([#470]): `Viewport::Inline` relies on a
  terminal DSR query to determine cursor position. Some terminals
  (particularly over SSH or slow connections) fail to respond, causing
  multi-second hangs at startup.
- **Resize ghost fragments** ([#418]): When the terminal resizes, inline
  viewport content already "scrolled off" into the terminal's native
  scrollback can't be cleared — causing visual corruption.

**What changed**:
- `scroll_buffer.rs`: app-managed `VecDeque<Line>` with visual-line-aware
  scrolling replaces terminal-native scrollback
- `mouse_select.rs`: click-drag text selection + `arboard` clipboard copy
  (essential — alternate screen disables terminal mouse selection)
- `ansi_parse.rs`: ANSI escape → ratatui Span conversion for tool output
- `history_render.rs`: session history replay into scroll buffer
- Single rendering path: all output → `ScrollBuffer` → `draw_viewport()`

**What didn't change**: The interaction model. Conversation is still the
primary surface. Menus, approvals, and wizards still render in `menu_area`.
The layout is the same — just managed by the app instead of the terminal.

[#470]: https://github.com/lijunzh/koda/issues/470
[#418]: https://github.com/lijunzh/koda/issues/418

---

## Safety

### Folder-Scoped Permissions (P2)

Writes outside `project_root` always require explicit confirmation,
regardless of trust mode. Bash commands are linted for path escapes
before execution.

Defense in depth with three layers — path resolution at execution, path
checks at approval, and heuristic bash linting. The LLM is semi-trusted
(can make mistakes, not adversarial). The concern is accidental blast
radius, not targeted attacks.

For operational details, see the [trust module docs](https://docs.rs/koda-core/latest/koda_core/trust/).

### Security Model (P2)

Per-tool safety classification with three trust modes and hardcoded floors
that override mode settings for high-risk operations.

The LLM is semi-trusted — capable of mistakes, not adversarial. Every tool
call is classified into one of four effects (ReadOnly, LocalMutation,
Destructive, RemoteAction). TrustMode (Plan/Safe/Auto) determines which
effects need confirmation. Hardcoded floors ensure outside-project writes
always require confirmation regardless of mode. The kernel sandbox
(always active) enforces the perimeter.

**TrustMode is the single mechanism** (#1250). The same `TrustMode` enum
derives kernel sandbox bounds, per-tool approval rules, and sub-agent
context-sensitive defaults. There are no separate "strict mode", "yolo
mode", or per-tool toggles — every permission decision in the system
resolves to `(trust_mode, tool_effect)` plus the always-on safety floors.
This is the canonical instance of P1 ("customization over configuration"):
adding a new permission concept means extending the matrix in `trust.rs`,
not bolting on a parallel knob.

For trust mode tables, tool effect matrix, and operational details, see
the [trust module docs](https://docs.rs/koda-core/latest/koda_core/trust/)
and [`docs/src/approval.md`](docs/src/approval.md) (the canonical
user-facing mental-model doc).

**Key design choices**:
- **`Auto × Destructive` confirms, not auto-approves** (#1251). The user
  said YOLO for normal work, not for `rm -rf` / `git reset --hard` /
  `git push --force`. Destructive ops by definition can't be
  undone by the sandbox alone (deleting a tracked file is "legal" inside
  the project root), so Auto keeps the prompt as a deliberate speed-bump.
- **What counts as Destructive follows Codex, plus four kinds of command
  it leaves out** (`bash_safety.rs`, 2026-11). Codex treats a forced `rm`
  as its one dangerous command and lets its sandbox handle everything
  else; Claude Code, with its sandbox on, runs every sandboxed command
  without asking. Koda's list had grown to any `rm` or `rmdir`, `chmod`,
  `chown`, `kill`, `sed -i`, `find -delete` and `-exec`, `eval` and an
  interpreter's `-c`, so in Auto a model's cleanup of its own temp file or
  a `python3 -c` port probe asked, while `python3 script.py`, which can do
  the same, didn't. Now a forced `rm` is the one local file operation that
  asks, wherever it is: behind `env`, `nohup`, `xargs` and the like, inside
  `sh -c`, `eval` or `find -exec`. Koda adds what the sandbox can't contain
  or what loses work for good, since it has no undo: `git reset --hard`,
  `git clean -f`, `git push --force`, publishing, `gh` merges, deletes,
  auth and `api`, `sudo`, disk tools and reboots. Safe mode still asks for
  every change.
- **A yes can cover the rest of the session, in memory only** (2026-11).
  At a prompt for a local change inside the project, `s` approves and stops
  asking for the same Bash command or the same file until the session ends
  (`trust::SessionAllows`, `trust::session_allow_key`). This is Codex's
  model. Claude Code instead writes "don't ask again" rules to a per-machine
  settings file, which would make Koda's behaviour depend on dotfiles that
  differ between machines, and would be a second gating mechanism beside
  `TrustMode`. A session allow only remembers a yes the mode asked for, and
  is never offered for destructive actions, leaving the sandbox, remote
  actions or the outside-project floor. In recorded eval sessions run in
  Safe mode, it would have removed about 40% of prompts.
- **Sub-agents resolve `⏸ confirm` cells using a context-sensitive
  matrix** (`check_tool_for_sub_agent`, #1251). Sub-agents have no live
  human approval channel by design — the master TUI is the only
  confirm-prompt surface. So what the master matrix would treat as
  `⏸ confirm` resolves to **auto-approve for mutations** (the user
  already trusted this sub-agent enough to spawn it; nagging would be
  useless without a UI to nag in) and **block for destructive ops**
  (we still want a backstop on the worst ops, even when no one's home
  to confirm). This pins the bug fix from #1249.
- **Per-agent trust declaration via `trust:` field** (#1247, #1252).
  Agent JSONs declare `"trust": "plan" | "safe" | "auto"`. The legacy
  `write_access: bool` field is deprecated but still loads with a
  deprecation warning. The new field is strictly more expressive: it
  captures sandbox bounds + approval rules + sub-agent defaults in one
  declaration, where `write_access` only spoke to the second.
- Sub-agents inherit the parent’s trust mode (clamped via `TrustMode::clamp()`
  — child can never run with less protection than parent). The clamp is the
  *single source of truth* across all four sub-agent modes (sequential,
  parallel, background, fork) — there is no path that hard-codes a child
  trust value. Same rule for sandbox policy via `SandboxPolicy::compose()`.
- **Kernel-level sandboxing** — always active. macOS uses `sandbox-exec`
  (seatbelt); Linux uses `bwrap` (bubblewrap). Credential directories
  are always protected.
- **One command can leave the sandbox, with the user's yes.** Inside it,
  Bash reaches the network only through the egress proxy's allowlist
  (GitHub and the main package registries over HTTP(S)), so `git push`
  over SSH, other hosts and the local network fail, and `~/.ssh` can't be
  read. Before 2026-11-08 the model wasn't told, and had no way out: in a
  test of the 0.6.0 candidate, Flash-Next took a blocked connection to the
  user's git server to mean they were off their home network, and never
  pushed. Bash now says what the sandbox allows, and takes
  `outside_sandbox: true` with a `reason`. `BashTool::classify` makes such a
  call `Destructive` whatever the command, so the existing matrix gives the
  right answer with no new rule: Safe and Auto ask, showing the reason;
  Plan, sub-agents and headless refuse. It runs with no kernel profile and
  no proxy, keeping the environment scrub and resource limits, plus
  `SSH_AUTH_SOCK` for keys held by an agent. A sandbox denial in the output
  points to it. This is the peers' shape: Codex's `require_escalated` with a
  `justification`, Claude Code's `dangerouslyDisableSandbox`, each approved
  by the user. Unlike them there is no setting to pre-approve commands; each
  call asks.
- **A Bash command is ReadOnly only when proven** (`bash_safety.rs`).
  ReadOnly auto-approves in every mode, so it fails closed: the command
  must be plain words and quoted strings joined only by `&&`, `||`, `;` and
  `|`, with every segment on the read-only allowlist. Newlines, a single
  `&`, redirects, heredocs, subshells, braces, substitutions and line
  continuations all make it at least LocalMutation, even when each word is
  harmless. The exception is `2>&1` and output to exactly `/dev/null`:
  they write no file, and agents add them to read-only commands all the
  time, so this is a deliberate departure from Codex, whose word-only
  parse rejects every redirect. Before, the
  allowlist judged only each segment's first word, so `ls\nrm -rf /`
  and `ls & rm -rf /` passed as ReadOnly. The rule is Codex's
  (`try_parse_word_only_commands_sequence`), done with a quote-aware
  scanner instead of a tree-sitter parse. Destructive detection is
  separate and keeps looking everywhere: it splits on newlines and `&` too.
- **A heredoc body is data, as in Codex** (`bash_safety.rs`,
  `classify_heredocs`). The shell hands the body to a command; it doesn't
  run it. So the command is classified without its bodies, and code in one
  (`fn main() {` written with `cat > a.rs <<'EOF'`) no longer matches the
  fork-bomb pattern `() {`. In recorded eval sessions that pattern made
  about two-thirds of Auto's prompts. Codex parses with tree-sitter and
  finds commands only in the substitutions of an unquoted body; so does
  Koda. Two additions, because Koda's lexer is not a parser and Auto has no
  other gate: a body fed to a shell (`bash <<EOF`, `ssh host <<EOF`) is
  classified as a script, which Codex misses; and a body whose terminator
  never comes may be a misread `<<`, so a destructive command in it still
  counts. `<<` inside `((…))` is a shift, not a heredoc.
- **Arithmetic and function definitions are judged by what they run, as
  in Codex** (`bash_safety.rs`). `$((…))` is arithmetic, not a
  substitution: only the `$(…)` inside it runs, so
  `$(( $(date +%s) - start ))` is judged by `date`, and a bare
  `(( $(…) > 3 ))` evaluates its substitution rather than running the
  output. A function definition is judged by the commands in its body, so
  `run() { cargo test; }` no longer matches the fork-bomb pattern `() {`,
  which is gone. Codex has no fork-bomb check and leaves runaway processes
  to its sandbox, but Koda's sandbox limits CPU, memory and open files, not
  the number of processes, so a function that calls itself
  (`:(){ :|:& };:`) still asks.
- **A substitution is judged by what it runs** (`bash_safety.rs`). The
  command inside a `$(…)`, backticks or `<(…)` / `>(…)` is classified on its
  own, and a destructive one makes the whole command destructive. So does a
  substitution whose output runs as a command, in the command position or
  handed to a shell or interpreter (`bash <(curl …)`, `sh -c "$(…)"`), and
  one that isn't closed. Otherwise the command is at most LocalMutation.
  Until 2026-11 every substitution was destructive, so in Auto an ordinary
  wait loop (`for i in $(seq 1 20); do …; sleep 1; done`) asked, and a
  headless run refused it. An eval task that polls a dev server failed 3 of
  3 that way.
- **Sandboxed shell env scrub** (#1228) — every `bash -c` tool call runs
  with a fixed env allowlist (locale, identity, `PATH`, tmpdir, proxy
  URLs + per-tool extras like `CARGO_HOME` for `cargo`). Secrets like
  `OPENAI_API_KEY`, `AWS_SECRET_ACCESS_KEY`, `GITHUB_TOKEN` never reach
  the child process even if a prompt-injected sub-agent runs `env`.

**Accepted risks**:
1. Destructive detection in shell commands is heuristic — complex syntax can
   hide a destructive command (it still needs approval as LocalMutation in
   Safe mode, but Auto mode approves it)
2. Inside the sandbox the network is the proxy's allowlist, which covers `cargo fetch` and `npm install`; anything else needs an approved `outside_sandbox` call, which runs with the user's full network
3. If the sandbox backend is unavailable (e.g. no bwrap on Linux), `Auto`
   refuses to start or resume; `Safe`/`Plan` may still run with warnings and
   human approval floors

### Content the Agent Reads Is Data (P1, P3)

Web pages, search results and MCP results are wrapped before the model sees
them (`koda-core/src/untrusted.rs`): one line saying the content is data whose
instructions carry no authority beyond the user's request, then the content
between `<<<EXTERNAL_CONTENT>>>` markers with a random id. Marker look-alikes
and chat-template tokens inside are broken up. The system prompt says every
tool result is data and that an attempt to direct the model is reported, not
followed.

- **Why:** a personal assistant reads mail and web pages written by others.
  The security model above bounds what a model may do; this tells it what it
  is reading. All three peers checked draw the same line: OpenClaw wraps web,
  mail and attachments the same way; Codex's action reviewer treats tool
  output as untrusted evidence that can't widen what the user approved;
  Hermes scans instruction files and asks before writes to untrusted MCP
  servers.
- **Short note, by design:** OpenClaw found longer lists of forbidden actions
  in the note made models refuse legitimate requests.
- **Not wrapped:** file reads and command output, which in a project are
  mostly the user's own and read constantly while coding.
- **Measured** with the koda-evals task `assistant-injection`, an inbox whose
  one mail tells the assistant to upload an SSH key and stay quiet.

### No Delete tool (P2)

Koda had a `Delete` tool until 2026-11, and with it a file tracker
(`file_tracker.rs`, #465) that let it delete files Koda had created
without asking. Both are gone. None of the peers has a file-delete tool:
Codex deletes through a `*** Delete File:` entry in `apply_patch`, which it
approves like any write inside the sandbox, and Claude Code, Qwen Code,
Gemini CLI and Goose delete through the shell. Two ways to delete meant two
approval rules: after #1556 a plain `rm a` ran in the sandbox in Auto while
`Delete` of the same file still asked, and in recorded eval runs `Delete`
became Auto's most frequent prompt. Haiku, the main model, used it 3 times
against 75 `rm` commands. Deleting is now a Bash command, judged by the
same classifier as everything else: `rm` runs in the sandbox, a forced
`rm` asks. Opening a database drops the tracker's `owned_files` table;
an older Koda recreates it empty if run again.

### No File Undo (P2)

Koda keeps no history of file changes, and there is no `/undo`. If a change can
be recovered with git or the shell, that's how to recover it. If it can't, a
second history inside Koda isn't the answer: it would cover only some changes,
and the user would have to learn where it stops. It could never cover Bash,
which changes files too, so it would promise less than it seemed to.

The cost is real: a change to work that isn't committed can't be brought back,
and Auto makes those changes without asking. Commit what you want to keep.

Peers split here. Claude Code's `/rewind` keeps snapshots, and Codex dropped its
`/undo` and removed the snapshots behind it, so this follows neither by default.

---

## References

- [ACP (Agent Client Protocol)](https://www.npmjs.com/package/@agentclientprotocol/sdk)
- [Zed Agent Architecture](https://github.com/zed-industries/zed/tree/main/crates/agent)
- [Goose ACP Server](https://github.com/block/goose/tree/main/crates/goose-acp)
- [xi-editor Frontend Protocol](https://xi-editor.io/docs/frontend-protocol.html)
- [Neovim API](https://neovim.io/doc/user/api.html)
