# Reverse Engineering Claude Code

> A bottom-up, source-verified guide to how a production coding agent is built: tools, the query loop, compaction, permissions, hooks, MCP, subagents, the terminal renderer and the remote bridge.


---

<!-- README.md — https://reverseengineeringclaudecode.com/introduction -->

# Dissecting an Agentic Coding Tool

> **A bottom-up, building-blocks reverse-engineering guide to the Claude Code codebase.**

This folder is the working manuscript for a technical book that teaches the entire Claude Code codebase (~1,884 TypeScript/TSX files across 1,910 tracked repository files) from the ground up. Instead of dumping a reference manual or diving headfirst into an 800 KB `main.tsx`, the book starts with the smallest zero-dependency atoms—branded IDs, a 34-line reactive store, an 8-line lazy schema wrapper, an 88-line bounded async-generator multiplexer—and builds upward layer by layer until every subsystem snaps into place.

By the final chapter, you will not just know *where* features live in this repository; you will understand *why* every abstraction was forced into existence by real production constraints: prompt-cache economics, cold-start latency, circular imports, concurrent tool execution, permission boundaries, context-window exhaustion, terminal rendering at 60 FPS, and multi-agent coordination.

---

## Who This Book Is For

- **Engineers building AI agents and coding assistants** who want to see how a production-grade agent harness solves tool scheduling, permissions, compaction, hooks, MCP, subagents, and streaming UI.
- **Systems-minded TypeScript developers** curious how a massive CLI/TUI application manages module graphs, dead-code elimination, custom React reconciliation in the terminal, and zero-dependency state stores.
- **Codebase archaeologists** who want a disciplined, source-verified map of every layer in this repository.

---

## Pedagogical Method: Strict Bottom-Up Assembly

Every chapter follows the same rule: **no magic boxes**.

1. **No forward dependencies.** A chapter only builds on primitives explained in earlier chapters (or explicitly flags a forward reference as a seam to be filled in later).
2. **Every claim cites real code.** Every interface, invariant, and edge case points to exact repo-relative file paths and symbols verified directly in this checkout.
3. **Explain the *why* before the *what*.** Before reading an implementation, each section frames the production failure mode that forced the design—cache busting, NTLM credential leaks on UNC paths, import cycles, stale usage counts after compaction, or subagents mutating the parent's React tree.

---

## Repository Snapshot Caveats

This book is written directly against the tracked source tree in this repository. Readers should know five concrete facts about the checkout up front (covered in full in [Chapter 0](chapters/00-how-to-read-a-1900-file-agent.md)):

1. **Version: Claude Code 2.1.88.** The source carries no version string (the build injects `MACRO.VERSION`), so the version comes from matching the code against the [official changelog](https://code.claude.com/docs/en/changelog). Everything listed through 2.1.87 is present (for example the `X-Claude-Code-Session-Id` header and the `.jj`/`.sl` exclusions from 2.1.86, and the `if` field on hooks from 2.1.85). The 2.1.89 entry, which also covers the unlisted 2.1.88, is largely present too: the `PermissionDenied` hook, the `"defer"` hook decision, `CLAUDE_CODE_NO_FLICKER`, `showThinkingSummaries`, `TaskCreated` and `/buddy`. Nothing from 2.1.90 onward is: no `/powerup`, no `CLAUDE_CODE_PLUGIN_KEEP_MARKETPLACE_ON_FAILURE`, no `disableSkillShellExecution`, no `forceRemoteSettingsRefresh`, and `/tag` and `/vim` (removed in 2.1.92) are still here. 2.1.88 is the one release missing from the changelog, and it is the build published on 2026-03-31, the day this source was imported.
2. **Source-only snapshot:** There is no tracked `package.json`, `tsconfig.json`, lockfile, or test runner config in this repo. Treat code listings as architectural truth rather than a runnable build recipe.
3. **A few imported files are absent:** Some modules imported by tracked source—most notably `types/message.ts`, `query/transitions.ts`, `services/contextCollapse/`, and `services/skillSearch/`—are not present in this checkout. Where a chapter touches those boundaries, it documents what can be verified from call sites and marks absent definitions explicitly.
4. **Build-time feature gating (`bun:bundle`):** Many modules sit behind `feature('...')` guards and `process.env.USER_TYPE === 'ant'` checks for Bun dead-code elimination (DCE). Presence in the repo does not mean a feature ships in every build.
5. **React Compiler output in `.tsx` files:** Tracked `.tsx` files include React Compiler memoization transforms (`import { c as _c } from "react/compiler-runtime"`) and inline base64 source maps containing the original pre-compiled TSX.

---

## Directory Layout

```text
book/
├── README.md                                                 # You are here
├── OUTLINE.md                                                # Complete 8-part, 24-chapter curriculum
├── ARCHITECTURE_MAP.md                                       # Visual layer cake, dependency DAG, cross-cutting themes
├── EDITORIAL_GUIDE.md                                        # Authoring craft, chapter template, verification rules
├── GLOSSARY.md                                               # Living dictionary of codebase types, terms, and gates
└── chapters/
    ├── 00-how-to-read-a-1900-file-agent.md                   # Prologue: Codebase anatomy & 5 recurring idioms
    ├── 01-atoms-types-stores-and-primitives.md               # Ch 1: Layer 0 leaf primitives
    ├── 02-the-tool-contract.md                               # Ch 2: Tool.ts, buildTool, GlobTool, tools.ts
    ├── 03-command-and-message-contracts.md                   # Ch 3: Command contract, processUserInput, messages.ts
    ├── 04-prompt-engineering-and-cache-boundaries.md         # Ch 4: context.ts, system prompt & cache boundaries
    ├── 05-talking-to-the-model.md                            # Ch 5: API client, streaming, retries, usage & cost
    ├── 06-executing-tools.md                                 # Ch 6: Tool execution, hooks, batching & spill storage
    ├── 07-the-heartbeat-query-loop.md                        # Ch 7: query.ts AsyncGenerator turn state machine
    ├── 08-session-envelope-query-engine-and-transcripts.md   # Ch 8: QueryEngine.ts, JSONL transcripts & /rewind
    ├── 09-five-layer-compaction-pipeline.md                  # Ch 9: 5-stage compaction pipeline & circuit breaker
    ├── 10-memory-systems-claudemd-auto-memory-and-dream.md   # Ch 10: CLAUDE.md, memdir, SessionMemory & autoDream
    ├── 11-the-permission-engine.md                           # Ch 11: Permission modes, rules, classifier & modals
    ├── 12-shell-execution-sandboxing-and-workspace-tools.md  # Ch 12: Bash/PowerShell, sandbox & workspace tools
    ├── 13-the-hook-system.md                                 # Ch 13: Hook events, 4 backends, SSRF guard & snapshots
    ├── 14-configuration-settings-and-enterprise-policy.md    # Ch 14: Settings cascade, live watch, MDM & migrations
    ├── 15-model-context-protocol-mcp.md                      # Ch 15: MCP transports, OAuth/XAA, elicitation & ToolSearch
    ├── 16-skills-plugins-output-styles-and-lsp.md            # Ch 16: Skills, 3-layer plugins, output styles & LSP
    ├── 17-background-task-runtime.md                         # Ch 17: 7 task kinds, disk outputs, cron & sleep wakeups
    ├── 18-subagents-context-forking-and-worktrees.md         # Ch 18: Subagent isolation, cache-sharing forks & worktrees
    ├── 19-agent-teams-swarms-and-coordinator-mode.md         # Ch 19: Teammate mailboxes, permission bridge & coordinator
    ├── 20-inside-ink-terminal-react-renderer.md              # Ch 20: Custom React renderer, pure-TS Yoga & Screen diffing
    ├── 21-the-interactive-repl-screens-keybindings-and-vim.md # Ch 21: REPL.tsx, QueryGuard, keybinding chords & Vim mode
    ├── 22-cold-start-mastery-cli-init-main.md                # Ch 22: cli.tsx fast-paths, init.ts, main.tsx & shutdown
    ├── 23-machine-readable-modes-headless-sdk-and-control-protocols.md # Ch 23: print.ts, StructuredIO NDJSON & MCP server mode
    └── 24-across-the-wire-remote-sessions-bridge-and-direct-connect.md # Ch 24: REPL bridge, CCR transports & upstreamproxy
└── appendices/
    ├── A-feature-flags-and-env-knobs.md                      # App A: Complete 90-flag feature() & env-knob inventory
    ├── B-missing-snapshot-boundaries.md                      # App B: 187-target boundary audit & call-site reconstructions
    └── C-mini-harness-blueprint.md                           # App C: ~500-line educational toy clone & production crosswalk
```

---

## Manuscript Progress

| Section / Chapter | File | Status |
| --- | --- | --- |
| Master Curriculum & Chapter Blueprints | [OUTLINE.md](OUTLINE.md) | Complete |
| Layered Architecture & Dependency Map | [ARCHITECTURE_MAP.md](ARCHITECTURE_MAP.md) | Complete |
| Authoring & Verification Guide | [EDITORIAL_GUIDE.md](EDITORIAL_GUIDE.md) | Complete |
| Codebase Glossary | [GLOSSARY.md](GLOSSARY.md) | Complete (v6) |
| **Ch 00:** How to Read a 1,900-File Agent | [00-how-to-read-a-1900-file-agent.md](chapters/00-how-to-read-a-1900-file-agent.md) | Complete |
| **Ch 01:** The Atoms — Identity, Stores, Lazy Schemas, Generators & Caches | [01-atoms-types-stores-and-primitives.md](chapters/01-atoms-types-stores-and-primitives.md) | Complete |
| **Ch 02:** The Tool Contract — Defining What an Agent Can Do | [02-the-tool-contract.md](chapters/02-the-tool-contract.md) | Complete |
| **Ch 03:** The Command & Message Contracts — User Input Meets the Model | [03-command-and-message-contracts.md](chapters/03-command-and-message-contracts.md) | Complete |
| **Ch 04:** Prompt Engineering as Systems Engineering — Context & Cache Boundaries | [04-prompt-engineering-and-cache-boundaries.md](chapters/04-prompt-engineering-and-cache-boundaries.md) | Complete |
| **Ch 05:** Talking to the Model — API Client, Streaming, Retries, and Accounting | [05-talking-to-the-model.md](chapters/05-talking-to-the-model.md) | Complete |
| **Ch 06:** Executing Tools — Validation, Hooks, Concurrency, and Streaming Execution | [06-executing-tools.md](chapters/06-executing-tools.md) | Complete |
| **Ch 07:** The Heartbeat — `query.ts` and the Agentic Turn State Machine | [07-the-heartbeat-query-loop.md](chapters/07-the-heartbeat-query-loop.md) | Complete |
| **Ch 08:** The Session Envelope — `QueryEngine.ts` and Transcript Persistence | [08-session-envelope-query-engine-and-transcripts.md](chapters/08-session-envelope-query-engine-and-transcripts.md) | Complete |
| **Ch 09:** The Five-Layer Compaction Pipeline | [09-five-layer-compaction-pipeline.md](chapters/09-five-layer-compaction-pipeline.md) | Complete |
| **Ch 10:** Memory Systems — `CLAUDE.md`, Auto-Memory, Session Memory, and Auto-Dream | [10-memory-systems-claudemd-auto-memory-and-dream.md](chapters/10-memory-systems-claudemd-auto-memory-and-dream.md) | Complete |
| **Ch 11:** The Permission Engine — Modes, Rules, Classifiers, and Persistence | [11-the-permission-engine.md](chapters/11-the-permission-engine.md) | Complete |
| **Ch 12:** Shell Execution, Sandboxing, and Core Workspace Tools | [12-shell-execution-sandboxing-and-workspace-tools.md](chapters/12-shell-execution-sandboxing-and-workspace-tools.md) | Complete |
| **Ch 13:** The Hook System — Intercepting Every Lifecycle Event | [13-the-hook-system.md](chapters/13-the-hook-system.md) | Complete |
| **Ch 14:** Configuration, Settings Precedence, and Enterprise Policy | [14-configuration-settings-and-enterprise-policy.md](chapters/14-configuration-settings-and-enterprise-policy.md) | Complete |
| **Ch 15:** Model Context Protocol (MCP) — Clients, Transports, Auth, and Tool Search | [15-model-context-protocol-mcp.md](chapters/15-model-context-protocol-mcp.md) | Complete |
| **Ch 16:** Skills, Plugins, Output Styles, and LSP Intelligence | [16-skills-plugins-output-styles-and-lsp.md](chapters/16-skills-plugins-output-styles-and-lsp.md) | Complete |
| **Ch 17:** The Background Task Runtime | [17-background-task-runtime.md](chapters/17-background-task-runtime.md) | Complete |
| **Ch 18:** Subagents, Context Forking, and Git Worktrees | [18-subagents-context-forking-and-worktrees.md](chapters/18-subagents-context-forking-and-worktrees.md) | Complete |
| **Ch 19:** Agent Teams, Swarms, and Coordinator Mode | [19-agent-teams-swarms-and-coordinator-mode.md](chapters/19-agent-teams-swarms-and-coordinator-mode.md) | Complete |
| **Ch 20:** Inside `ink/` — A Custom React Renderer for the Terminal | [20-inside-ink-terminal-react-renderer.md](chapters/20-inside-ink-terminal-react-renderer.md) | Complete |
| **Ch 21:** The Interactive REPL — Screens, Input, Keybindings, and Vim Mode | [21-the-interactive-repl-screens-keybindings-and-vim.md](chapters/21-the-interactive-repl-screens-keybindings-and-vim.md) | Complete |
| **Ch 22:** Cold Start Mastery — From `entrypoints/cli.tsx` Through `init.ts` to `main.tsx` | [22-cold-start-mastery-cli-init-main.md](chapters/22-cold-start-mastery-cli-init-main.md) | Complete |
| **Ch 23:** Machine-Readable Modes — Headless CLI, Agent SDK, and Control Protocols | [23-machine-readable-modes-headless-sdk-and-control-protocols.md](chapters/23-machine-readable-modes-headless-sdk-and-control-protocols.md) | Complete |
| **Ch 24:** Across the Wire — Remote Sessions, Always-On Bridge, and Direct Connect | [24-across-the-wire-remote-sessions-bridge-and-direct-connect.md](chapters/24-across-the-wire-remote-sessions-bridge-and-direct-connect.md) | Complete |
| **Ch 25:** Bringing It to the Present — From 2.1.88 to 2.1.331 | [25-bringing-it-to-the-present.md](chapters/25-bringing-it-to-the-present.md) | Complete |
| **Appendix A:** Complete Inventory of Build-Time `feature()` Flags & Environment Knobs | [A-feature-flags-and-env-knobs.md](appendices/A-feature-flags-and-env-knobs.md) | Complete |
| **Appendix B:** Reconstructing the Missing Snapshot Boundaries from Call Sites | [B-missing-snapshot-boundaries.md](appendices/B-missing-snapshot-boundaries.md) | Complete |
| **Appendix C:** Mini-Harness Blueprint (500-Line Working Toy Clone) | [C-mini-harness-blueprint.md](appendices/C-mini-harness-blueprint.md) | Complete |

---

## Where to Start Reading

1. Start with [**ARCHITECTURE_MAP.md**](ARCHITECTURE_MAP.md) to get the visual 9-layer map in your head.
2. Read [**Chapter 0: How to Read a 1,900-File Agent**](chapters/00-how-to-read-a-1900-file-agent.md) to learn the five recurring idioms that appear in almost every file.
3. Follow Chapters 01–24 in order—building from leaf atoms (`types/ids.ts`, `state/store.ts`) all the way up to `entrypoints/cli.tsx`, `main.tsx`, SDK control protocols, and the remote bridge.
4. Keep [**GLOSSARY.md**](GLOSSARY.md) and Appendices [**A**](appendices/A-feature-flags-and-env-knobs.md), [**B**](appendices/B-missing-snapshot-boundaries.md), and [**C**](appendices/C-mini-harness-blueprint.md) open as reference guides while exploring the repo or building your own agent harness.


---

<!-- ARCHITECTURE_MAP.md — https://reverseengineeringclaudecode.com/architecture-map -->

# Architecture Map: The Bottom-Up Layer Cake

At 1,884 TypeScript/TSX files, Claude Code looks intimidating from the outside. From the inside, however, it is built out of **nine clear architectural layers** stacked one on top of the next. Each layer solves one crisp problem and hands a clean contract upward.

This document is the visual compass for the entire book. Keep it open beside you as you read.

---

## 1. The Nine-Layer Stack

```text
+-----------------------------------------------------------------------------+
| LAYER 8: ENTRYPOINTS, STARTUP & WIRE PROTOCOLS                   [Ch 22-24] |
| entrypoints/cli.tsx -> init.ts -> setup.ts -> main.tsx                      |
| Interactive REPL | Headless Print/SDK (cli/structuredIO.ts) | MCP Server    |
| Remote Bridge (bridge/) | Direct Connect (server/) | Upstream Proxy         |
+-----------------------------------------------------------------------------+
| LAYER 7: TERMINAL UI & INPUT ENGINE                              [Ch 20-21] |
| replLauncher.tsx -> App.tsx -> screens/REPL.tsx -> components/ & hooks/     |
| Custom React Terminal Renderer (ink/ + native-ts/yoga-layout/)              |
| Keybindings (keybindings/) | Vim Editor State Machine (vim/)                |
+-----------------------------------------------------------------------------+
| LAYER 6: CONCURRENCY, BACKGROUND TASKS & MULTI-AGENT SWARMS      [Ch 17-19] |
| Task.ts + tasks/* (local_bash, local_agent, remote_agent, teammate, dream)  |
| AgentTool (runAgent, forkSubagent, resumeAgent) | Worktrees | Swarm/Teams   |
+-----------------------------------------------------------------------------+
| LAYER 5: DYNAMIC CAPABILITIES & INTEGRATIONS                     [Ch 15-16] |
| MCP Client & Transports (services/mcp/) | ToolSearch (deferred schemas)     |
| Skills (skills/) | Plugins (plugins/, utils/plugins/) | LSP (services/lsp/) |
+-----------------------------------------------------------------------------+
| LAYER 4: SAFETY, POLICY, SANDBOX & LIFECYCLE HOOKS               [Ch 11-14] |
| Permission Engine (utils/permissions/) | Auto Classifier (yoloClassifier)   |
| Shell & OS Sandbox (BashTool, utils/sandbox/) | Settings & Policy Merging   |
| Lifecycle Hooks (utils/hooks/: shell, HTTP+SSRF guard, prompt, agent hooks) |
+-----------------------------------------------------------------------------+
| LAYER 3: LONG-HORIZON CONTEXT & MEMORY                           [Ch 09-10] |
| 5-Stage Compaction (budget -> snip -> microcompact -> collapse -> compact)  |
| CLAUDE.md hierarchy | memdir/ | SessionMemory | autoDream | teamMemorySync  |
+-----------------------------------------------------------------------------+
| LAYER 2: THE AGENT ENGINE (PROMPT -> STREAM -> TOOLS -> LOOP)    [Ch 04-08] |
| QueryEngine.ts (session envelope) -> query.ts (AsyncGenerator turn loop)    |
| services/api/claude.ts (streaming + retries) | context.ts + prompts.ts      |
| toolOrchestration.ts (batch concurrency) | StreamingToolExecutor.ts         |
+-----------------------------------------------------------------------------+
| LAYER 1: CORE CAPABILITY & INPUT CONTRACTS                       [Ch 02-03] |
| Tool.ts (Tool, buildTool, ToolUseContext) + tools.ts (catalog & cache sort) |
| types/command.ts (prompt | local | local-jsx) + commands.ts                 |
| utils/messages.ts (normalization) + processUserInput/ (input routing)       |
+-----------------------------------------------------------------------------+
| LAYER 0: LEAF ATOMS & ZERO-DEPENDENCY PRIMITIVES                    [Ch 01] |
| types/ids.ts (branded IDs) | state/store.ts (34-line reactive store)        |
| bootstrap/state.ts (process leaf singleton) | utils/lazySchema.ts           |
| utils/generators.ts (bounded async mux) | utils/fileStateCache.ts (LRU)     |
+-----------------------------------------------------------------------------+
```

---

## 2. Dependency Flow Between Subsystems

```mermaid
flowchart BT
    subgraph L0["Layer 0: Leaf Atoms"]
        IDs["types/ids.ts"]
        Store["state/store.ts"]
        Boot["bootstrap/state.ts"]
        Lazy["utils/lazySchema.ts"]
        Gen["utils/generators.ts"]
        FSC["utils/fileStateCache.ts"]
    end

    subgraph L1["Layer 1: Contracts"]
        Tool["Tool.ts + tools.ts"]
        Cmd["types/command.ts + commands.ts"]
        Msg["utils/messages.ts + processUserInput/"]
        AppState["state/AppStateStore.ts + AppState.tsx"]
    end

    subgraph L2["Layer 2: The Agent Engine"]
        Prompt["context.ts + systemPromptSections.ts"]
        API["services/api/claude.ts + withRetry.ts"]
        ToolExec["toolExecution.ts + toolOrchestration.ts + StreamingToolExecutor.ts"]
        Query["query.ts (turn state machine)"]
        Engine["QueryEngine.ts (session envelope)"]
    end

    subgraph L34["Layers 3 & 4: Memory, Compaction, Permissions & Hooks"]
        Compact["services/compact/*"]
        Mem["memdir/ + SessionMemory/ + claudemd.ts"]
        Perm["utils/permissions/* + sandbox/"]
        Hooks["utils/hooks/* + services/tools/toolHooks.ts"]
    end

    subgraph L56["Layers 5 & 6: Extensions, Tasks & Swarms"]
        Ext["services/mcp/ + skills/ + plugins/ + lsp/"]
        Tasks["Task.ts + tasks/*"]
        Agents["AgentTool/ + utils/swarm/"]
    end

    subgraph L78["Layers 7 & 8: Surfaces & Entrypoints"]
        Ink["ink/ + screens/REPL.tsx + components/"]
        SDK["cli/print.ts + structuredIO.ts + bridge/"]
        CLI["entrypoints/cli.tsx -> init.ts -> main.tsx"]
    end

    IDs --> Boot
    Store --> AppState
    Lazy --> Tool
    FSC --> Tool
    Gen --> ToolExec
    Boot --> Prompt
    Boot --> Query
    AppState --> Tool

    Tool --> ToolExec
    Tool --> Query
    Cmd --> Msg
    Msg --> Engine

    Prompt --> Query
    API --> Query
    ToolExec --> Query
    Compact --> Query
    Mem --> Prompt
    Perm --> ToolExec
    Hooks --> ToolExec
    Hooks --> Query

    Ext --> Tool
    Ext --> Cmd
    Tasks --> AppState
    Agents --> Query
    Agents --> Tasks

    Query --> Engine
    Engine --> SDK
    Query --> Ink
    Ink --> CLI
    SDK --> CLI
```

---

## 3. End-to-End Runtime Dataflow: One User Turn

When a user submits a prompt (whether from the interactive Ink REPL, headless `-p` / SDK mode, or a remote bridge), the turn travels through a remarkably consistent pipeline:

```mermaid
sequenceDiagram
    participant Surface as Surface (REPL / SDK / Bridge)
    participant Input as processUserInput()
    participant QE as QueryEngine / REPL Caller
    participant Loop as query.ts (while true)
    participant Compact as Context Pipeline (5 stages)
    participant API as services/api/claude.ts
    participant Exec as StreamingToolExecutor / runTools
    participant Perm as Hooks + Permissions + Sandbox

    Surface->>Input: raw text / slash command / images
    Input-->>Surface: messages[] + shouldQuery (or local JSX / text)
    Surface->>QE: submitMessage() / start query()
    QE->>Loop: query({ messages, systemPrompt, tools, canUseTool, toolUseContext })

    loop Until Terminal Reason (completed / max_turns / aborted / error)
        Loop->>Compact: toolResultBudget -> snip -> microcompact -> collapse -> autocompact
        Compact-->>Loop: bounded messagesForQuery
        Loop->>API: queryModelWithStreaming(messagesForQuery, fullSystemPrompt, tools)
        loop Streaming SSE chunks
            API-->>Loop: StreamEvent / AssistantMessage
            opt tool_use block arrives & streamingToolExecution enabled
                Loop->>Exec: streamingToolExecutor.addTool(block)
                Exec->>Perm: validateInput -> PreToolUse -> canUseTool
                Perm-->>Exec: allow / deny / updatedInput
                Exec-->>Loop: buffered progress & tool_result
            end
        end
        opt Non-streaming or remaining tools
            Loop->>Exec: runTools() / getRemainingResults()
            Exec-->>Loop: ordered tool_result + contextModifiers
        end
        alt No tool calls
            Loop->>Perm: handleStopHooks() + tokenBudget check
        end
    end

    Loop-->>QE: return Terminal { reason }
    QE-->>Surface: yield SDKMessage / update REPL state + persist JSONL
```

---

## 4. Seven Cross-Cutting Engineering Principles

Seven recurring design principles explain *almost every non-obvious line of code* across all 1,884 files. You will encounter them over and over throughout the book:

### 1. Prompt-Cache Prefix Stability Drives Data Structures
In an agentic loop that makes 10–100 API calls per task, breaking the Anthropic prompt cache turns pennies into dollars and adds seconds per turn. Because prompt caches match exact byte prefixes (`tools` → `system` → `messages`):
- `tools.ts` (`assembleToolPool`) sorts built-in tools and MCP tools into **two separate sorted partitions** so adding an MCP server never interleaves with built-in tools and invalidates the global cache prefix.
- `constants/prompts.ts` splits the system prompt at `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` so the static prefix can use `scope: 'global'`.
- `constants/systemPromptSections.ts` memoizes sections by default and names the opt-out `DANGEROUS_uncachedSystemPromptSection(name, fn, _reason)` to force code reviewers to justify every cache break.
- `context.ts` snapshots `git status` **once** at conversation start and memoizes it.
- `ToolUseContext.renderedSystemPrompt` freezes the parent's system prompt bytes so forked subagents share the parent's KV cache.

### 2. Everything Is an `AsyncGenerator`
From API streaming (`queryModelWithStreaming`) to tool execution (`runToolUse`, `runTools`) to the core agent loop (`query`) to the session wrapper (`QueryEngine.submitMessage`), control flow is modeled as composable `AsyncGenerator<YieldedEvent, ReturnValue>` pipelines. That gives the codebase uniform backpressure, streaming progress events, clean `yield*` delegation, and structured terminal return values (`Terminal`).

### 3. Cold-Start Obsession & Dead-Code Elimination
CLI startup latency is guarded aggressively at every boundary:
- `entrypoints/cli.tsx` resolves `--version` with **zero imports** and dynamically imports fast paths before touching `main.tsx`.
- `utils/lazySchema.ts` defers Zod schema construction behind JS getters until first tool use.
- `entrypoints/init.ts` defers ~400 KB of OpenTelemetry and ~700 KB of gRPC exporters via dynamic `import()`, while firing `preconnectAnthropicApi()` early to hide TCP+TLS handshake latency behind local setup work.
- `bun:bundle`'s `feature('...')` checks stay **inline** at branch sites (never abstracted into helper wrappers or `QueryConfig`) so Bun's bundler tree-shakes internal/experimental modules completely out of external builds.

### 4. Intentional Import-DAG Discipline
In a 1,884-file TypeScript codebase, circular dependencies silently break module initialization. The repo combats cycles systematically:
- Pure type files live in `types/` (`types/ids.ts`, `types/permissions.ts`, `types/command.ts`, `types/hooks.ts`) with zero runtime imports.
- `bootstrap/state.ts` is enforced as a **leaf** via `custom-rules/bootstrap-isolation`, acting as a neutral handoff point (for example, `cachedClaudeMdContent` breaks a 4-hop cycle between `yoloClassifier`, `claudemd`, `filesystem`, and `permissions`).
- Strategic lazy `require()` calls break unavoidable cycles in `tools.ts` (team tools), `QueryEngine.ts` (UI components), and `utils/systemPrompt.ts`.

### 5. Fail-Closed Defaults Everywhere Security or Concurrency Matters
- `buildTool()` defaults every tool to `isConcurrencySafe: () => false` and `isReadOnly: () => false`. A tool must *explicitly opt in* to parallel execution.
- `partitionToolCalls()` wraps `tool.isConcurrencySafe()` in `try/catch` and falls back to `false` (serial) if parsing throws.
- Permission checks layer `validateInput` → blanket deny filtering (`filterToolsByDenyRules`, removing denied tools before the model even sees them) → hooks → rule matching → classifier/sandbox → interactive user prompt.

### 6. Dual Representation: Model View vs. Human View
What the LLM needs and what the human sees in the terminal are intentionally decoupled:
- Every `Tool` separately implements `mapToolResultToToolResultBlockParam()` (compact, model-facing serialization), `renderToolResultMessage()` (React/Ink terminal UI), and `extractSearchText()` (exact rendered text for transcript search highlighting).
- UI-only system notices (`SystemMessage`) are kept in the REPL transcript and stripped at `normalizeMessagesForAPI()`.
- Oversized tool outputs spill to `<persisted-output>` files for the model while keeping structured data for the renderer.

### 7. Explicit Separation of Process Lifetime, Session Lifetime, and Turn Lifetime
Three state containers exist for three distinct lifetimes—never conflate them:
- **`bootstrap/state.ts`** — Process lifetime (PID-scoped, non-reactive, leaf singleton).
- **`AppState` (`state/AppStateStore.ts`)** — Session/UI lifetime (immutable snapshots, reactive via `useSyncExternalStore`).
- **`query.ts` `State` + `ToolUseContext`** — Single turn / subagent execution lifetime (mutable per-iteration loop state, cloned or isolated per child agent).


---

<!-- OUTLINE.md — https://reverseengineeringclaudecode.com/outline -->

# Master Outline & Chapter Blueprints

This book is structured as **8 Parts and 24 Chapters** (plus a Prologue). Each part represents one architectural layer sitting cleanly atop the previous parts. You can think of the book as rebuilding the entire agent harness in miniature, one load-bearing beam at a time.

---

## Prologue

### Chapter 00 — How to Read a 1,900-File Agent *(Drafted)*
- **File:** [chapters/00-how-to-read-a-1900-file-agent.md](chapters/00-how-to-read-a-1900-file-agent.md)
- **Goal:** Orient the reader without drowning in `main.tsx`. Map file distribution across top-level directories (`utils/`, `components/`, `commands/`, `tools/`, `services/`, `hooks/`, `ink/`), explain the five idioms seen everywhere (`feature()` DCE, `lazySchema()`, `bootstrap/state.ts` leaf isolation, React Compiler `_c(...)` output in `.tsx`, and snapshot gaps), and establish the bottom-up reading path.

---

## Part I — Foundations: Atoms, State, and Contracts (Layers 0–1)

*Before an agent can call a model or edit a file, it needs identity, state, bounded caches, concurrency primitives, and a contract for capabilities.*

### Chapter 01 — The Atoms: Identity, Reactive Stores, Lazy Schemas, and Async Generators *(Drafted)*
- **File:** [chapters/01-atoms-types-stores-and-primitives.md](chapters/01-atoms-types-stores-and-primitives.md)
- **Primary Source:** `types/ids.ts`, `state/store.ts`, `state/AppStateStore.ts`, `state/AppState.tsx`, `bootstrap/state.ts`, `utils/lazySchema.ts`, `utils/generators.ts`, `utils/fileStateCache.ts`
- **Key Questions Answered:**
  - How do branded types prevent session/agent ID mix-ups at compile time?
  - Why does the app build its own 34-line store instead of pulling Redux/Zustand, and how does `useSyncExternalStore` prevent whole-tree re-renders?
  - What belongs in `bootstrap/state.ts` (process leaf singleton) vs. `AppState` (immutable reactive UI/session state)?
  - How does `all()` in `utils/generators.ts` multiplex async generators with a concurrency cap?
  - Why does `FileStateCache` normalize paths, evict by byte size, and track `isPartialView`?

### Chapter 02 — The Tool Contract: Defining What an Agent Can Do *(Drafted)*
- **File:** [chapters/02-the-tool-contract.md](chapters/02-the-tool-contract.md)
- **Primary Source:** `Tool.ts`, `tools.ts`, `tools/GlobTool/GlobTool.ts`, `constants/tools.ts`, `constants/toolLimits.ts`
- **Key Questions Answered:**
  - What are the four faces of the `Tool<Input, Output, P>` interface (schema, safety/scheduling, lifecycle, UI/transcript projection)?
  - Why does `buildTool()` default to fail-closed (`isConcurrencySafe: false`, `isReadOnly: false`)?
  - Why does `ToolUseContext` carry both `setAppState` and `setAppStateForTasks`, plus `renderedSystemPrompt` and `contentReplacementState`?
  - Why does `assembleToolPool()` sort built-in tools and MCP tools *separately* instead of sorting one flat array?

### Chapter 03 — The Command & Message Contracts: User Input Meets the Model *(Drafted)*
- **File:** [chapters/03-command-and-message-contracts.md](chapters/03-command-and-message-contracts.md)
- **Primary Source:** `types/command.ts`, `commands.ts`, `utils/messages.ts`, `utils/slashCommandParsing.ts`, `utils/processUserInput/processUserInput.ts`, `utils/processUserInput/processTextPrompt.ts`
- **Key Questions Answered:**
  - How do the three command variants (`prompt`, `local`, `local-jsx`) unify slash commands, skills, plugins, and MCP prompts?
  - How are internal `Message` objects normalized into Anthropic API `MessageParam` payloads (`normalizeMessagesForAPI`), and why are UI-only system messages stripped at that exact boundary?
  - How does `processUserInput()` route plain text, slash commands, image pastes, IDE selections, and attachments?
  - What invariants govern `tool_use` / `tool_result` pairing and thinking-block preservation?

---

## Part II — The Prompt, the Model, and the Engine (Layer 2)

*Now that we have messages and tools, how do we talk to the LLM, keep the prompt cache hot, execute tools concurrently while streaming, and recover from every API failure mode?*

### Chapter 04 — Prompt Engineering as Systems Engineering: Context & Cache Boundaries *(Drafted)*
- **File:** [chapters/04-prompt-engineering-and-cache-boundaries.md](chapters/04-prompt-engineering-and-cache-boundaries.md)
- **Primary Source:** `context.ts`, `constants/systemPromptSections.ts`, `constants/prompts.ts`, `utils/systemPrompt.ts`, `utils/systemPromptType.ts`, `utils/api.ts`, `utils/claudemd.ts`, `services/api/promptCacheBreakDetection.ts`
- **Key Questions Answered:**
  - Why is `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` load-bearing for cross-org global prompt caching?
  - Why does `DANGEROUS_uncachedSystemPromptSection()` require a `_reason` parameter?
  - Why is `git status` snapshotted *once* at conversation start in `context.ts` and memoized?
  - How does `buildEffectiveSystemPrompt()` resolve priority across override, coordinator, agent, custom, and default prompts?

### Chapter 05 — Talking to the Model: API Client, Streaming, Retries, and Accounting *(Drafted)*
- **File:** [chapters/05-talking-to-the-model.md](chapters/05-talking-to-the-model.md)
- **Primary Source:** `services/api/claude.ts`, `services/api/client.ts`, `services/api/withRetry.ts`, `services/api/errors.ts`, `services/api/usage.ts`, `cost-tracker.ts`, `utils/model/model.ts`, `utils/thinking.ts`, `utils/effort.ts`
- **Key Questions Answered:**
  - How does `queryModelWithStreaming()` construct requests, attach beta headers, stream SSE chunks, and yield internal `StreamEvent` / `AssistantMessage` records?
  - How does `withRetry.ts` classify transient errors, backoff, and trigger model fallbacks (`FallbackTriggeredError`)?
  - How are token usage, cache read/creation tokens, and USD cost tracked across models and turns?

### Chapter 06 — Executing Tools: Validation, Hooks, Concurrency, and Streaming Execution *(Drafted)*
- **File:** [chapters/06-executing-tools.md](chapters/06-executing-tools.md)
- **Primary Source:** `services/tools/toolExecution.ts`, `services/tools/toolOrchestration.ts`, `services/tools/StreamingToolExecutor.ts`, `services/tools/toolHooks.ts`, `utils/toolResultStorage.ts`
- **Key Questions Answered:**
  - What is the exact lifecycle of a single tool call (`runToolUse`): lookup → Zod parse → `validateInput` → `PreToolUse` hooks → `canUseTool` permission check → `call()` → spill-to-disk result budgeting → `PostToolUse` hooks?
  - How does `partitionToolCalls()` split tool calls into concurrent read-only batches and serial mutating steps, and why are `contextModifier`s replayed in original block order?
  - How does `StreamingToolExecutor` execute tools *before the assistant finishes streaming*, emit results in strict arrival order, and cancel sibling subprocesses via `siblingAbortController` without killing the turn?
  - How does `toolResultStorage.ts` spill oversized outputs to `<persisted-output>` files without creating a circular Read→file→Read loop (`maxResultSizeChars: Infinity`)?

### Chapter 07 — The Heartbeat: `query.ts` and the Agentic Turn State Machine *(Drafted)*
- **File:** [chapters/07-the-heartbeat-query-loop.md](chapters/07-the-heartbeat-query-loop.md)
- **Primary Source:** `query.ts`, `query/config.ts`, `query/deps.ts`, `query/stopHooks.ts`, `query/tokenBudget.ts`
- **Key Questions Answered:**
  - How is the entire multi-turn agent loop modeled as an `AsyncGenerator` over an explicit `State` struct with typed `Continue` transitions and `Terminal` exits?
  - Why is `stop_reason === 'tool_use'` NOT trusted as the loop continuation signal (and what replaces it)?
  - How do `QueryDeps` and `QueryConfig` decouple I/O and runtime gates from loop logic?
  - Why are `max_output_tokens` and `prompt_too_long` errors *withheld* from downstream SDK consumers until recovery has been attempted?
  - How do stop hooks (`stop_hook_blocking`, `stop_hook_prevented`) and token-budget continuations keep the agent working or halt it cleanly?

### Chapter 08 — The Session Envelope: `QueryEngine.ts` and Transcript Persistence *(Drafted)*
- **File:** [chapters/08-session-envelope-query-engine-and-transcripts.md](chapters/08-session-envelope-query-engine-and-transcripts.md)
- **Primary Source:** `QueryEngine.ts`, `utils/sessionStorage.ts`, `utils/sessionRestore.ts`, `utils/conversationRecovery.ts`, `utils/fileHistory.ts`, `utils/queryHelpers.ts`
- **Key Questions Answered:**
  - What responsibilities live in `QueryEngine` (conversation lifetime, `mutableMessages`, `readFileState`, `permissionDenials`, `totalUsage`, SDK framing) versus `query()` (a single multi-step turn)?
  - How are session transcripts written to JSONL, resumed, forked, and recovered from partial writes?
  - How does `fileHistory.ts` snapshot edited files so `/rewind` can roll back both conversation and disk state?

---

## Part III — Surviving Long Horizon: Context Management & Memory (Layer 3)

*LLMs have finite context windows and zero memory across restarts. This part dissects how the agent compresses history without breaking prompt caches or losing critical facts.*

### Chapter 09 — The Five-Layer Compaction Pipeline *(Drafted)*
- **File:** [chapters/09-five-layer-compaction-pipeline.md](chapters/09-five-layer-compaction-pipeline.md)
- **Primary Source:** `services/compact/microCompact.ts`, `services/compact/apiMicrocompact.ts`, `services/compact/autoCompact.ts`, `services/compact/compact.ts`, `services/compact/sessionMemoryCompact.ts`, `services/compact/prompt.ts`, `services/compact/postCompactCleanup.ts`
- **Key Questions Answered:**
  - How do the five stages compose in `query.ts`: (1) aggregate tool-result budgeting, (2) history snipping, (3) microcompaction (clearing old tool results & cache edits), (4) context collapse, and (5) full summarization (`autoCompact` / `sessionMemoryCompact`)?
  - How does compaction preserve the `compact_boundary`, re-inject active files/skills/plans, reset system-prompt caches, and guard against infinite retry loops with a circuit breaker (`consecutiveFailures`)?
  - Why must `taskBudgetRemaining` be adjusted manually across compaction boundaries?

### Chapter 10 — Memory Systems: `CLAUDE.md`, Auto-Memory, Session Memory, and Auto-Dream *(Drafted)*
- **File:** [chapters/10-memory-systems-claudemd-auto-memory-and-dream.md](chapters/10-memory-systems-claudemd-auto-memory-and-dream.md)
- **Primary Source:** `utils/claudemd.ts`, `memdir/memdir.ts`, `memdir/memoryTypes.ts`, `memdir/findRelevantMemories.ts`, `memdir/memoryScan.ts`, `services/SessionMemory/sessionMemory.ts`, `services/extractMemories/`, `services/autoDream/autoDream.ts`, `services/teamMemorySync/`
- **Key Questions Answered:**
  - How are hierarchical `CLAUDE.md` files discovered, filtered, deduplicated (`loadedNestedMemoryPaths`), and injected as nested memory attachments when the agent touches new subdirectories?
  - How does `startRelevantMemoryPrefetch()` hide memory retrieval latency behind the LLM stream using `using` disposable resource management?
  - How does `SessionMemory` maintain a live structured scratchpad in the background, and how does `autoDream` consolidate cross-session memories under a lock?

---

## Part IV — Safety, Policy, and Extensibility (Layer 4)

*Giving an LLM a shell and filesystem access requires layered defense in depth—and giving users safe ways to customize the loop.*

### Chapter 11 — The Permission Engine: Modes, Rules, Classifiers, and Persistence *(Drafted)*
- **File:** [chapters/11-the-permission-engine.md](chapters/11-the-permission-engine.md)
- **Primary Source:** `types/permissions.ts`, `utils/permissions/PermissionMode.ts`, `utils/permissions/permissions.ts`, `utils/permissions/permissionSetup.ts`, `utils/permissions/filesystem.ts`, `utils/permissions/shellRuleMatching.ts`, `utils/permissions/yoloClassifier.ts`, `utils/permissions/denialTracking.ts`, `hooks/useCanUseTool.tsx`
- **Key Questions Answered:**
  - How do permission modes (`default`, `plan`, `acceptEdits`, `dontAsk`, `bypassPermissions`, `auto`) interact with `alwaysAllowRules`, `alwaysDenyRules`, and `alwaysAskRules` across 8 rule sources?
  - How does filesystem path validation (`filesystem.ts`, `pathValidation.ts`) handle symlinks, additional working directories, and protected paths?
  - How does the auto-mode security classifier (`yoloClassifier.ts`) evaluate tool actions, and how does `denialTracking.ts` fall back to interactive prompting after consecutive denials?

### Chapter 12 — Shell Execution, Sandboxing, and Core Workspace Tools *(Drafted)*
- **File:** [chapters/12-shell-execution-sandboxing-and-workspace-tools.md](chapters/12-shell-execution-sandboxing-and-workspace-tools.md)
- **Primary Source:** `tools/BashTool/`, `tools/PowerShellTool/`, `tools/FileReadTool/`, `tools/FileEditTool/`, `tools/FileWriteTool/`, `tools/GrepTool/`, `utils/bash/`, `utils/sandbox/sandbox-adapter.ts`, `utils/shell/`
- **Key Questions Answered:**
  - How does `BashTool` parse shell ASTs/redirections to distinguish read-only commands from mutating commands, enforce timeouts, and promote long-running commands to background tasks?
  - How does `SandboxManager` (`utils/sandbox/sandbox-adapter.ts`) enforce OS-level filesystem and network isolation?
  - How do `FileReadTool`, `FileEditTool`, and `FileWriteTool` cooperate with `FileStateCache` to prevent stale blind overwrites?

### Chapter 13 — The Hook System: Intercepting Every Lifecycle Event *(Drafted)*
- **File:** [chapters/13-the-hook-system.md](chapters/13-the-hook-system.md)
- **Primary Source:** `types/hooks.ts`, `schemas/`, `utils/hooks.ts`, `utils/hooks/hookEvents.ts`, `utils/hooks/hooksConfigManager.ts`, `utils/hooks/AsyncHookRegistry.ts`, `utils/hooks/execHttpHook.ts`, `utils/hooks/execPromptHook.ts`, `utils/hooks/execAgentHook.ts`, `utils/hooks/ssrfGuard.ts`, `services/tools/toolHooks.ts`
- **Key Questions Answered:**
  - What are the four hook execution backends (shell command, HTTP webhook with SSRF guard, single-shot LLM prompt hook, and full agent hook)?
  - How can a `PreToolUse` hook approve, deny, ask, or rewrite `updatedInput`?
  - How do `hooksConfigSnapshot.ts` and `sessionHooks.ts` guarantee consistent hook behavior across subagents and mid-session settings edits?

### Chapter 14 — Configuration, Settings Precedence, and Enterprise Policy *(Drafted)*
- **File:** [chapters/14-configuration-settings-and-enterprise-policy.md](chapters/14-configuration-settings-and-enterprise-policy.md)
- **Primary Source:** `utils/config.ts`, `utils/settings/settings.ts`, `utils/settings/constants.ts`, `utils/settings/types.ts`, `utils/settings/changeDetector.ts`, `utils/settings/applySettingsChange.ts`, `services/remoteManagedSettings/`, `services/policyLimits/`, `migrations/`
- **Key Questions Answered:**
  - How do user, project, local, CLI flag, MDM, and remote-managed settings merge, and which sources are fail-closed vs. fail-open?
  - How does live settings file watching (`changeDetector.ts`) propagate changes into both interactive `AppState` and headless SDK sessions?
  - How do `migrations/` run idempotently during startup?

---

## Part V — Dynamic Capabilities: MCP, Skills, Plugins, and LSP (Layer 5)

*An agent shouldn't be limited to hardcoded built-in tools. Here we reverse-engineer every dynamic extension point.*

### Chapter 15 — Model Context Protocol (MCP): Clients, Transports, Auth, and Tool Search *(Drafted)*
- **File:** [chapters/15-model-context-protocol-mcp.md](chapters/15-model-context-protocol-mcp.md)
- **Primary Source:** `services/mcp/client.ts`, `services/mcp/config.ts`, `services/mcp/auth.ts`, `services/mcp/useManageMCPConnections.ts`, `services/mcp/elicitationHandler.ts`, `services/mcp/InProcessTransport.ts`, `services/mcp/SdkControlTransport.ts`, `tools/MCPTool/`, `tools/ToolSearchTool/`, `utils/toolSearch.ts`
- **Key Questions Answered:**
  - How does the MCP client manager handle stdio, SSE/HTTP, WebSocket, in-process, and SDK-control transports plus OAuth flows?
  - How do MCP tools get normalized (`mcp__server__tool`), permission-checked, and exposed alongside built-ins?
  - How does `ToolSearchTool` + `shouldDefer: true` solve tool-schema context bloat when dozens of MCP servers are attached?

### Chapter 16 — Skills, Plugins, Output Styles, and LSP Intelligence *(Drafted)*
- **File:** [chapters/16-skills-plugins-output-styles-and-lsp.md](chapters/16-skills-plugins-output-styles-and-lsp.md)
- **Primary Source:** `skills/loadSkillsDir.ts`, `skills/bundledSkills.ts`, `tools/SkillTool/`, `plugins/builtinPlugins.ts`, `utils/plugins/`, `outputStyles/`, `services/lsp/LSPServerManager.ts`, `services/lsp/LSPClient.ts`, `services/lsp/passiveFeedback.ts`, `tools/LSPTool/`
- **Key Questions Answered:**
  - How are Markdown-defined skills parsed, path-scoped (`paths` glob triggers), discovered, and executed either inline or in a forked subagent?
  - How do plugins bundle commands, skills, agents, hooks, and MCP servers—and how does `/reload-plugins` hot-swap them?
  - How does `services/lsp/` run language servers in the background and feed compiler diagnostics back to the model?

---

## Part VI — Concurrency, Tasks, Subagents, and Swarms (Layer 6)

*One agent turn is good; background jobs, isolated worktrees, forked subagents, and cooperating teammate swarms are where the architecture turns distributed.*

### Chapter 17 — The Background Task Runtime *(Drafted)*
- **File:** [chapters/17-background-task-runtime.md](chapters/17-background-task-runtime.md)
- **Primary Source:** `Task.ts`, `tasks.ts`, `tasks/types.ts`, `tasks/stopTask.ts`, `tasks/LocalShellTask/`, `tasks/LocalAgentTask/`, `tasks/RemoteAgentTask/`, `tasks/InProcessTeammateTask/`, `tasks/DreamTask/`, `utils/task/`
- **Key Questions Answered:**
  - How does a single unified `TaskStateBase` record track 7 distinct background task kinds (`local_bash`, `local_agent`, `remote_agent`, `in_process_teammate`, `local_workflow`, `monitor_mcp`, `dream`)?
  - How are task outputs persisted to disk with byte offsets (`outputFile`, `outputOffset`) so the agent and UI can tail them without holding gigabytes in RAM?
  - How do scheduled cron tasks (`tools/ScheduleCronTool/`, `utils/cron*.ts`) and `SleepTool` enable proactive/periodic wakeups?

### Chapter 18 — Subagents, Context Forking, and Git Worktrees *(Drafted)*
- **File:** [chapters/18-subagents-context-forking-and-worktrees.md](chapters/18-subagents-context-forking-and-worktrees.md)
- **Primary Source:** `tools/AgentTool/AgentTool.tsx`, `tools/AgentTool/runAgent.ts`, `tools/AgentTool/forkSubagent.ts`, `tools/AgentTool/loadAgentsDir.ts`, `tools/AgentTool/builtInAgents.ts`, `tools/AgentTool/resumeAgent.ts`, `tools/EnterWorktreeTool/`, `utils/worktree.ts`
- **Key Questions Answered:**
  - How does `createSubagentContext()` isolate a child agent's `readFileState`, `abortController`, `localDenialTracking`, and `setAppState` (while keeping `setAppStateForTasks` wired to the root store)?
  - How does `forkSubagent.ts` freeze `renderedSystemPrompt` and clone `contentReplacementState` so a forked subagent achieves near-100% prompt-cache hits against its parent's conversation prefix?
  - How do sidechain transcripts enable resuming a background agent days later?
  - How do `EnterWorktreeTool` / `ExitWorktreeTool` isolate concurrent code edits in Git worktrees?

### Chapter 19 — Agent Teams, Swarms, and Coordinator Mode *(Drafted)*
- **File:** [chapters/19-agent-teams-swarms-and-coordinator-mode.md](chapters/19-agent-teams-swarms-and-coordinator-mode.md)
- **Primary Source:** `utils/swarm/inProcessRunner.ts`, `utils/swarm/spawnInProcess.ts`, `utils/swarm/leaderPermissionBridge.ts`, `utils/swarm/permissionSync.ts`, `utils/swarm/teamHelpers.ts`, `utils/teammateMailbox.ts`, `tools/TeamCreateTool/`, `tools/SendMessageTool/`, `coordinator/`
- **Key Questions Answered:**
  - How do in-process teammates and pane/tmux teammates communicate via mailboxes (`SendMessageTool`, `teammateMailbox.ts`)?
  - How does `leaderPermissionBridge.ts` bubble a worker's permission prompt up to the team leader's interactive terminal?
  - How does Coordinator Mode strip editing tools from the leader and turn it into a pure orchestrator over worker agents?

---

## Part VII — The Terminal UI Engine (Layer 7)

*A terminal app that streams tokens, renders diffs, handles vim motions, supports mouse selection, and shows live spinners at 60 FPS cannot rely on `console.log`.*

### Chapter 20 — Inside `ink/`: A Custom React Renderer for the Terminal *(Drafted)*
- **File:** [chapters/20-inside-ink-terminal-react-renderer.md](chapters/20-inside-ink-terminal-react-renderer.md)
- **Primary Source:** `ink/dom.ts`, `ink/reconciler.ts`, `ink/ink.tsx`, `ink/render-node-to-output.ts`, `ink/screen.ts`, `ink/log-update.ts`, `ink/parse-keypress.ts`, `ink/selection.ts`, `ink/layout/`, `native-ts/yoga-layout/`
- **Key Questions Answered:**
  - Why does this repo maintain a full vendored/customized Ink implementation (~96 files) instead of a stock npm dependency?
  - How does a React component tree flow through `react-reconciler` → custom DOM nodes → Yoga flexbox layout → 2D character cell `Screen` buffer → diffed ANSI escape sequences?
  - How do terminal focus tracking, mouse hit-testing (`hit-test.ts`), text selection, Kitty/iTerm keyboard parsing (`parse-keypress.ts`), and hyperlinks work?

### Chapter 21 — The Interactive REPL: Screens, Input, Keybindings, and Vim Mode *(Drafted)*
- **File:** [chapters/21-the-interactive-repl-screens-keybindings-and-vim.md](chapters/21-the-interactive-repl-screens-keybindings-and-vim.md)
- **Primary Source:** `replLauncher.tsx`, `components/App.tsx`, `screens/REPL.tsx`, `interactiveHelpers.tsx`, `components/PromptInput/`, `components/messages/`, `keybindings/`, `vim/`, `hooks/useVimInput.ts`, `hooks/useMergedCommands.ts`, `hooks/useMergedTools.ts`
- **Key Questions Answered:**
  - How does `screens/REPL.tsx` bridge the async generator of `query()` into React state, message lists, progress indicators, permission modals, and queued user prompts?
  - How does `keybindings/` resolve user-customizable shortcuts across contexts without colliding with modal dialogs or terminal sequences?
  - How does `vim/` implement a pure-functional state machine for motions, operators, and text objects inside the prompt editor?

---

## Part VIII — Entrypoints, Startup, SDK, and Remote Control (Layer 8)

*Now—and only now—we arrive at `entrypoints/cli.tsx` and `main.tsx`, seeing how every layer we built gets wired together for every execution mode.*

### Chapter 22 — Cold Start Mastery: From `entrypoints/cli.tsx` Through `init.ts` to `main.tsx` *(Drafted)*
- **File:** [chapters/22-cold-start-mastery-cli-init-main.md](chapters/22-cold-start-mastery-cli-init-main.md)
- **Primary Source:** `entrypoints/cli.tsx`, `entrypoints/init.ts`, `setup.ts`, `main.tsx`, `utils/startupProfiler.ts`, `utils/gracefulShutdown.ts`, `utils/cleanupRegistry.ts`
- **Key Questions Answered:**
  - How does `cli.tsx` keep `--version` at zero imports and branch fast-paths (MCP servers, daemon workers, remote bridge) before touching the 800 KB `main.tsx`?
  - Why does `init.ts` order config loading → safe env vars → CA certs (before BoringSSL caches the cert store!) → mTLS/proxy → `preconnectAnthropicApi()` TCP+TLS warmup?
  - How does `main.tsx` run parallel prefetches, trust dialogs, migrations, and dispatch into interactive REPL vs. `-p` print mode vs. SDK mode?

### Chapter 23 — Machine-Readable Modes: Headless CLI, Agent SDK, and Control Protocols *(Drafted)*
- **File:** [chapters/23-machine-readable-modes-headless-sdk-and-control-protocols.md](chapters/23-machine-readable-modes-headless-sdk-and-control-protocols.md)
- **Primary Source:** `cli/print.ts`, `cli/structuredIO.ts`, `cli/ndjsonSafeStringify.ts`, `entrypoints/agentSdkTypes.ts`, `entrypoints/sdk/controlSchemas.ts`, `entrypoints/sdk/coreSchemas.ts`, `entrypoints/mcp.ts`, `utils/streamJsonStdoutGuard.ts`
- **Key Questions Answered:**
  - How does `structuredIO.ts` multiplex NDJSON user inputs, control requests, permission round-trips, and MCP elicitations over stdin/stdout while keeping stdout pure?
  - How does `entrypoints/mcp.ts` turn the agent itself into an MCP server?

### Chapter 24 — Across the Wire: Remote Sessions, Always-On Bridge, and Direct Connect *(Drafted)*
- **File:** [chapters/24-across-the-wire-remote-sessions-bridge-and-direct-connect.md](chapters/24-across-the-wire-remote-sessions-bridge-and-direct-connect.md)
- **Primary Source:** `bridge/bridgeMain.ts`, `bridge/remoteBridgeCore.ts`, `bridge/replBridge.ts`, `bridge/replBridgeTransport.ts`, `bridge/bridgePermissionCallbacks.ts`, `cli/transports/HybridTransport.ts`, `cli/transports/WebSocketTransport.ts`, `cli/transports/SSETransport.ts`, `remote/RemoteSessionManager.ts`, `server/directConnectManager.ts`, `upstreamproxy/`
- **Key Questions Answered:**
  - How does the REPL bridge expose a local terminal session to a remote web/mobile client (`claude.ai`) with bidirectional messages, attachments, and remote permission approvals?
  - How do `HybridTransport`, `WebSocketTransport`, and `SSETransport` handle reconnection, backpressure, and ordered event delivery?
  - How does `upstreamproxy/` inject org credentials into container subprocess requests via a local HTTP `CONNECT` relay?

---

## Part IX — Epilogue: The Snapshot Meets the Shipped Product

*The book ends where its source ends, at 2.1.88. This epilogue carries the nine-layer model forward to the build installed today, and labels every claim by how we know it.*

### Chapter 25 — Bringing It to the Present: From 2.1.88 to 2.1.331 *(Drafted)*
- **File:** [chapters/25-bringing-it-to-the-present.md](chapters/25-bringing-it-to-the-present.md)
- **Goal:** Map eight months and roughly 240 releases of drift onto Layers 0–8, tagging each claim as Changelog, Binary (2.1.331 or 2.1.296 extraction), or Speculation, and show which 2.1.88 contracts held.
- **Primary Source:** the public changelog (2.1.89–2.1.331), modules carved from the shipped 2.1.331 native binary, [2026-10-11-claude-code-2.1.296-workflows-binary-audit.md](../2026-10-11-claude-code-2.1.296-workflows-binary-audit.md), and snapshot anchors such as `Tool.ts`, `query.ts`, `entrypoints/sdk/coreTypes.ts`, `types/permissions.ts`, `constants/betas.ts`
- **Key Questions Answered:**
  - What can a bun-compiled binary tell us about the current architecture, and what does minification hide?
  - Which snapshot `feature()` gates became shipping features (workflows, auto mode, NO_FLICKER fullscreen, PowerShell, Code Mode), and what was removed (`/tag`, `/vim`, `/buddy`, TaskOutput, TeamCreate)?
  - Which 2.1.88 abstractions (Tool defaults, the generator loop and its terminal reasons, the permission decision-reason union, hook events, the dynamic cache boundary) survived to 2.1.331?

---

## Appendices *(Drafted)*

- **Appendix A — Complete Inventory of Build-Time `feature()` Flags & Environment Knobs:** [appendices/A-feature-flags-and-env-knobs.md](appendices/A-feature-flags-and-env-knobs.md)
- **Appendix B — Reconstructing the Missing Snapshot Boundaries (`types/message.ts`, `query/transitions.ts`) from Call Sites:** [appendices/B-missing-snapshot-boundaries.md](appendices/B-missing-snapshot-boundaries.md)
- **Appendix C — Mini-Harness Blueprint: Building a 500-Line Working Toy Clone Using the Patterns in This Book:** [appendices/C-mini-harness-blueprint.md](appendices/C-mini-harness-blueprint.md)


---

<!-- chapters/00-how-to-read-a-1900-file-agent.md — https://reverseengineeringclaudecode.com/chapters/00-how-to-read-a-1900-file-agent -->

# Chapter 00 — How to Read a 1,900-File Agent

> **Layer:** Prologue (Orientation)
> **Prerequisites:** None
> **Primary Source Files:**
> - `entrypoints/cli.tsx` — zero-import CLI bootstrapper
> - `main.tsx` — full CLI wiring and dispatch (~804 KB)
> - `screens/REPL.tsx` — interactive terminal conversation UI (~896 KB)
> - `docs/REPO_AUDIT.md` — existing source-tree audit index

---

## Why Reading Top-Down Fails

When most engineers open an unfamiliar CLI repository, they reach straight for `main.tsx`.

In Claude Code, opening `main.tsx` first is the fastest way to get lost. At over 800 KB, `main.tsx` sits at the very *top* of the dependency pyramid: it imports startup profilers, telemetry, OAuth, remote managed settings, migrations, MCP servers, plugins, skills, permission policies, structured I/O, Ink renderers, and the REPL launcher all at once. Reading `main.tsx` before understanding the primitives underneath is like trying to learn how an internal combustion engine works by staring at a fully assembled Formula 1 car from the outside.

This book takes the exact opposite route: **bottom-up assembly**. We will start at the zero-dependency leaves—files that are 8, 34, 44, and 88 lines long—and stack one layer onto the next until `main.tsx` and `screens/REPL.tsx` read like straightforward wiring diagrams.

Before we touch Layer 0, however, let's get a quick satellite view of the repository and learn the **five codebase idioms** you will see in almost every file you open.

---

## 1. The Lay of the Land: Where the 1,910 Files Live

This checkout contains **1,910 tracked files**, of which **1,884 are `.ts` and `.tsx` source files**. Roughly 85% of the codebase lives in just seven directories:

| Directory | Files | What Lives Here |
| --- | ---: | --- |
| `utils/` | 564 | Shared infrastructure, permissions, hooks, plugins, settings, swarm, messages, shell, git, telemetry |
| `components/` | 389 | Reusable React/Ink terminal UI views, message renderers, permission prompts, dialogs, design system |
| `commands/` | 207 | Built-in slash commands (`/compact`, `/resume`, `/model`, `/mcp`, `/plugin`, `/permissions`, etc.) |
| `tools/` | 184 | Model-callable tools (`BashTool`, `FileReadTool`, `FileEditTool`, `GlobTool`, `GrepTool`, `AgentTool`, etc.) |
| `services/` | 130 | Domain services: Anthropic API client (`api/`), compaction (`compact/`), MCP (`mcp/`), LSP (`lsp/`), analytics, memory |
| `hooks/` | 104 | React hooks bridging terminal input, permissions, tasks, IDE, voice, and live settings into components |
| `ink/` | 96 | A full repository-local React terminal renderer (custom DOM, reconciler, Yoga layout, screen diffing, ANSI/mouse/focus) |

The remaining ~200 files form the **architectural spine** of the application—and they are remarkably compact:

- **Root orchestrators & contracts:** `Tool.ts`, `tools.ts`, `Task.ts`, `tasks.ts`, `commands.ts`, `context.ts`, `query.ts`, `QueryEngine.ts`, `setup.ts`, `replLauncher.tsx`, `cost-tracker.ts`, `main.tsx`
- **Focused subsystems:** `bootstrap/` (1), `state/` (6), `query/` (4), `types/` (11), `entrypoints/` (8), `cli/` (19), `tasks/` (12), `memdir/` (8), `skills/` (20), `keybindings/` (14), `vim/` (5), `bridge/` (31), `remote/` (4), `server/` (3), `screens/` (3)

> [!TIP]
> Notice the asymmetry: **surface area** (hundreds of UI components, slash commands, and utilities) is huge, while the **architectural core** (`Tool.ts`, `state/store.ts`, `query.ts`, `QueryEngine.ts`, `services/tools/*`, `Task.ts`) is only a couple dozen files. Master that core and the rest of the 1,884 files snap into obvious drawers.

---

## 2. Five Recurring Idioms You Will See Everywhere

Open almost any file in this repo and you will immediately notice five patterns that look unusual if you haven't seen them explained before. Learning them right now will save you hours of confusion.

### Idiom 1: Build-Time Dead-Code Elimination with `feature('...')`

You will see `import { feature } from 'bun:bundle'` at the top of dozens of files, paired with inline ternaries and `require(...)` calls like this one in `tools.ts:25-28`:

```ts
const SleepTool =
  feature('PROACTIVE') || feature('KAIROS')
    ? require('./tools/SleepTool/SleepTool.js').SleepTool
    : null
```

And comments like:

```ts
// Intentionally excludes feature() gates — those are tree-shaking boundaries
// and must stay inline at the guarded blocks for dead-code elimination.
```

*(from `query/config.ts:13-14`)*

**Why it looks like this:** Claude Code ships multiple build flavors from a single TypeScript tree (including internal Anthropic builds identified by `process.env.USER_TYPE === 'ant'` and external customer builds). Bun's bundler evaluates `feature('FLAG')` at **compile time**. When a flag is off, the entire false branch—including its `require(...)` target and all transitive strings/imports—is completely tree-shaken out of the output binary. That is why you see `require()` inside ternaries instead of static top-level ES `import` statements, and why `feature()` checks are never wrapped in a helper function.

### Idiom 2: ESM `.js` Specifiers + `src/` Path Aliases

Even though every source file is `.ts` or `.tsx`, local imports use `.js` extensions (`import { createStore } from './store.js'`) and occasionally use a `src/` root alias (`import { logEvent } from 'src/services/analytics/index.js'`). This is standard TypeScript ESM resolution combined with a bundler/tsconfig alias from the upstream build environment.

### Idiom 3: Startup-Deferred Work (`lazySchema`, Lazy `require`, Dynamic `import()`)

A CLI tool that takes 800 ms just to print `--version` feels broken. Throughout the codebase, module evaluation time is treated as a first-class performance budget:

- `entrypoints/cli.tsx` intercepts `--version` with **zero imports** before touching `main.tsx`.
- `utils/lazySchema.ts` wraps Zod schemas in memoized thunks behind JS getters (`get inputSchema()`) so 60+ tool schemas are never constructed at import time.
- Heavy optional subsystems (OpenTelemetry ~400 KB, gRPC ~700 KB, `App.tsx`/`REPL.tsx`, MCP servers, `local-jsx` slash commands) load behind dynamic `await import(...)`.
- Some `require()` calls are wrapped in thunks specifically to break circular dependencies—for example, `tools.ts:63-71` wraps `TeamCreateTool`, `TeamDeleteTool`, and `SendMessageTool` in `getTeamCreateTool()` / `getSendMessageTool()` because team tools transitively import `tools.ts`.

### Idiom 4: React Compiler Output in `.tsx` Files

If you open `state/AppState.tsx` or `replLauncher.tsx`, you will see lines like:

```ts
import { c as _c } from "react/compiler-runtime";
export function AppStateProvider(t0) {
  const $ = _c(13);
  ...
```

And at the very bottom of the file, a long `//# sourceMappingURL=data:application/json;charset=utf-8;base64,...` comment.

**What you are looking at:** The `.tsx` files in this snapshot were captured **after React Compiler transformation** (automatic fine-grained memoization via `_c(slotCount)`). Even better: the base64 inline source map at the bottom of each `.tsx` file embeds `sourcesContent`—the original, uncompiled TSX source code! When studying `.tsx` files, focus on the semantic React hooks and data flow rather than the generated `$[0]` cache-slot boilerplate.

### Idiom 5: Snapshot Completeness Boundaries

Because this repository is a source snapshot of **Claude Code 2.1.88** (dated against the changelog; see the [Introduction](../README.md#repository-snapshot-caveats)) rather than the complete upstream monorepo, keep two factual boundaries in mind:

1. **No build/test harness is checked in:** There is no `package.json`, `tsconfig.json`, or test config in the tracked tree. We treat this repo as a read-only specimen to dissect, verify by reading source and running `rg`, and learn from.
2. **A handful of imported modules are absent from the snapshot:** Notably:
   - `types/message.ts` (widely imported for `Message`, `UserMessage`, `AssistantMessage`, `SystemMessage`, `AttachmentMessage`, `ProgressMessage`, `StreamEvent`, `TombstoneMessage`, etc.—whose exact shapes can still be observed through every constructor in `utils/messages.ts`)
   - `query/transitions.ts` (imported by `query.ts` for `Terminal` and `Continue`, whose exact discriminated union variants are directly visible at every `return { reason: ... }` and `transition: { reason: ... }` site in `query.ts`)
   - Feature-gated `services/contextCollapse/` and `services/skillSearch/` (guarded behind `feature('CONTEXT_COLLAPSE')` and `feature('EXPERIMENTAL_SKILL_SEARCH')`).

Whenever a chapter crosses one of these boundaries, it will tell you explicitly what is verified directly in source and what is absent.

---

## 3. How We Will Build Up the Codebase

Instead of wandering directory by directory, we will assemble the machine in strict dependency order:

1. **Part I (Chapters 1–3):** Atoms (`types/ids.ts`, `state/store.ts`, `bootstrap/state.ts`, `lazySchema`, `generators`, `FileStateCache`) → `Tool` contract → `Command` & `Message` contracts.
2. **Part II (Chapters 4–8):** Prompt construction & cache boundaries → Anthropic streaming API client → tool execution & `StreamingToolExecutor` → the `query.ts` turn state machine → the `QueryEngine.ts` session envelope.
3. **Part III (Chapters 9–10):** Five-stage context compaction and multi-tier memory (`CLAUDE.md`, `memdir/`, `SessionMemory`, `autoDream`).
4. **Part IV (Chapters 11–14):** Permission modes/rules/classifiers, shell/sandbox execution, lifecycle hooks, and settings/policy precedence.
5. **Part V (Chapters 15–16):** Dynamic extensions—MCP, `ToolSearch`, skills, plugins, output styles, and LSP.
6. **Part VI (Chapters 17–19):** Background tasks (`Task.ts`), subagents/forking/worktrees, and multi-agent swarms.
7. **Part VII (Chapters 20–21):** The custom `ink/` React terminal renderer and the interactive `REPL.tsx` UI.
8. **Part VIII (Chapters 22–24):** Finally, `entrypoints/cli.tsx` → `init.ts` → `main.tsx`, headless/SDK structured I/O, and remote bridges.

---

## Reading Checkpoints

Before moving to Chapter 1, run these two read-only inspections in the repo root to see the idioms live:

1. **See the zero-import fast paths in `entrypoints/cli.tsx`:**
   Read lines 1–60 of [`entrypoints/cli.tsx`](../../entrypoints/cli.tsx) and notice how `CLAUDE_CODE_ABLATION_BASELINE` sets env vars *before* dynamic imports so module-level constants in `BashTool`/`AgentTool` see them.
2. **Count compile-time feature gates across the codebase:**
   ```sh
   rg "feature\('" --no-heading | head -n 30
   ```
   Notice how every `feature('...')` sits inline at a branch rather than behind an abstraction.

Now let's drop all the way down to **Layer 0** and examine the six foundational atoms in [Chapter 1](01-atoms-types-stores-and-primitives.md).


---

<!-- chapters/01-atoms-types-stores-and-primitives.md — https://reverseengineeringclaudecode.com/chapters/01-atoms-types-stores-and-primitives -->

# Chapter 01 — The Atoms: Identity, Reactive Stores, Lazy Schemas, and Async Generators

> **Layer:** Layer 0 (Leaf Primitives & Zero-Dependency Foundations)
> **Prerequisites:** [Chapter 00](00-how-to-read-a-1900-file-agent.md)
> **Primary Source Files:**
> - [`types/ids.ts`](../../types/ids.ts) — compile-time branded `SessionId` and `AgentId` (44 lines)
> - [`state/store.ts`](../../state/store.ts) — minimal reactive store (34 lines)
> - [`state/AppStateStore.ts`](../../state/AppStateStore.ts) & [`state/AppState.tsx`](../../state/AppState.tsx) — immutable session state and `useSyncExternalStore` bindings
> - [`bootstrap/state.ts`](../../bootstrap/state.ts) — process-wide leaf singleton
> - [`utils/lazySchema.ts`](../../utils/lazySchema.ts) — deferred Zod schema factory (8 lines)
> - [`utils/generators.ts`](../../utils/generators.ts) — bounded concurrent async-generator multiplexer (88 lines)
> - [`utils/fileStateCache.ts`](../../utils/fileStateCache.ts) — path-normalizing, byte-bounded LRU file cache (142 lines)

---

## Why This Layer Exists

Before an agentic coding tool can prompt an LLM, execute a shell command, or draw a single pixel to a terminal, it needs six low-level guarantees:

1. **Unambiguous identity** — never accidentally pass a subagent ID where a session ID is expected.
2. **Reactive session state without re-render storms** — hundreds of UI components and non-React services must read and update shared state cleanly.
3. **Process-wide state without circular imports** — deep leaf utilities need the current working directory, session ID, and cost counters without importing React or high-level orchestrators.
4. **Zero-cost cold-start declarations** — defining 60+ tool schemas must not burn CPU when the process boots.
5. **Bounded streaming concurrency** — running multiple read-only tools at once must stream progress incrementally while respecting a concurrency cap.
6. **Bounded file awareness** — remembering what files the model has read so edits don't clobber unseen changes, without leaking gigabytes of RAM.

Remarkably, the codebase solves all six with small, crisp, self-contained primitives at the bottom of the import graph. Let's dissect each one.

Four of those primitives are short enough to read whole. Browse them here, then follow the sections below:

`types/ids.ts` (whole file, Claude Code 2.1.88)

````ts
/**
 * Branded types for session and agent IDs.
 * These prevent accidentally mixing up session IDs and agent IDs at compile time.
 */

/**
 * A session ID uniquely identifies a Claude Code session.
 * Returned by getSessionId().
 */
export type SessionId = string & { readonly __brand: 'SessionId' }

/**
 * An agent ID uniquely identifies a subagent within a session.
 * Returned by createAgentId().
 * When present, indicates the context is a subagent (not the main session).
 */
export type AgentId = string & { readonly __brand: 'AgentId' }

/**
 * Cast a raw string to SessionId.
 * Use sparingly - prefer getSessionId() when possible.
 */
export function asSessionId(id: string): SessionId {
  return id as SessionId
}

/**
 * Cast a raw string to AgentId.
 * Use sparingly - prefer createAgentId() when possible.
 */
export function asAgentId(id: string): AgentId {
  return id as AgentId
}

const AGENT_ID_PATTERN = /^a(?:.+-)?[0-9a-f]{16}$/

/**
 * Validate and brand a string as AgentId.
 * Matches the format produced by createAgentId(): `a` + optional `<label>-` + 16 hex chars.
 * Returns null if the string doesn't match (e.g. teammate names, team-addressing).
 */
export function toAgentId(s: string): AgentId | null {
  return AGENT_ID_PATTERN.test(s) ? (s as AgentId) : null
}
````

`state/store.ts` (whole file, Claude Code 2.1.88)

````ts
type Listener = () => void
type OnChange<T> = (args: { newState: T; oldState: T }) => void

export type Store<T> = {
  getState: () => T
  setState: (updater: (prev: T) => T) => void
  subscribe: (listener: Listener) => () => void
}

export function createStore<T>(
  initialState: T,
  onChange?: OnChange<T>,
): Store<T> {
  let state = initialState
  const listeners = new Set<Listener>()

  return {
    getState: () => state,

    setState: (updater: (prev: T) => T) => {
      const prev = state
      const next = updater(prev)
      if (Object.is(next, prev)) return
      state = next
      onChange?.({ newState: next, oldState: prev })
      for (const listener of listeners) listener()
    },

    subscribe: (listener: Listener) => {
      listeners.add(listener)
      return () => listeners.delete(listener)
    },
  }
}
````

`utils/lazySchema.ts` (whole file, Claude Code 2.1.88)

````ts
/**
 * Returns a memoized factory function that constructs the value on first call.
 * Used to defer Zod schema construction from module init time to first access.
 */
export function lazySchema<T>(factory: () => T): () => T {
  let cached: T | undefined
  return () => (cached ??= factory())
}
````

`utils/generators.ts` (whole file, Claude Code 2.1.88)

````ts
const NO_VALUE = Symbol('NO_VALUE')

export async function lastX<A>(as: AsyncGenerator<A>): Promise<A> {
  let lastValue: A | typeof NO_VALUE = NO_VALUE
  for await (const a of as) {
    lastValue = a
  }
  if (lastValue === NO_VALUE) {
    throw new Error('No items in generator')
  }
  return lastValue
}

export async function returnValue<A>(
  as: AsyncGenerator<unknown, A>,
): Promise<A> {
  let e
  do {
    e = await as.next()
  } while (!e.done)
  return e.value
}

type QueuedGenerator<A> = {
  done: boolean | void
  value: A | void
  generator: AsyncGenerator<A, void>
  promise: Promise<QueuedGenerator<A>>
}

// Run all generators concurrently up to a concurrency cap, yielding values as they come in
export async function* all<A>(
  generators: AsyncGenerator<A, void>[],
  concurrencyCap = Infinity,
): AsyncGenerator<A, void> {
  const next = (generator: AsyncGenerator<A, void>) => {
    const promise: Promise<QueuedGenerator<A>> = generator
      .next()
      .then(({ done, value }) => ({
        done,
        value,
        generator,
        promise,
      }))
    return promise
  }
  const waiting = [...generators]
  const promises = new Set<Promise<QueuedGenerator<A>>>()

  // Start initial batch up to concurrency cap
  while (promises.size < concurrencyCap && waiting.length > 0) {
    const gen = waiting.shift()!
    promises.add(next(gen))
  }

  while (promises.size > 0) {
    const { done, value, generator, promise } = await Promise.race(promises)
    promises.delete(promise)

    if (!done) {
      promises.add(next(generator))
      // TODO: Clean this up
      if (value !== undefined) {
        yield value
      }
    } else if (waiting.length > 0) {
      // Start a new generator when one finishes
      const nextGen = waiting.shift()!
      promises.add(next(nextGen))
    }
  }
}

export async function toArray<A>(
  generator: AsyncGenerator<A, void>,
): Promise<A[]> {
  const result: A[] = []
  for await (const a of generator) {
    result.push(a)
  }
  return result
}

export async function* fromArray<T>(values: T[]): AsyncGenerator<T, void> {
  for (const value of values) {
    yield value
  }
}
````

---

## 1. Branded Identity (`types/ids.ts`)

### The Problem

An agent process quickly juggles multiple string identifiers: the top-level conversation's session UUID, subagent IDs, teammate names, and tool-use IDs. In plain TypeScript, all of them are `string`. Passing a `SessionId` to a function that writes a subagent sidechain transcript—or passing an `AgentId` to a session telemetry event—compiles silently and corrupts disk state at runtime.

### The Implementation

`types/ids.ts` is 44 lines with **zero imports**. It uses TypeScript structural branding (`string & { readonly __brand: ... }`) to make `SessionId` and `AgentId` mutually incompatible at compile time while costing zero bytes at runtime:

```ts
// types/ids.ts:10-17
export type SessionId = string & { readonly __brand: 'SessionId' }
export type AgentId = string & { readonly __brand: 'AgentId' }
```

Even better, `toAgentId()` acts as a runtime parsing boundary between arbitrary user/team strings and genuine agent IDs:

```ts
// types/ids.ts:35-44
const AGENT_ID_PATTERN = /^a(?:.+-)?[0-9a-f]{16}$/

export function toAgentId(s: string): AgentId | null {
  return AGENT_ID_PATTERN.test(s) ? (s as AgentId) : null
}
```

### Why This Matters Upward

Look at `Tool.ts:245`:
```ts
agentId?: AgentId // Only set for subagents; use getSessionId() for session ID.
```
And look at `bootstrap/state.ts:178`: invoked skills are keyed by `${agentId ?? ''}:${skillName}` so a subagent invoking a skill never overwrites the main thread's record. Because `AgentId` is distinct from `SessionId` at the type level, hooks, transcript storage, and telemetry cannot confuse main-thread calls with subagent calls.

---

## 2. The 34-Line Reactive Store (`state/store.ts` → `state/AppState.tsx`)

### The Problem

Claude Code has two very different consumers of session state:
- **React/Ink terminal components** (389 files under `components/` and `screens/`), which must re-render *only* when the exact slice of state they display changes—otherwise every spinner tick or token chunk would re-render the whole terminal screen.
- **Non-React imperative code** (`query.ts`, `Tool.call()`, `QueryEngine.ts`, background tasks, settings file watchers), which needs synchronous `getState()` / `setState(prev => next)` access outside the React tree.

### The Implementation

Instead of pulling in Redux or a large external state framework, `state/store.ts` builds the entire reactive primitive in **34 lines**:

```ts
// state/store.ts:1-34
type Listener = () => void
type OnChange<T> = (args: { newState: T; oldState: T }) => void

export type Store<T> = {
  getState: () => T
  setState: (updater: (prev: T) => T) => void
  subscribe: (listener: Listener) => () => void
}

export function createStore<T>(
  initialState: T,
  onChange?: OnChange<T>,
): Store<T> {
  let state = initialState
  const listeners = new Set<Listener>()

  return {
    getState: () => state,

    setState: (updater: (prev: T) => T) => {
      const prev = state
      const next = updater(prev)
      if (Object.is(next, prev)) return
      state = next
      onChange?.({ newState: next, oldState: prev })
      for (const listener of listeners) listener()
    },

    subscribe: (listener: Listener) => {
      listeners.add(listener)
      return () => listeners.delete(listener)
    },
  }
}
```

Pause and admire four quiet design choices in those 34 lines:

1. **Functional updaters only (`updater: (prev: T) => T`).** Callers cannot pass a raw partial object that silently clobbers concurrent updates; every write computes from the latest `prev`.
2. **Exact `Object.is(next, prev)` bailout.** If an updater returns `prev` unchanged, neither `onChange` nor any subscriber fires.
3. **Synchronous `onChange({ newState, oldState })` side-effect hook.** Runs *before* React subscribers—used by `state/onChangeAppState.ts` to react to cross-cutting transitions (like mode changes or notifications) regardless of what is mounted.
4. **Zero React dependency.** Headless SDK mode (`QueryEngine.ts`) and tests can instantiate `createStore(getDefaultAppState())` without ever importing React or Ink!

### Bridging to React (`state/AppState.tsx`)

When the interactive terminal UI *does* mount, `AppStateProvider` creates the store **once** in `useState(() => createStore(...))` and puts the stable `store` object (never the `state` value!) into `AppStoreContext`. Because the context value never changes, the provider never forces cascading re-renders.

Components read slices through `useAppState(selector)`, which plugs directly into React 18+'s `useSyncExternalStore`:

```ts
// From state/AppState.tsx (original source)
export function useAppState<T>(selector: (state: AppState) => T): T {
  const store = useAppStore()
  const get = () => {
    const state = store.getState()
    const selected = selector(state)
    // In internal ('ant') builds, throws if a selector returns the entire state!
    return selected
  }
  return useSyncExternalStore(store.subscribe, get, get)
}
```

And components that only *write* state call `useSetAppState()`, which returns `store.setState`—a reference that never changes, guaranteeing zero re-renders.

> [!IMPORTANT]
> **Notice the architectural split between `AppStateStore.ts` and `AppState.tsx`:**
> Look at the comment in `state/AppState.tsx:23-25`:
> *"Kept for back-compat during migration so `.ts` callers can incrementally move off the `.tsx` import and stop pulling React."*
> Keeping the `AppState` type and `getDefaultAppState()` in a pure `.ts` file (`state/AppStateStore.ts`) prevents headless code paths from accidentally bundling React.

---

## 3. The Process-Wide Leaf Singleton (`bootstrap/state.ts`)

### The Problem

Wait—if `AppState` already exists, why does `bootstrap/state.ts` exist too?

Because **process lifetime ≠ React/session lifetime**, and **import graphs hate cycles**.

Think about everything that happens *before* `AppState` is even created—or deep inside a utility that doesn't receive a `ToolUseContext`:
- What was `originalCwd` at launch, and what is the stable `projectRoot` (which must NOT change if the agent enters a Git worktree mid-session)?
- What is the active `sessionId`?
- How much USD (`totalCostUSD`), API latency (`totalAPIDuration`), and tokens (`modelUsage`) has this process spent across turns and subagents?
- What hooks were registered by SDK callbacks or plugins (`registeredHooks`)?
- Which skills have been invoked so compaction can preserve them (`invokedSkills`)?

If a low-level logger or permission helper imported `AppState` or `QueryEngine`, the module graph would knot into circular dependencies immediately.

### The Solution: A Strictly Isolated Leaf

`bootstrap/state.ts` holds a single private `State` object exposed via focused getter/setter functions—and is protected by a custom lint rule (`custom-rules/bootstrap-isolation`) to keep it a **leaf of the import DAG**.

Look at the real scars visible right in `bootstrap/state.ts`'s comments:

```ts
// bootstrap/state.ts:46-50
originalCwd: string
// Stable project root - set once at startup (including by --worktree flag),
// never updated by mid-session EnterWorktreeTool.
// Use for project identity (history, skills, sessions) not file operations.
projectRoot: string
```

And look at line 121-123—a textbook example of using a leaf store to break a 4-module import cycle:

```ts
// CLAUDE.md content cached by context.ts for the auto-mode classifier.
// Breaks the yoloClassifier → claudemd → filesystem → permissions cycle.
cachedClaudeMdContent: string | null
```

And line 144-149—why mutable session registries live here instead of scattered module-level variables:

```ts
// Teams created this session via TeamCreate. ...
// Lives here (not teamHelpers.ts) so resetStateForTests() clears it between tests.
sessionCreatedTeams: Set<string>
```

### The Mental Rule: `bootstrap/state.ts` vs. `AppState`

| Dimension | `bootstrap/state.ts` | `AppState` (`state/AppStateStore.ts`) |
| --- | --- | --- |
| **Lifetime** | Process-wide | Session / UI store instance |
| **Mutability** | Mutable singleton fields + getters/setters | `DeepImmutable<...>` replaced via pure updaters |
| **Reactivity** | Non-reactive (imperative reads) | Reactive (`useSyncExternalStore` + `onChange`) |
| **Import position** | Strict leaf of import DAG | Mid-layer (imports tool, task, MCP, plugin types) |
| **Examples** | `sessionId`, `projectRoot`, `totalCostUSD`, `cachedClaudeMdContent`, `invokedSkills` | `toolPermissionContext`, `tasks`, `mcp`, `plugins`, `mainLoopModel`, `expandedView` |

---

## 4. Deferred Schema Construction (`utils/lazySchema.ts`)

### The Problem

Every tool, permission rule, hook, and setting in Claude Code validates structured data with Zod v4 (`zod/v4`). Constructing dozens of deeply nested Zod schemas eagerly at module import time burns tens of milliseconds on every single CLI invocation—even if the user only ran a quick local command or only used 2 of the 60+ tools.

### The Implementation

The entire file `utils/lazySchema.ts` is **8 lines**:

```ts
// utils/lazySchema.ts:1-8
/**
 * Returns a memoized factory function that constructs the value on first call.
 * Used to defer Zod schema construction from module init time to first access.
 */
export function lazySchema<T>(factory: () => T): () => T {
  let cached: T | undefined
  return () => (cached ??= factory())
}
```

### How It Pairs with JavaScript Getters

On a tool definition (like `tools/GlobTool/GlobTool.ts:26-75`), `lazySchema` is paired with a JS `get` accessor:

```ts
const inputSchema = lazySchema(() =>
  z.strictObject({
    pattern: z.string().describe('...'),
    path: z.string().optional().describe('...'),
  }),
)

export const GlobTool = buildTool({
  ...
  get inputSchema() {
    return inputSchema()
  },
})
```

Notice the subtlety: if you wrote `inputSchema: inputSchema()`, you would evaluate the thunk eagerly when `GlobTool` is defined! Wrapping it inside `get inputSchema()` defers Zod execution until the exact moment the API serializer or validator actually reads `tool.inputSchema`.

> [!WARNING]
> **One subtle invariant of `buildTool` + getters:** Object spread `{ ...TOOL_DEFAULTS, ...def }` invokes enumerable getters on `def` when `buildTool` runs! That is worth checking whenever you optimize cold-start paths: `lazySchema` still guarantees single construction per schema and avoids module-top-level evaluation for standalone schemas like `permissionModeSchema` (`utils/permissions/PermissionMode.ts:21`) that are called as functions `permissionModeSchema()`.

---

## 5. Bounded Async-Generator Multiplexing (`utils/generators.ts`)

### The Problem

Suppose the LLM asks to call 12 read-only tools in parallel (`Read` x8, `Grep` x3, `Glob` x1). Each tool doesn't just return a final `Promise`—it is an `AsyncGenerator` that yields intermediate progress updates (`ProgressMessage`) along the way before yielding its final `tool_result`!

`Promise.all()` cannot solve this:
1. `Promise.all()` waits until *everything* finishes, throwing away incremental progress streaming.
2. `Promise.all()` launches all N tasks simultaneously with no concurrency cap.

### The Implementation

`utils/generators.ts` implements `all()`—an 88-line file whose heart is a 40-line concurrent async-generator multiplexer:

```ts
// utils/generators.ts:32-72
export async function* all<A>(
  generators: AsyncGenerator<A, void>[],
  concurrencyCap = Infinity,
): AsyncGenerator<A, void> {
  const next = (generator: AsyncGenerator<A, void>) => {
    const promise: Promise<QueuedGenerator<A>> = generator
      .next()
      .then(({ done, value }) => ({
        done,
        value,
        generator,
        promise,
      }))
    return promise
  }
  const waiting = [...generators]
  const promises = new Set<Promise<QueuedGenerator<A>>>()

  // Start initial batch up to concurrency cap
  while (promises.size < concurrencyCap && waiting.length > 0) {
    const gen = waiting.shift()!
    promises.add(next(gen))
  }

  while (promises.size > 0) {
    const { done, value, generator, promise } = await Promise.race(promises)
    promises.delete(promise)

    if (!done) {
      promises.add(next(generator))
      if (value !== undefined) {
        yield value
      }
    } else if (waiting.length > 0) {
      // Start a new generator when one finishes
      const nextGen = waiting.shift()!
      promises.add(next(nextGen))
    }
  }
}
```

Trace the trick in `next(generator)`:
- Each in-flight `.next()` promise resolves to an object **containing a reference to itself (`promise`)** plus its `generator`, `done`, and `value`.
- `Promise.race(promises)` wakes up as soon as *any* generator yields a single item or finishes.
- `promises.delete(promise)` removes the settled promise from the active `Set` in O(1).
- If `!done`, it immediately queues the next `.next()` call on the same generator and yields `value` to the caller.
- If `done`, a concurrency slot just opened up—so it shifts the next generator off `waiting` and starts it!

Alongside `all()`, `utils/generators.ts` provides four tiny companions used across the codebase: `lastX` (consume to final yielded value), `returnValue` (drain a generator and extract its `Return` value—crucial because `query()` returns `Terminal`), `toArray`, and `fromArray`.

---

## 6. Bounded File Awareness (`utils/fileStateCache.ts`)

### The Problem

Coding agents fail catastrophically when they edit files blindly:
- If the model tries to edit a file it never read, it hallucinates line contents.
- If the user (or a linter/formatter) modified a file on disk *after* the model read it, the model's patch silently overwrites the user's changes.
- Conversely, if the agent caches every file read forever in an unbounded `Map`, a long session inspecting large logs or generated bundles leaks hundreds of megabytes of RAM.

### The Implementation

`utils/fileStateCache.ts` wraps `LRUCache<string, FileState>` with three critical invariants:

```ts
// utils/fileStateCache.ts:4-23
export type FileState = {
  content: string
  timestamp: number
  offset: number | undefined
  limit: number | undefined
  // True when this entry was populated by auto-injection (e.g. CLAUDE.md) and
  // the injected content did not match disk (stripped HTML comments, stripped
  // frontmatter, truncated MEMORY.md). The model has only seen a partial view;
  // Edit/Write must require an explicit Read first. `content` here holds the
  // RAW disk bytes (for getChangedFiles diffing), not what the model saw.
  isPartialView?: boolean
}

export const READ_FILE_STATE_CACHE_SIZE = 100
const DEFAULT_MAX_CACHE_SIZE_BYTES = 25 * 1024 * 1024
```

Look closely at the three defenses baked right into `FileStateCache`:

1. **Path normalization on every key (`normalize(key)`):** Every `get`, `set`, `has`, and `delete` normalizes redundant segments (`/foo/../bar`) and Windows slash variants (`\` vs `/`) so the same file can never masquerade under two cache keys.
2. **Dual eviction caps (`max: 100` entries AND `maxSize: 25 MB`):** Size is calculated with `Math.max(1, Buffer.byteLength(value.content))` (the `Math.max(1, ...)` guards against empty 0-byte files violating `lru-cache`'s positive-size requirement!).
3. **`isPartialView` safety flag:** Auto-injected files like `CLAUDE.md` or truncated `MEMORY.md` store raw disk bytes for diff detection, while flagging `isPartialView: true` so `FileEditTool` / `FileWriteTool` refuse to edit until the model executes an explicit `Read`.
4. **Serialization (`dump()` / `load()` / `cloneFileStateCache()`):** Lets subagents clone the parent's read-file cache (`QueryEngine.ts:56`, `createSubagentContext`) and lets compaction serialize recently read files so the agent can re-attach them after summarizing history!

> [!NOTE]
> **Watch the downstream ripple of LRU eviction:** Because `readFileState` is an LRU cache that *can* evict entries in busy sessions, `ToolUseContext` (`Tool.ts:217-222`) maintains a *separate* `loadedNestedMemoryPaths: Set<string>` just for deduplicating `CLAUDE.md` injection—otherwise evicting a `CLAUDE.md` from `readFileState` would cause it to be re-injected dozens of times!

---

## Putting Layer 0 Together

```text
Layer 0 Atoms (Zero High-Level Dependencies)
├── types/ids.ts            --> SessionId, AgentId (compile-time identity)
├── state/store.ts          --> createStore() (34-line reactive store)
├── bootstrap/state.ts      --> process-wide leaf singleton & cycle breaker
├── utils/lazySchema.ts     --> 8-line deferred Zod initializer
├── utils/generators.ts     --> all() bounded async-generator multiplexer
└── utils/fileStateCache.ts --> path-normalized, 25 MB LRU file tracker
```

Notice what we **haven't** needed yet: no Anthropic SDK network calls, no prompts, no tools, no permissions, no React components, no terminal ANSI codes. Every single atom above is small enough to hold in your head in one sitting.

---

## How This Snaps Into the Next Layer

Every single Layer 0 atom plugs directly into **Layer 1 (`Tool.ts`, `tools.ts`)**:
- `ToolUseContext` carries `readFileState: FileStateCache`, `agentId?: AgentId`, and `getAppState` / `setAppState` wired directly to `createStore()`.
- Individual tools define their Zod schemas through `lazySchema()`.
- `services/tools/toolOrchestration.ts` passes concurrent tool generators straight into `all(..., getMaxToolUseConcurrency())`.

In [Chapter 2: The Tool Contract](02-the-tool-contract.md), we snap these atoms together to define what an agent can actually *do*.

---

## Reading Exercises & Code Checkpoints

1. **Check the `bootstrap-isolation` footprint:**
   Run `rg "bootstrap-isolation" bootstrap/` and inspect why `bootstrap/state.ts` has a special comment for `randomUUID`.
2. **Trace `Object.is` bailout:**
   Read [`state/selectors.ts`](../../state/selectors.ts) and [`state/onChangeAppState.ts`](../../state/onChangeAppState.ts) to see how selectors and state-change listeners hook into `createStore()`.
3. **Inspect `cloneFileStateCache`:**
   Read lines 120–142 of [`utils/fileStateCache.ts`](../../utils/fileStateCache.ts) and trace how `QueryEngine.ts` and `AgentTool` isolate file caches across agents.


---

<!-- chapters/02-the-tool-contract.md — https://reverseengineeringclaudecode.com/chapters/02-the-tool-contract -->

# Chapter 02 — The Tool Contract: Defining What an Agent Can Do

> **Layer:** Layer 1 (Core Capability Contracts)
> **Prerequisites:** [Chapter 01](01-atoms-types-stores-and-primitives.md)
> **Primary Source Files:**
> - [`Tool.ts`](../../Tool.ts) — `Tool`, `ToolDef`, `buildTool()`, `ToolUseContext`, `ToolPermissionContext`, `ToolResult` (792 lines)
> - [`tools/GlobTool/GlobTool.ts`](../../tools/GlobTool/GlobTool.ts) — clean, complete real-world tool implementation (198 lines)
> - [`tools.ts`](../../tools.ts) — tool catalog, DCE conditional loading, deny-rule pre-filtering, and prompt-cache-aware sorting (389 lines)

---

## Why This Layer Exists

An LLM by itself can only predict text. What turns a language model into a coding *agent* is a **tool contract**—a uniform interface that lets the runtime:

1. Advertise a tool's name, prompt instructions, and JSON Schema to the model.
2. Validate malformed model arguments *before* bothering the user with a permission prompt.
3. Decide whether two tool calls can safely run in parallel or must execute serially.
4. Enforce permissions, hooks, sandboxing, and security classifiers uniformly across built-in and MCP tools.
5. Stream progress and render rich terminal UI *without* polluting what gets sent back to the model.
6. Assemble and order the final tool list without busting the LLM prompt cache.

In Claude Code, every one of those responsibilities converges in a single contract: `Tool<Input, Output, P>` in `Tool.ts`.

---

## 1. The Four Faces of `Tool<Input, Output, P>` (`Tool.ts`)

If you read `Tool` (`Tool.ts:362-695`) from top to bottom, its ~35 properties and methods fall cleanly into **four orthogonal faces**:

```text
                       Tool<Input, Output, P>
    ┌──────────────────────┬───────────────────────┐
    │ 1. IDENTITY & SCHEMA │ 2. SAFETY & SCHEDULE  │
    │  name, aliases       │  isConcurrencySafe()  │
    │  inputSchema (Zod)   │  isReadOnly()         │
    │  inputJSONSchema     │  isDestructive()      │
    │  outputSchema        │  interruptBehavior()  │
    │  prompt(), searchHint│  isEnabled()          │
    │  shouldDefer         │  maxResultSizeChars   │
    ├──────────────────────┼───────────────────────┤
    │ 3. LIFECYCLE & EXEC  │ 4. UI & PROJECTION    │
    │  validateInput()     │  userFacingName()     │
    │  checkPermissions()  │  renderToolUseMessage │
    │  preparePermission-  │  renderToolResult...  │
    │    Matcher()         │  renderToolUseProgress│
    │  toAutoClassifier-   │  renderGroupedToolUse │
    │    Input()           │  extractSearchText()  │
    │  call() -> ToolResult│  mapToolResultToTool- │
    │                      │    ResultBlockParam() │
    └──────────────────────┴───────────────────────┘
```

Let's examine the subtle, high-leverage design choices hidden inside each face:

### Face 1: Identity, Schema, and Deferred Loading
- **`aliases?: string[]` & `findToolByName()` (`Tool.ts:348-360`):** Lets tools be renamed without breaking older transcripts or prompts.
- **`inputSchema` vs. `inputJSONSchema`:** Built-in tools define Zod v4 schemas (`inputSchema`); MCP tools pass raw JSON Schema directly via `inputJSONSchema` without round-tripping through Zod.
- **`shouldDefer` / `alwaysLoad` / `searchHint` (`Tool.ts:378, 442-449`):** When dozens of MCP servers are connected, dumping every tool schema into turn 1 wastes tens of thousands of tokens. Deferred tools are sent with `defer_loading: true` and discovered on demand by `ToolSearchTool` using `searchHint` (a 3–10 word keyword phrase). Tools marked `alwaysLoad: true` bypass deferral so the model always sees them on turn 1.
- **`maxResultSizeChars` (`Tool.ts:466`):** Controls when `utils/toolResultStorage.ts` spills a huge tool output to disk as `<persisted-output>`. Crucially, `FileReadTool` sets this to `Infinity`: persisting `Read`'s output to a file that the model must `Read` back would create an infinite Read→file→Read loop!

### Face 2: Safety & Concurrency Metadata
- **`isConcurrencySafe(input)` and `isReadOnly(input)` take `input`!**
  Why aren't these static booleans? Because `BashTool` depends on the command! `git status` or `ls -la` can be classified as read-only/concurrency-safe, whereas `rm -rf` or `npm install` is neither. Passing parsed `input` makes scheduling and permissions *input-sensitive*.
- **`interruptBehavior?(): 'cancel' | 'block'` (`Tool.ts:416`):** Declares what happens if the user submits a new message while this tool is mid-flight—either cancel and discard, or block the new message until the tool finishes (default: `'block'`).

### Face 3: The Execution & Validation Lifecycle
Notice the strict ordering documented right in `Tool.ts:483-503`:
1. **`backfillObservableInput?(input)`** — Runs on a *copy* of `tool_use` input before observers (SDK, hooks, transcripts) see it; the original API-bound input is never mutated so the prompt cache stays intact!
2. **`validateInput?(input, context)`** — Runs *before* permission prompts. Returns `{ result: true }` or `{ result: false, message, errorCode }` so invalid paths or bad arguments bounce straight back to the model without nagging the human.
3. **`checkPermissions(input, context)`** — Tool-specific permission logic (e.g., filesystem path rules for `GlobTool`, AST command rules for `BashTool`), layered with the general permission engine in `utils/permissions/permissions.ts`.
4. **`call(args, context, canUseTool, parentMessage, onProgress)`** — Executes the tool and returns `Promise<ToolResult<Output>>`.

Look at `ToolResult<T>` (`Tool.ts:321-336`):
```ts
export type ToolResult<T> = {
  data: T
  newMessages?: (UserMessage | AssistantMessage | AttachmentMessage | SystemMessage)[]
  // contextModifier is only honored for tools that aren't concurrency safe.
  contextModifier?: (context: ToolUseContext) => ToolUseContext
  mcpMeta?: {
    _meta?: Record<string, unknown>
    structuredContent?: Record<string, unknown>
  }
}
```
Notice `contextModifier`: a tool can return a pure function `(context) => nextContext` to update `ToolUseContext` for subsequent tools in the turn (for example, mutating session flags or caches), and the orchestrator controls *when* modifiers apply so concurrent tools never race on context mutation!

### Face 4: Separating Model Serialization from Human UI
A tool never returns a raw string directly to both the LLM and the screen. Instead, `call()` returns typed `data: Output`, and **three separate projections** read that `Output`:
1. **`mapToolResultToToolResultBlockParam(output, toolUseID)`** → Produces the Anthropic API `ToolResultBlockParam` the model sees.
2. **`renderToolResultMessage(output, progress, options)`** → Produces the React/Ink terminal UI the human sees (with `renderToolUseMessage` accepting `Partial<Input>` so the UI can render *while the JSON arguments are still streaming in*!).
3. **`extractSearchText?(output)`** → Flattens the *exact text visible in transcript mode* (excluding `<system-reminder>` wrappers and chrome like `"Found 3 files in 12ms"`) so in-terminal transcript search counts match highlighted screen cells 1-to-1 (`Tool.ts:582-599`).

---

## 2. Fail-Closed Defaults: `buildTool()` (`Tool.ts:703-792`)

### The Problem

With 60+ tools in `tools/`, making every tool implement boilerplate stubs like `isDestructive: () => false` or `isConcurrencySafe: () => false` causes two failures: repetitive noise, and worse, an engineer forgetting a safety check or callers littering the engine with `tool.isConcurrencySafe?.(input) ?? false`.

### The Implementation

Every tool is constructed through `buildTool(def)` (`Tool.ts:757-792`), which spreads a fail-closed `TOOL_DEFAULTS` object underneath the tool's definition:

```ts
// Tool.ts:757-792
const TOOL_DEFAULTS = {
  isEnabled: () => true,
  isConcurrencySafe: (_input?: unknown) => false,
  isReadOnly: (_input?: unknown) => false,
  isDestructive: (_input?: unknown) => false,
  checkPermissions: (
    input: { [key: string]: unknown },
    _ctx?: ToolUseContext,
  ): Promise<PermissionResult> =>
    Promise.resolve({ behavior: 'allow', updatedInput: input }),
  toAutoClassifierInput: (_input?: unknown) => '',
  userFacingName: (_input?: unknown) => '',
}

export function buildTool<D extends AnyToolDef>(def: D): BuiltTool<D> {
  return {
    ...TOOL_DEFAULTS,
    userFacingName: () => def.name,
    ...def,
  } as BuiltTool<D>
}
```

Look closely at the **fail-closed defaults**:
- `isConcurrencySafe` defaults to **`false`** — a new tool runs serially until explicitly audited and marked safe.
- `isReadOnly` defaults to **`false`** — assume a tool mutates state unless proven otherwise.
- `checkPermissions` returns `{ behavior: 'allow', updatedInput: input }`, which does *not* bypass security—it defers to the general permission engine (`permissions.ts`), where modes, deny rules, ask rules, and classifiers still apply.
- At the TypeScript level, `BuiltTool<D>` (`Tool.ts:735-741`) mirrors the runtime `{ ...TOOL_DEFAULTS, ...def }` spread so callers retain each tool's exact literal `name`, `Input`, and `Output` types with zero `?.()` optional checks needed at runtime.

---

## 3. The Capability Bag: `ToolUseContext` & `ToolPermissionContext`

Every tool's `call()` and `checkPermissions()` receives a `ToolUseContext` (`Tool.ts:158-300`). Reading its fields is like looking at an X-ray of the entire agent runtime—every Layer 0 atom we studied in Chapter 1 shows up here:

- **Static turn options (`options`):** `tools`, `commands`, `mainLoopModel`, `thinkingConfig`, `mcpClients`, `mcpResources`, `agentDefinitions`, `isNonInteractiveSession`, `refreshTools`.
- **Execution & cancellation:** `abortController`, `messages`, `queryTracking: { chainId, depth }`, `toolUseId`.
- **State bridges (from Chapter 1):**
  - `readFileState: FileStateCache`
  - `getAppState()` / `setAppState()`
  - **`setAppStateForTasks?` (`Tool.ts:184-192`)** — A classic production scar! For async background subagents, `setAppState` is replaced with a **no-op** so a subagent cannot clobber the main UI. Yet background subagents still need to register or clean up session-wide background tasks and hooks. `setAppStateForTasks` punches a narrow, intentional channel straight through to the root store.
  - **`localDenialTracking?` (`Tool.ts:279-283`)** — Same root cause! Because an async subagent's `setAppState` is a no-op, denial counts written via `setAppState` would never accumulate; `localDenialTracking` gives the subagent a mutable local counter so fallback-to-prompting still triggers.
- **Prompt-cache & budget state:**
  - `contentReplacementState?: ContentReplacementState` — tracks which tool outputs were spilled to disk so forked subagents make identical replacement decisions.
  - `renderedSystemPrompt?: SystemPrompt` — freezes the parent's rendered system prompt bytes at turn start so forked subagents share the parent's prompt cache instead of re-evaluating GrowthBook flags and busting it.
- **UI & notification hooks (optional—undefined in headless SDK mode!):**
  `setToolJSX`, `addNotification`, `appendSystemMessage`, `sendOSNotification`, `requestPrompt`, `setStreamMode`, `setHasInterruptibleToolInProgress`.

Alongside it sits `ToolPermissionContext` (`Tool.ts:123-138`), wrapped in `DeepImmutable<...>`:
- `mode: PermissionMode` (`default`, `plan`, `acceptEdits`, `bypassPermissions`, `dontAsk`, or internal `auto`/`bubble`)
- `additionalWorkingDirectories: Map<string, AdditionalWorkingDirectory>`
- `alwaysAllowRules`, `alwaysDenyRules`, `alwaysAskRules` (indexed by `PermissionRuleSource`)
- `shouldAvoidPermissionPrompts` (auto-deny prompts for headless background agents) and `prePlanMode` (remembers which mode to restore when exiting Plan Mode).

---

## 4. Concrete Walkthrough: `tools/GlobTool/GlobTool.ts`

Abstract interfaces come alive when you read a real 198-line tool end to end. `GlobTool` is one of the cleanest tools in the repo, and it exercises nearly every concept in this chapter:

1. **Lazy Zod schemas behind getters (`GlobTool.ts:26-75`):**
   Both `inputSchema` (`z.strictObject({ pattern, path? })`) and `outputSchema` (`{ durationMs, numFiles, filenames, truncated }`) are wrapped in `lazySchema(...)` and exposed via `get inputSchema()` / `get outputSchema()`.
2. **Explicit opt-in to concurrency & read-only (`GlobTool.ts:76-87`):**
   Overrides `buildTool`'s fail-closed defaults with `isConcurrencySafe() { return true }`, `isReadOnly() { return true }`, and `isSearchOrReadCommand() { return { isSearch: true, isRead: false } }` (allowing the UI to collapse consecutive search calls).
3. **Result size cap (`GlobTool.ts:60`):**
   `maxResultSizeChars: 100_000` bounds inline output before `toolResultStorage.ts` spills it to disk.
4. **Defensive pre-permission validation (`GlobTool.ts:94-134`):**
   Look at lines 100–103 inside `validateInput`:
   ```ts
   // SECURITY: Skip filesystem operations for UNC paths to prevent NTLM credential leaks.
   if (absolutePath.startsWith('\\\\') || absolutePath.startsWith('//')) {
     return { result: true }
   }
   ```
   On Windows, calling `fs.stat('//attacker/share')` triggers an outbound SMB handshake that leaks NTLM hashes *before the user has even been asked for permission*. Skipping `fs.stat` on UNC paths in `validateInput` pushes the decision safely into `checkPermissions`! For normal local paths, `validateInput` verifies the directory exists and even suggests a corrected path under `cwd` (`suggestPathUnderCwd`) when `ENOENT` occurs—giving the model actionable self-correction feedback without a permission prompt.
5. **Tool-specific permission check (`GlobTool.ts:135-142`):**
   Delegates to `checkReadPermissionForTool(GlobTool, input, appState.toolPermissionContext)`.
6. **Execution & token-saving relativization (`GlobTool.ts:154-176`):**
   Runs `glob(...)` with `abortController.signal` and `limit = globLimits?.maxResults ?? 100`, then maps results through `toRelativePath` specifically to save model tokens.
7. **Dual projection (`GlobTool.ts:151-153, 177-197`):**
   - `extractSearchText` returns `filenames.join('\n')` (matching the rendered list).
   - `mapToolResultToToolResultBlockParam` emits `'No files found'` when empty, or newline-joined paths plus a truncation hint for the LLM.

---

## 5. Assembling the Tool Catalog (`tools.ts`)

Having 60+ `Tool` objects on disk is only half the story. Before any turn begins, `tools.ts` decides *which* tools exist in this build, *which* are permitted right now, and *in what exact order* they are handed to the API.

### Step 1: Build-Time Filtering & Cycle Breaking (`tools.ts:16-156, 193-251`)
`getAllBaseTools()` builds the master array using three gating mechanisms:
- **Compile-time DCE:** `feature('PROACTIVE')`, `feature('AGENT_TRIGGERS')`, `feature('COORDINATOR_MODE')`, `process.env.USER_TYPE === 'ant'`.
- **Circular-dependency thunks:** `getSendMessageTool()`, `getTeamCreateTool()`, `getTeamDeleteTool()`, and `getPowerShellTool()` use lazy `require()` calls to break `tools.ts → Team*Tool → ... → tools.ts`.
- **Environment adaptation:** On internal native builds with embedded `bfs`/`ugrep` (`hasEmbeddedSearchTools()`), `GlobTool` and `GrepTool` are omitted because the shell's `find`/`grep` are already aliased to fast embedded binaries.

### Step 2: Mode & Blanket-Deny Filtering (`tools.ts:262-327`)
`getTools(permissionContext)` applies runtime filtering:
- **`CLAUDE_CODE_SIMPLE` mode:** Collapses the entire catalog down to just `[BashTool, FileReadTool, FileEditTool]` (plus coordinator tools if active).
- **Blanket deny filtering (`filterToolsByDenyRules`):** Removes any tool (or entire MCP server prefix like `mcp__server`) matched by a blanket deny rule *before the model ever sees the tool schema*—saving tokens and eliminating futile tool calls.
- **`isReplModeEnabled()`:** When the ant-only VM `REPLTool` is active, hides raw primitive tools (`REPL_ONLY_TOOLS`) so the model routes through the VM.
- **`tool.isEnabled()`:** Final runtime enablement filter.

### Step 3: Partitioned Sorting for Prompt-Cache Stability (`tools.ts:345-367`)
Finally, `assembleToolPool(permissionContext, mcpTools)` merges built-in tools and dynamic MCP tools. Read lines 354–366 of `tools.ts` carefully—this is one of the best systems-engineering gems in the entire repository:

```ts
// tools.ts:354-366
// Sort each partition for prompt-cache stability, keeping built-ins as a
// contiguous prefix. The server's claude_code_system_cache_policy places a
// global cache breakpoint after the last prefix-matched built-in tool; a flat
// sort would interleave MCP tools into built-ins and invalidate all downstream
// cache keys whenever an MCP tool sorts between existing built-ins. uniqBy
// preserves insertion order, so built-ins win on name conflict.
const byName = (a: Tool, b: Tool) => a.name.localeCompare(b.name)
return uniqBy(
  [...builtInTools].sort(byName).concat(allowedMcpTools.sort(byName)),
  'name',
)
```

Think about what would happen if you naively ran `[...builtInTools, ...allowedMcpTools].sort(byName)`:
- Connecting a single MCP server whose tool is named `mcp__alpha__query` would insert it *between* `Edit` and `Read`—invalidating the global prompt cache prefix for **every** built-in tool after it and the entire system prompt below it!
- By sorting `[builtInTools]` and `[allowedMcpTools]` as **two separate contiguous partitions**, built-in tools stay byte-identical across users and MCP configurations, AND `uniqBy(..., 'name')` guarantees a malicious or colliding MCP tool can never shadow a built-in tool.

---

## Putting Layer 1 Together

```text
Individual Tool Modules (GlobTool, FileReadTool, BashTool, ...)
   │  wrapped by buildTool() (fail-closed defaults + BuiltTool<D> types)
   ▼
getAllBaseTools()              ── compile-time feature() DCE + lazy cycle requires
   │
   ▼
getTools(permissionContext)    ── CLAUDE_CODE_SIMPLE + filterToolsByDenyRules + isEnabled()
   │
   ▼
assembleToolPool(ctx, mcpTools)── [sorted built-ins] ++ [sorted allowed MCPs] + uniqBy
   │
   ▼
Ready for API serialization (Ch 4-5) & Tool Execution / StreamingToolExecutor (Ch 6)
```

---

## How This Snaps Into the Next Layer

We now have the complete contract for **what the model can invoke** (`Tool` + `assembleToolPool`). Next, we need the other half of Layer 1: **what the user can invoke and how conversation messages flow**—the three-variant `Command` contract (`types/command.ts`), `utils/messages.ts`, and `utils/processUserInput/processUserInput.ts` (Chapter 3).

Then, in Part II, we will feed these tools and messages into `context.ts`, `services/api/claude.ts`, `services/tools/toolOrchestration.ts`, `StreamingToolExecutor.ts`, and `query.ts` to bring the entire agent loop to life.

---

## Reading Exercises & Code Checkpoints

1. **Compare a read-only tool with a mutating tool:**
   Read [`tools/FileEditTool/FileEditTool.ts`](../../tools/FileEditTool/FileEditTool.ts) alongside [`tools/GlobTool/GlobTool.ts`](../../tools/GlobTool/GlobTool.ts). How does `FileEditTool` use `ToolUseContext.readFileState` (from Chapter 1) inside `validateInput`?
2. **Find every `maxResultSizeChars: Infinity` opt-out:**
   Run `rg "maxResultSizeChars" tools/` and observe *which* tools opt out of disk persistence and why.
3. **Trace `assembleToolPool` callers:**
   Run `rg "assembleToolPool"` to see how both interactive REPL (`useMergedTools`) and subagents (`runAgent.ts`) share the exact same partitioned-sort pipeline.


---

<!-- chapters/03-command-and-message-contracts.md — https://reverseengineeringclaudecode.com/chapters/03-command-and-message-contracts -->

# Chapter 03 — The Command & Message Contracts: User Input Meets the Model

> **Layer:** Layer 1 (Core Capability & Input Contracts)
> **Prerequisites:** [Chapter 00](00-how-to-read-a-1900-file-agent.md), [Chapter 01](01-atoms-types-stores-and-primitives.md), [Chapter 02](02-the-tool-contract.md)
> **Primary Source Files:**
> - [`types/command.ts`](../../types/command.ts) — three-variant `Command` union, `LocalJSXCommandContext`, `CommandAvailability`, and leaf helpers (216 lines)
> - [`commands.ts`](../../commands.ts) — `COMMANDS` thunk, memoized `loadAllCommands`, live `getCommands` filtering, skill projections, and remote/bridge allowlists (754 lines)
> - [`utils/slashCommandParsing.ts`](../../utils/slashCommandParsing.ts) — zero-import slash parser with two-token `(MCP)` glue (60 lines)
> - [`utils/processUserInput/processUserInput.ts`](../../utils/processUserInput/processUserInput.ts) — multi-modal input router, image resizing, `bridgeOrigin` gate, `ULTRAPLAN` rewrite, attachments, and `UserPromptSubmit` hooks (605 lines)
> - [`utils/processUserInput/processTextPrompt.ts`](../../utils/processUserInput/processTextPrompt.ts) — plain-text prompt assembly, `promptId`, interaction spans, and OTel logging (100 lines)
> - [`utils/messages.ts`](../../utils/messages.ts) — dual UI/API projections, Stage 1 `normalizeMessagesForAPI`, thinking-block passes, `stripSignatureBlocks`, and `ensureToolResultPairing` (5,512 lines)

---

## Why This Layer Exists

Chapter 02 built the model-facing half of Layer 1 (`Tool`, `ToolUseContext`, `assembleToolPool`). Before Layer 2 can build a system prompt and call the LLM, Claude Code needs the human-facing half:

1. **One contract for user-invocable commands:** `/compact`, `/model`, `/commit`, `/my-skill`, and `/server:prompt (MCP)` share one `/` prefix across host actions, Ink dialogs, inline prompt expansions, and forked subagents.
2. **One multi-modal input funnel:** Terminal strings, SDK/VS Code `ContentBlockParam[]` arrays, pasted images, `!` shell escapes, IDE selections, attachments, Remote Control bridge messages, and `UserPromptSubmit` hooks must collapse into one `shouldQuery` envelope.
3. **Two projections over one transcript:** Ink wants 1-block rows, spinners, retry rows, and compaction dividers; the Anthropic API requires strictly alternating `user`/`assistant` turns, valid thinking signatures, and paired `tool_use`/`tool_result` IDs.

---

## 1. The Three-Variant Command Contract & Registry

### The Problem

Separate registries for CLI commands, Ink pickers, disk skills, plugins, workflows, and MCP prompts would fracture autocomplete, `SkillTool`, and remote-safety checks. Eagerly importing ~100 command modules or reading auth state at module load would also hurt startup latency and break mid-session `/login` switches.

### The Real Implementation

`types/command.ts` unifies every command into `Command = CommandBase & (PromptCommand | LocalCommand | LocalJSXCommand)` (`types/command.ts:205-206`). Every import at `types/command.ts:1-14` is `import type`; only `getCommandName` and `isCommandEnabled` (`types/command.ts:209-216`) emit runtime code.

1. **`PromptCommand` (`type: 'prompt'`, `types/command.ts:25-57`)** unifies built-in prompt commands (`/init`, `/review`, `/insights`), bundled skills (`skills/bundledSkills.ts:75-95`), disk skills and `.claude/commands/` (`skills/loadSkillsDir.ts:467`, `skills/loadSkillsDir.ts:608`), plugins (`utils/plugins/loadPluginCommands.ts:300-325`), workflows (`feature('WORKFLOW_SCRIPTS')`), and MCP prompts (`services/mcp/client.ts:2056-2095`), carrying `hooks`, `skillRoot`, `allowedTools`, `model`, `effort`, `paths`, and inline/fork controls:

```ts
// types/command.ts:42-56
// Execution context: 'inline' (default) or 'fork' (run as sub-agent)
// 'inline' = skill content expands into the current conversation
// 'fork' = skill runs in a sub-agent with separate context and token budget
context?: 'inline' | 'fork'
// Agent type to use when forked (e.g., 'Bash', 'general-purpose')
// Only applicable when context is 'fork'
agent?: string
effort?: EffortValue
// Glob patterns for file paths this skill applies to
// When set, the skill is only visible after the model touches matching files
paths?: string[]
getPromptForCommand(
  args: string,
  context: ToolUseContext,
): Promise<ContentBlockParam[]>
```

2. **`LocalCommand` (`type: 'local'`, `types/command.ts:74-78`)** lazy-loads host code via `load: () => Promise<LocalCommandModule>` and returns `LocalCommandResult` (`types/command.ts:16-23`: `'text'`, `'compact'`, or `'skip'`).
3. **`LocalJSXCommand` (`type: 'local-jsx'`, `types/command.ts:144-152`)** lazy-loads an Ink dialog mounted via `setToolJSX`, completing through `LocalJSXCommandOnDone` (`types/command.ts:117-126`: `display?: 'skip' | 'system' | 'user'`, `shouldQuery?`, `metaMessages?`, `nextInput?`, `submitNextInput?`).

**Ch 02 → Ch 03 seam:** `Tool.ts:11` imports `type { Command }` into `ToolUseContext.options.commands` (`Tool.ts:158-160`), while `types/command.ts:6` extends `ToolUseContext` into `LocalJSXCommandContext` (`types/command.ts:80-98`, adding `setMessages`, `canUseTool`, `theme`, `onChangeAPIKey`, `resume`). Both `local` and `local-jsx` receive `LocalJSXCommandContext`; `import type` breaks the bidirectional cycle. On `CommandBase` (`types/command.ts:175-203`), static auth/provider `availability?: ('claude-ai' | 'console')[]` (`types/command.ts:169-173`) is kept strictly separate from dynamic `isEnabled?: () => boolean`.

`commands.ts` splits discovery across three volatility tiers:
- **Deferred built-ins (`COMMANDS`, `commands.ts:258-346`):** A private `lodash-es/memoize` thunk because `isUsing3PServices()` and `login()` read config and auth unavailable at module load. Heavy `/insights` (`commands/insights.ts`, ~113 KB) uses a lazy shim (`usageReport`, `commands.ts:190-202`), and `INTERNAL_ONLY_COMMANDS` (`commands.ts:225-254`) spreads only when `process.env.USER_TYPE === 'ant' && !process.env.IS_DEMO` (`commands.ts:343-345`).
- **Memoized `loadAllCommands(cwd)` vs. live `getCommands(cwd)` (`commands.ts:449-517`):**

```ts
// commands.ts:449-485
const loadAllCommands = memoize(async (cwd: string): Promise<Command[]> => {
  const [
    { skillDirCommands, pluginSkills, bundledSkills, builtinPluginSkills },
    pluginCommands,
    workflowCommands,
  ] = await Promise.all([
    getSkills(cwd),
    getPluginCommands(),
    getWorkflowCommands ? getWorkflowCommands(cwd) : Promise.resolve([]),
  ])

  return [
    ...bundledSkills,
    ...builtinPluginSkills,
    ...skillDirCommands,
    ...workflowCommands,
    ...pluginCommands,
    ...pluginSkills,
    ...COMMANDS(),
  ]
})
// ...
export async function getCommands(cwd: string): Promise<Command[]> {
  const allCommands = await loadAllCommands(cwd)

  // Get dynamic skills discovered during file operations
  const dynamicSkills = getDynamicSkills()

  // Build base commands without dynamic skills
  const baseCommands = allCommands.filter(
    _ => meetsAvailabilityRequirement(_) && isCommandEnabled(_),
  )
```

Running `meetsAvailabilityRequirement` (`commands.ts:417-443`; `'console'` requires `!isClaudeAISubscriber() && !isUsing3PServices() && isFirstPartyAnthropicBaseUrl()`, excluding Bedrock/Vertex/Foundry and gateways) and `isCommandEnabled` outside `loadAllCommands` lets `/login` take effect immediately. `getCommands` then deduplicates `getDynamicSkills()` and splices them right before built-in `COMMANDS()` (`commands.ts:505-516`), preserving `findCommand` order (`commands.ts:688-698`).

- **MCP & skill projections:** Reactive MCP commands live in `AppState.mcp.commands` (`services/mcp/client.ts:2054-2096`) and merge via `useMergedCommands` (`hooks/useMergedCommands.ts:5-15`); behind `feature('MCP_SKILLS')`, `getMcpSkillCommands` (`commands.ts:547-559`) filters `loadedFrom === 'mcp'` (its loader `skills/mcpSkills.js` is absent from this snapshot). Two memoized selectors project distinct skill slices: `getSkillToolCommands` (`commands.ts:563-581`) returns strictly model-invocable prompt commands (`!cmd.disableModelInvocation` at `commands.ts:569`), whereas `getSlashCommandToolSkills` (`commands.ts:586-608`) selects skill-shaped prompt commands and explicitly *includes* `cmd.disableModelInvocation` (`commands.ts:598`). Human-facing labels (`formatDescriptionWithSource`, `commands.ts:728-754`) stay strictly in the UI layer.
- **Remote & bridge allowlists:** `REMOTE_SAFE_COMMANDS` (`commands.ts:619-637`, 17 local-TUI built-ins) feeds `filterCommandsForRemoteMode` (`commands.ts:684-686`). For Remote Control mobile/web input, **`BRIDGE_SAFE_COMMANDS` (`commands.ts:651-660`) and `isBridgeSafeCommand` (`commands.ts:672-676`)** relax **PR #19134**'s blanket bridge block (originally added after iOS `/model` popped the local terminal Ink picker, `commands.ts:666-670`): `'local-jsx'` stays blocked (`false`), `'prompt'` is safe by construction (`true`), and `'local'` fails closed against six allowlisted commands (`compact`, `clear`, `cost`, `summary`, `releaseNotes`, `files`).

### Hidden Invariants & Failure Modes

- **Split cache invalidation (`commands.ts:523-539`):** `clearCommandMemoizationCaches()` clears `loadAllCommands`, `getSkillToolCommands`, `getSlashCommandToolSkills`, and—behind `feature('EXPERIMENTAL_SKILL_SEARCH')` (`commands.ts:96-100`)—`clearSkillIndexCache?.()` (outer memoization in absent `services/skillSearch/localSearch.js`) *without* calling `clearSkillCaches()`, because `utils/skills/skillChangeDetector.ts:92-97` invokes it right after discovering dynamic skills. Full `clearCommandsCache()` wipes everything on `/reload-plugins`. Neither clears `COMMANDS.cache`, and `commands.ts:1` disables import sorting to protect ANT-ONLY strip markers.

> [!NOTE]
> **Gates & Snapshot Absences in `commands.ts`:** Sixteen compile-time `feature('...')` flags (`commands.ts:63-122`, `commands.ts:401`) and `process.env.USER_TYPE === 'ant'` (`commands.ts:49`) gate conditional `require()` imports, while a seventeenth flag (`feature('MCP_SKILLS')`, `commands.ts:550`) gates `getMcpSkillCommands()` runtime filtering and `process.env.USER_TYPE === 'ant' && !process.env.IS_DEMO` (`commands.ts:343`) gates spreading `INTERNAL_ONLY_COMMANDS` into `COMMANDS()`. Thirteen conditional `require()` targets (`commands/agents-platform/index.js`, `commands/proactive.js`, `commands/assistant/index.js`, `commands/remoteControlServer/index.js`, `commands/force-snip.js`, `commands/workflows/index.js`, `services/skillSearch/localSearch.js`, `commands/subscribe-pr.js`, `commands/torch.js`, `commands/peers/index.js`, `commands/fork/index.js`, `commands/buddy/index.js`, `tools/WorkflowTool/createWorkflowCommand.js`) are **absent from this snapshot** (call-site evidence only); 5 `feature()`-gated commands (`commands/brief.ts`, `commands/bridge/index.ts`, `commands/voice/index.ts`, `commands/remote-setup/index.ts`, `commands/ultraplan.tsx`) are present; and 18 inert `.js` stub files back 19 of the 28 `INTERNAL_ONLY_COMMANDS` entries (17 one-line `{ isEnabled: () => false, isHidden: true, name: 'stub' }` default stubs plus 4-line `commands/reset-limits/index.js` exporting both `resetLimits` and `resetLimitsNonInteractive`).

---

## 2. Slash Parsing & Runtime Dispatch

### The Problem

A leading `/` could be a built-in command, an MCP prompt with a space before `(MCP)`, a mistyped skill with long arguments, or a POSIX path like `/etc/hosts`. Once resolved, each variant must protect UI focus, redact secrets, preserve compaction timestamps, and prevent local output from baiting the model into replying next turn.

### The Real Implementation

`parseSlashCommand` (`utils/slashCommandParsing.ts:25-60`) is a zero-import parser returning `ParsedSlashCommand | null` (`{ commandName, args, isMcp }`, `utils/slashCommandParsing.ts:5-9`). Non-`/` input or a bare `'/'` returns `null`; otherwise it splits strictly on `' '` and glues `words[1] === '(MCP)'` into `commandName + ' (MCP)'` to match `services/mcp/client.ts:2066-2070` (`"{client.name}:{prompt.name} (MCP)"`).

Because POSIX paths like `/usr/bin/env` also start with `/`, semantic disambiguation happens inside [`utils/processUserInput/processSlashCommand.tsx`](../../utils/processUserInput/processSlashCommand.tsx) (922 lines: 921 pre-compiled `.tsx` lines + line 922 inline sourcemap, with build-time folded `"external" === 'ant'` checks at `utils/processUserInput/processSlashCommand.tsx:276`, `utils/processUserInput/processSlashCommand.tsx:430`, and `utils/processUserInput/processSlashCommand.tsx:498`). When `!hasCommand()` (`utils/processUserInput/processSlashCommand.tsx:333-381`), it probes `stat('/' + commandName)` and tests `looksLikeCommand(commandName)` (`!/[^a-zA-Z0-9:\-_]/.test(commandName)`, `utils/processUserInput/processSlashCommand.tsx:304-308`). Only `looksLikeCommand && !isFilePath` rejects with `Unknown skill: ...` (`shouldQuery: false`), emitting a UI-only warning `Args from unknown skill: ...` (**`gh-32591`**, `utils/processUserInput/processSlashCommand.tsx:355-357`) so typed arguments survive; real filesystem paths fall through as plain prompts (`shouldQuery: true`).

For known commands, `getMessagesForSlashCommand` (`utils/processUserInput/processSlashCommand.tsx:525-777`) blocks `userInvocable === false` and switches on `command.type`:
- **`local-jsx` (`utils/processUserInput/processSlashCommand.tsx:551-656`):** Settles asynchronously via `onDone`. On the `options?.display === 'system'` branch (`utils/processUserInput/processSlashCommand.tsx:591-593`), it skips `' dismissed'` scrollback entries when fullscreen mode is enabled (`isFullscreenEnvEnabled()`, gated by `CLAUDE_CODE_NO_FLICKER` / `process.env.USER_TYPE === 'ant'` outside `tmux -CC` at `utils/fullscreen.ts:112-129`). Two explicit deadlock guards protect the input queue (`utils/processUserInput/processSlashCommand.tsx:622-655`): `doneWasCalled` stops an early-exit `onDone()` plus returned JSX from re-arming `isLocalJSXCommand`, and `.catch()` clears JSX and resolves so thrown errors never wedge `queryGuard`.
- **`local` (`utils/processUserInput/processSlashCommand.tsx:657-722`):** Redacts arguments to `'***'` when `isSensitive` is set and wraps `'text'` results in `createCommandInputMessage` (`system/local_command`). For `'compact'` results, it bumps `displayText`'s timestamp by `Date.now() + 100` (`utils/processUserInput/processSlashCommand.tsx:689`) so `--resume` selects it as the latest leaf, then calls `resetMicrocompactState()` (`utils/processUserInput/processSlashCommand.tsx:699`).
- **`prompt` (`utils/processUserInput/processSlashCommand.tsx:723-921`):**
  - *Forked (`context === 'fork'`, `utils/processUserInput/processSlashCommand.tsx:62-295`):* The synchronous path streams `runAgent({ isAsync: false, querySource: 'agent:custom', ... })` and returns `shouldQuery: false`. Behind `feature('KAIROS') && (await context.getAppState()).kairosEnabled` (`utils/processUserInput/processSlashCommand.tsx:102-183`), it instead launches an async `runAgent` with a standalone `bgAbortController` and captured `spawnTimeWorkload = getWorkload()`. Before running, the background task polls every `200` ms up to `MCP_SETTLE_TIMEOUT_MS` (`10_000` ms, `utils/processUserInput/processSlashCommand.tsx:56-57`) until no MCP client is `'pending'`, calls `refreshTools?.()`, and re-enqueues `<scheduled-task-result>` (`isMeta: true, skipSlashCommands: true`).
  - *Inline (`getMessagesForPromptSlashCommand`, `utils/processUserInput/processSlashCommand.tsx:827-921`, shared by `SkillTool` via `processPromptSlashCommand` at `utils/processUserInput/processSlashCommand.tsx:817-826`):* Behind `feature('COORDINATOR_MODE') && isEnvTruthy(process.env.CLAUDE_CODE_COORDINATOR_MODE) && !context.agentId` (`utils/processUserInput/processSlashCommand.tsx:837-868`), main-thread coordinators receive a delegation stub while workers (`agentId` set) expand the prompt normally:

```tsx
// utils/processUserInput/processSlashCommand.tsx:874-912
const hooksAllowedForThisSkill = !isRestrictedToPluginOnly('hooks') || isSourceAdminTrusted(command.source);
if (command.hooks && hooksAllowedForThisSkill) {
  const sessionId = getSessionId();
  registerSkillHooks(context.setAppState, sessionId, command.hooks, command.name, command.type === 'prompt' ? command.skillRoot : undefined);
}
// ...
const skillPath = command.source ? `${command.source}:${command.name}` : command.name;
const skillContent = result.filter((b): b is TextBlockParam => b.type === 'text').map(b => b.text).join('\n\n');
addInvokedSkill(command.name, skillPath, skillContent, getAgentContext()?.agentId ?? null);
const metadata = formatCommandLoadingMetadata(command, args);
const additionalAllowedTools = parseToolListFromCLI(command.allowedTools ?? []);
// ...
const messages = [createUserMessage({
  content: metadata,
  uuid
}), createUserMessage({
  content: mainMessageContent,
  isMeta: true
}), ...attachmentMessages, createAttachmentMessage({
  type: 'command_permissions',
  allowedTools: additionalAllowedTools,
  model: command.model
})];
```

### Hidden Invariants & Failure Modes

- **Skill hooks & compaction isolation:** `hooksAllowedForThisSkill` enforces `strictPluginOnlyCustomization: ["hooks"]`, while `addInvokedSkill` keys `bootstrap/state.ts:1510-1524` by `"{agentId ?? ''}:{skillName}"` so invoked skills never leak across subagents during compaction.
- **Metadata & 110 KB latency guard:** Expanded-body attachment extraction passes `{ skipSkillDiscovery: true }` (`utils/processUserInput/processSlashCommand.tsx:897-901`) to avoid stalls on 110 KB `SKILL.md` files. Meanwhile, `formatCommandLoadingMetadata` (`utils/processUserInput/processSlashCommand.tsx:803-816`) emits `<command-name>` and `<command-message>` using qualified `command.name` (plus `<skill-format>true</skill-format>` for model-only skills).
- **Synthetic caveat shield (`utils/processUserInput/processSlashCommand.tsx:512-515`):** Unless `messageShouldQuery`, all messages are `system/local_command`, or the result is a compaction boundary, `processSlashCommand` prepends `createSyntheticUserCaveatMessage()` (`utils/messages.ts:566-571`, `isMeta: true` `<local-command-caveat>`) so the model ignores local output next turn.

---

## 3. Multi-Modal Input Routing & `UserPromptSubmit` Hooks

### The Problem

Input arrives from terminals (strings, pasted images, `!` shell escapes, IDE selections), SDK/VS Code callers (`ContentBlockParam[]` arrays), and Remote Control bridges—while `UserPromptSubmit` hooks can augment, stop, or erase model-bound prompts.

### The Real Implementation

`ProcessUserInputContext = ToolUseContext & LocalJSXCommandContext` and `ProcessUserInputBaseResult` (`utils/processUserInput/processUserInput.ts:62-83`) unify REPL (`utils/handlePromptSubmit.ts:476-496`) and SDK (`QueryEngine.ts:416-428`) callers behind `processUserInput()` (`utils/processUserInput/processUserInput.ts:85-270`). The outer shell echoes non-`isMeta` prompt strings (`setUserInputOnProcessing`), profiles with `queryCheckpoint()` (`CLAUDE_CODE_PROFILE_QUERY`, `utils/queryProfiler.ts:36`), and returns early when `!result.shouldQuery` so local turns bypass hooks.

Inside `processUserInputBase()` (`utils/processUserInput/processUserInput.ts:281-589`):
1. **String vs. `ContentBlockParam[]` (`utils/processUserInput/processUserInput.ts:300-349`):** Resizes inline `image` blocks into `normalizedInput` (fixing dropped resizes and iOS `mediaType` vs. `media_type` per `mobile-apps#5825`), collects `imageMetadataTexts`, splits a trailing `text` block into `inputString` + `precedingInputBlocks`, and throws if `inputString === null && mode !== 'prompt'`.
2. **Terminal `pastedContents` (`utils/processUserInput/processUserInput.ts:351-420`):** Filters pastes via `isValidImagePaste` (`types/textInputTypes.ts:367-369`, dropping 0-byte images that 400), persists via `storeImages()` (`utils/imageStore.ts:84-99`), resizes in parallel (`Promise.all`), and appends `imageMetadataTexts` as an `isMeta: true` `UserMessage` via `addImageMetadataMessage()` (`utils/processUserInput/processUserInput.ts:592-605`) on every exit except `bridgeOrigin` rejection.
3. **`bridgeOrigin` gate (`utils/processUserInput/processUserInput.ts:422-453`):** Mobile/web input arrives with `bridgeOrigin: true` and `skipSlashCommands: true`. For `/...`, `isBridgeSafeCommand` (`commands.ts:672-676`) clears `effectiveSkipSlash` for safe commands, short-circuits known unsafe commands (`shouldQuery: false`), and lets unknown `/shrug` fall through as plain text.
4. **Gated `ULTRAPLAN` rewrite (`utils/processUserInput/processUserInput.ts:467-493`):** Behind `feature('ULTRAPLAN')` plus 8 runtime guards (checking `hasUltraplanKeyword(preExpansionInput ?? inputString)` so pasted text cannot trigger), rewrites to `/ultraplan ${rewritten}` before attachment I/O so React batches UI transitions without flicker.
5. **Attachments & IDE selection (`utils/processUserInput/processUserInput.ts:495-514`):** Skipped for `/slash` commands in `prompt` mode; otherwise drains `getAttachmentMessages` (`utils/attachments.ts:2937-2970`), which wraps `getAttachments` (`utils/attachments.ts:743-1003`). Inside `getAttachments`, collection runs under a 1,000 ms timeout (`utils/attachments.ts:767`) and short-circuits to queued commands only when `CLAUDE_CODE_DISABLE_ATTACHMENTS` or `CLAUDE_CODE_SIMPLE` is set (`utils/attachments.ts:752-760`). On the main thread, `ideSelection` emits `selected_lines_in_ide` or `opened_file_in_ide` while honoring `isFileReadDenied()`.
6. **Three dispatch exits:**
   - **`mode === 'bash'` (`utils/processUserInput/processUserInput.ts:517-529`):** Dynamically imports [`utils/processUserInput/processBashCommand.tsx`](../../utils/processUserInput/processBashCommand.tsx) (140 lines: 139 code + line 140 sourcemap). It selects PowerShell only when `isPowerShellToolEnabled() && resolveDefaultShell() === 'powershell'` (`utils/processUserInput/processBashCommand.tsx:26`), lazy-requiring ~300 KB `PowerShellTool` behind a Windows-only gate (`CLAUDE_CODE_USE_POWERSHELL_TOOL` / `process.env.USER_TYPE === 'ant'`, `utils/shell/shellToolUtils.ts:17-22`). Execution runs with `dangerouslyDisableSandbox: true`, formats stdout via `processToolResultBlock(shellTool, { ...data, stderr: '' }, randomUUID())` (`utils/processUserInput/processBashCommand.tsx:98-106`), and returns `shouldQuery: false`.
   - **`/slash` (`utils/processUserInput/processUserInput.ts:533-551`):** Dynamically imports `utils/processUserInput/processSlashCommand.tsx`.
   - **Plain text (`utils/processUserInput/processUserInput.ts:553-588`):** Logs `tengu_subagent_at_mention` when an `@agent-` attachment is present and delegates assembly to `processTextPrompt()`.

**Plain-text assembly (`utils/processUserInput/processTextPrompt.ts:19-100`):** Every non-slash, non-bash prompt funnels through `processTextPrompt()`. It mints a fresh `promptId` via `setPromptId(promptId)` (`bootstrap/state.ts`) and opens the telemetry interaction span using the *first* text block (`.find(block => block.type === 'text')`).

By contrast, OTel `user_prompt` logging (redacted unless `OTEL_LOG_USER_PROMPTS` is set, `utils/telemetry/events.ts:14`) reads **`.findLast(block => block.type === 'text')`** (`utils/processUserInput/processTextPrompt.ts:47-57`)—a production scar from **`anthropics/claude-code#33301`**, because VS Code submits `ContentBlockParam[]` arrays with `<ide_selection>` context prepended ahead of the user's actual message. After logging `tengu_input_prompt` keyword analytics, `processTextPrompt()` drops whitespace-only text when pasted images are attached (`utils/processUserInput/processTextPrompt.ts:67-76`) so the model sees clean image blocks, then returns `[userMessage, ...attachmentMessages]` with `shouldQuery: true`.

When `result.shouldQuery` is `true`, `executeUserPromptSubmitHooks` (`utils/processUserInput/processUserInput.ts:182-263`) distinguishes blocking from stopping and truncates `additionalContexts` / non-empty `hook_success` strings at `MAX_HOOK_OUTPUT_LENGTH = 10000` (`applyTruncation`, `utils/processUserInput/processUserInput.ts:272-279`):

```ts
// utils/processUserInput/processUserInput.ts:193-224
// Return only a system-level error message, erasing the original user input
if (hookResult.blockingError) {
  const blockingMessage = getUserPromptSubmitHookBlockingMessage(
    hookResult.blockingError,
  )
  return {
    messages: [
      // TODO: Make this an attachment message
      createSystemMessage(
        `${blockingMessage}\n\nOriginal prompt: ${input}`,
        'warning',
      ),
    ],
    shouldQuery: false,
    allowedTools: result.allowedTools,
  }
}

// If preventContinuation is set, stop processing but keep the original
// prompt in context.
if (hookResult.preventContinuation) {
  const message = hookResult.stopReason
    ? `Operation stopped by hook: ${hookResult.stopReason}`
    : 'Operation stopped by hook'
  result.messages.push(
    createUserMessage({
      content: message,
    }),
  )
  result.shouldQuery = false
  return result
}
```

### Hidden Invariants & Failure Modes

> [!WARNING]
> **Three Traps in `utils/processUserInput/`:**
> 1. **`blockingError` erases vs. `preventContinuation` preserves:** `blockingError` wipes `result.messages` into a UI-only `warning` `SystemMessage` (note `${input}` at `utils/processUserInput/processUserInput.ts:202` stringifies arrays as `[object Object]`); `preventContinuation` retains the prompt and appends a stop message.
> 2. **Unescaped `<persisted-output>`:** `utils/processUserInput/processBashCommand.tsx:102-106` skips `escapeXml()` on `mapped.content` (escaping only `stderr` and raw fallback `data.stdout`) so disk-spilled `<persisted-output>` tags aren't broken into `&lt;persisted-output&gt;`.
> 3. **Snapshot absences:** Type-only imports `constants/querySource.js` (`utils/processUserInput/processUserInput.ts:8`), `types/message.js` (`utils/processUserInput/processUserInput.ts:20-27`), and `types/tools.js` (`utils/processUserInput/processBashCommand.tsx:8`, `ShellProgress` observed in `components/BashModeProgress.tsx:34`) are **absent from this checkout**.

---

## 4. Dual Message Views & The Two-Stage API Boundary

### The Problem

One `Message[]` array must serve Ink (1-block rows, spinners, retry rows, compaction dividers) and the Anthropic API (alternating `user`/`assistant` turns, zero UI chrome), while ~10 internal callers—compaction (`services/compact/compact.ts:1293`), VCR (`services/vcr.ts:96`), analytics, and `query.ts:855`—need normalized messages without model, beta, or cache context.

> [!NOTE]
> **Snapshot Absence of `types/message.ts` & `types/utils.ts`:** Both `types/message.ts` (`utils/messages.ts:41-73`, 31 types) and `types/utils.ts` (`utils/messages.ts:121`, `DeepImmutable`) are **absent from this snapshot**. Observed via `utils/messages.ts` factories: 5 core union variants (`user`, `assistant`, `attachment`, `progress`, and `system` with **14 constructed subtypes** at `utils/messages.ts:4335-4603`) plus 4 stream/SDK envelopes (`tombstone`, `tool_use_summary`, `stream_event`, `stream_request_start` at `utils/messages.ts:2951-2962`).

### The Real Implementation

`utils/messages.ts` projects the transcript in opposite directions:

| Dimension | UI View (`components/Messages.tsx`) | API View (`normalizeMessagesForAPI` → Stage 2) |
|---|---|---|
| **Granularity** | **Splits 1 → N** via `normalizeMessages` (`utils/messages.ts:741-823`) with deterministic `deriveUUID` (`utils/messages.ts:725-728`) so Ink never remounts rows. | **Merges N → 1** via `mergeUserMessages` (`utils/messages.ts:2411-2449`) and `mergeAssistantMessages` (`utils/messages.ts:2389-2400`). |
| **Non-chat records** | Keeps `attachment`, `progress`, `system`; `reorderMessagesInUI` (`utils/messages.ts:855-1026`) groups tools/hooks; `shouldShowUserMessage` (`utils/messages.ts:4658-4677`) hides `isMeta` except `origin.kind === 'channel'` (`feature('KAIROS') \|\| feature('KAIROS_CHANNELS')`). | Drops `isVirtual`, `progress`, `isSyntheticApiErrorMessage`, and 13 of 14 `system` subtypes; promotes `system/local_command` to `UserMessage`; bubbles and expands `attachment` into `isMeta` `UserMessage[]`. |
| **Scale / Compaction** | `buildMessageLookups` (`utils/messages.ts:1170-1340`) precomputes O(1) Maps; `components/Messages.tsx:496-498` passes `{ includeSnipped: true }` to `getMessagesAfterCompactBoundary`. | `query.ts:365` slices via `getMessagesAfterCompactBoundary` (`utils/messages.ts:4643-4656`, absent `services/compact/snipProjection.js` under `feature('HISTORY_SNIP')`). |

*(Notably, `filterUnresolvedToolUses` at `utils/messages.ts:2796-2800` skips `normalizeMessages` because derived UUIDs would defeat JSONL resume deduplication.)*

> [!IMPORTANT]
> **The Two-Stage Normalization Boundary:**
> **Stage 1** (`normalizeMessagesForAPI`, `utils/messages.ts:1989-2370`) is model-agnostic and returns **internal `(UserMessage | AssistantMessage)[]`** retaining `uuid`, `isMeta`, `timestamp`, and `message.id`—**not** wire `MessageParam[]`.
> **Stage 2** lives in `services/api/claude.ts` ([Chapter 05](05-talking-to-the-model.md)): right after calling `normalizeMessagesForAPI` (`services/api/claude.ts:1266-1315`), it runs model-aware `!useToolSearch` re-stripping, calls **`ensureToolResultPairing`** (`services/api/claude.ts:1301` — *outside* `normalizeMessagesForAPI`), strips advisor blocks without `ADVISOR_BETA_HEADER`, and caps media at `100` (`API_MAX_MEDIA_PER_REQUEST`). Finally, `addCacheBreakpoints` (`services/api/claude.ts:3063-3211`) emits wire `MessageParam[]` via `userMessageToMessageParam` and `assistantMessageToMessageParam` (`services/api/claude.ts:588-674`).

**Why UI-only `system` messages vanish here:** First, `reorderAttachmentsForAPI` (`utils/messages.ts:1481-1527`) bubbles attachments upward in O(N) until hitting an `assistant` or `tool_result` user message, and `isVirtual` records are dropped (`utils/messages.ts:1999-2001`). Second, `stripTargets` (`utils/messages.ts:2004-2054`) scans `isSyntheticApiErrorMessage` (`utils/messages.ts:321-329`, `model === '<synthetic>'`) for 5 PDF/image errors, tagging the preceding `isMeta` user message to strip poisoned blocks. Only *after* `compact_boundary` has been sliced (`query.ts:365`) and `stripTargets` has read synthetic errors—yet *before* role merging—does the filter run:

```ts
// utils/messages.ts:2056-2075
const result: (UserMessage | AssistantMessage)[] = []
reorderedMessages
  .filter(
    (
      _,
    ): _ is
      | UserMessage
      | AssistantMessage
      | AttachmentMessage
      | SystemLocalCommandMessage => {
      if (
        _.type === 'progress' ||
        (_.type === 'system' && !isSystemLocalCommandMessage(_)) ||
        isSyntheticApiErrorMessage(_)
      ) {
        return false
      }
      return true
    },
  )
```

Thirteen of fourteen `system` subtypes (`compact_boundary`, `microcompact_boundary`, `api_error`, `turn_duration`, `stop_hook_summary`, `api_metrics`, `informational`, etc.) are dropped; only `subtype === 'local_command'` (`utils/messages.ts:1529-1533`) promotes to a `UserMessage` (`utils/messages.ts:2078-2093`). Stripping earlier breaks compaction and error recovery; stripping later corrupts role merging.

Inside the main `switch` (`utils/messages.ts:2076-2293`) and post-passes (`utils/messages.ts:2301-2367`):
- **User merging (`mergeUserMessages`, `utils/messages.ts:2411-2449`):** Strips `tool_reference` blocks via `isToolSearchEnabledOptimistic()`, applies `stripTargets`, and merges consecutive user turns (required by Bedrock). It hoists `tool_result` blocks first (`hoistToolResults`, `utils/messages.ts:2470-2483`), appends `\n` onto **`a`'s tail** (`joinTextAtSeam`, `utils/messages.ts:2505-2515`) so `b`'s leading `<system-reminder>` survives, and preserves the non-meta `uuid` (`a.isMeta ? b.uuid : a.uuid`, `utils/messages.ts:2443`). Inside `if (feature('HISTORY_SNIP'))` when `isSnipRuntimeEnabled()` is active (`utils/messages.ts:2414-2438`), an earlier branch preserves the same non-meta `uuid` (`utils/messages.ts:2429`) while narrowing `isMeta` to `a.isMeta && b.isMeta ? true : undefined` so mixed real-user turns still receive `[id:]` tags.
- **Assistant reassembly:** Canonicalizes tool names, calls `normalizeToolInputForAPI` (`utils/api.ts:685-718`, stripping injected `ExitPlanModeV2` and legacy `FileEditTool` fields), drops `caller` when tool search is off, and walks *backward* across interleaved `tool_result`s and different-`id` teammate assistants (`utils/messages.ts:2250-2264`) to merge split streaming chunks sharing `message.id`.
- **Attachment expansion (`normalizeAttachmentForAPI`, `utils/messages.ts:3453-4286`):** Expands runtime attachments into `isMeta` `UserMessage[]`—with gated branches for `feature('EXPERIMENTAL_SKILL_SEARCH')` (`utils/messages.ts:3506`), `feature('HISTORY_SNIP')` (`context_efficiency` at `utils/messages.ts:4149`, requiring absent `services/compact/snipCompact.js`), and `process.env.CLAUDE_CODE_VERIFY_PLAN === 'true'` (`utils/messages.ts:4244`)—then folds them into the preceding user turn via `mergeUserMessagesAndToolResults` (`utils/messages.ts:2372-2387`).
- **The `#21049` smooshing scar:** Leaving `<system-reminder>` text as siblings after a `tool_result` taught models premature 3-token `end_turn` stops (`#21049`, `utils/messages.ts:2605-2609`). When Statsig/GrowthBook gate `tengu_chair_sermon` is off, a legacy ungated path still smooshes all-text siblings into string-content `tool_result`s (`utils/messages.ts:2615-2628`). Enabling `tengu_chair_sermon` turns on *universal* smooshing (images, documents, and search results), `ensureSystemReminderWrap` (`utils/messages.ts:2273-2277`), and post-pass `smooshSystemReminderSiblings` (`utils/messages.ts:2334-2338`). Separately, `tengu_toolref_defer_j8m` (`utils/messages.ts:2160`, `utils/messages.ts:2301-2305`) relocates siblings off `tool_reference` messages (`relocateToolReferenceSiblings`) instead of injecting the fallback `'Tool loaded.'` turn boundary.
- **Final Stage 1 guards:** `sanitizeErrorToolResultContent` (`utils/messages.ts:2343`, unconditional) strips non-text blocks from `is_error: true` tool results; `feature('HISTORY_SNIP') && process.env.NODE_ENV !== 'test'` appends `[id:...]` tags via `isSnipRuntimeEnabled()` from absent `services/compact/snipCompact.js` (`utils/messages.ts:2351-2364`); and `validateImagesForAPI` (`utils/messages.ts:2367`) enforces the 5 MB base64 cap.

### Hidden Invariants & Failure Modes

- **Cache & VCR protection:** Inbound `normalizeContentFromAPI` (`utils/messages.ts:2721-2730`) leaves whitespace text unmodified so prompt-cache hashes hold (logging unparseable JSON only when `process.env.USER_TYPE === 'ant'` at `utils/messages.ts:2687`). Outbound Stage 2 `userMessageToMessageParam` (`services/api/claude.ts:622-630`) clones array `content` so `cache_edits` splicing (`feature('CACHED_MICROCOMPACT')`) never mutates caller arrays. Both `tengu_chair_sermon` and `HISTORY_SNIP` guard against changing VCR fixture hashes.

---

## 5. Wire-Safety Invariants: Thinking Blocks & Tool Pairing

### The Problem

Interrupted streams, compaction slices, `/resume`, `/login`, and fallback retries can strand thinking shards, leave trailing thinking atop whitespace text, invalidate signatures, duplicate `tool_use` IDs across turns, or orphan `tool_result`s—all fatal 400 errors.

### The Real Implementation

#### A. Thinking-Block Pass Order & Signature Stripping

Stage 1 runs four assistant-cleanup passes in a **strict, non-commutable order**:

```ts
// utils/messages.ts:2307-2325
// Filter orphaned thinking-only assistant messages (likely introduced by
// compaction slicing away intervening messages between a failed streaming
// response and its retry). Without this, consecutive assistant messages with
// mismatched thinking block signatures cause API 400 errors.
const withFilteredOrphans = filterOrphanedThinkingOnlyMessages(relocated)

// Order matters: strip trailing thinking first, THEN filter whitespace-only
// messages. The reverse order has a bug: a message like [text("\n\n"), thinking("...")]
// survives the whitespace filter (has a non-text block), then thinking stripping
// removes the thinking block, leaving [text("\n\n")] — which the API rejects.
//
// These multi-pass normalizations are inherently fragile — each pass can create
// conditions a prior pass was meant to handle. Consider unifying into a single
// pass that cleans content, then validates in one shot.
const withFilteredThinking =
  filterTrailingThinkingFromLastAssistant(withFilteredOrphans)
const withFilteredWhitespace =
  filterWhitespaceOnlyAssistantMessages(withFilteredThinking)
const withNonEmpty = ensureNonEmptyAssistantContent(withFilteredWhitespace)
```

1. `filterOrphanedThinkingOnlyMessages` (`utils/messages.ts:4991-5058`) drops thinking-only shards whose `message.id` has no non-thinking sibling.
2. `filterTrailingThinkingFromLastAssistant` (`utils/messages.ts:4781-4828`) strips trailing thinking blocks from `messages.at(-1)` (substituting `'[No message content]'` if all blocks were thinking).
3. `filterWhitespaceOnlyAssistantMessages` (`utils/messages.ts:4869-4919`) drops whitespace-only assistants and re-merges newly adjacent `user` turns—catching `[text("\n\n")]` exposed by step 2.
4. `ensureNonEmptyAssistantContent` (`utils/messages.ts:4933-4977`) patches non-final `content: []` to `NO_CONTENT_MESSAGE` (`'(no content)'`), leaving a final empty assistant legal for prefill.

Across credential or model changes, `stripSignatureBlocks` (`utils/messages.ts:5066-5099`) strips `thinking`, `redacted_thinking`, and—behind `feature('CONNECTOR_TEXT')`—`isConnectorTextBlock` (from absent `types/connectorText.js`), stripping thinking-only shards to `content: []` so `mergeAssistantMessages` absorbs them. It runs unconditionally on `/login` (`commands/login/login.tsx:24`) and behind `process.env.USER_TYPE === 'ant'` on `FallbackTriggeredError` (`query.ts:927-929`). In Stage 2, `assistantMessageToMessageParam` (`services/api/claude.ts:658-661`) also refuses to attach `cache_control` to trailing `thinking`, `redacted_thinking`, or `CONNECTOR_TEXT` blocks.

#### B. Bidirectional `ensureToolResultPairing` (`utils/messages.ts:5133-5460`)

Because 1-to-1 `(assistant, user)` adjacency exists only after Stage 1 merges streaming chunks and consecutive user turns, `ensureToolResultPairing` runs in **Stage 2 at `services/api/claude.ts:1301`**:

```ts
// utils/messages.ts:5301-5443
// Find missing tool_result IDs (forward direction: tool_use without tool_result)
const toolUseIdSet = new Set(toolUseIds)
const missingIds = toolUseIds.filter(id => !existingToolResultIds.has(id))

// Find orphaned tool_result IDs (reverse direction: tool_result without tool_use)
const orphanedIds = [...existingToolResultIds].filter(
  id => !toolUseIdSet.has(id),
)
// ...
// Build synthetic error tool_result blocks for missing IDs
const syntheticBlocks: ToolResultBlockParam[] = missingIds.map(id => ({
  type: 'tool_result' as const,
  tool_use_id: id,
  content: SYNTHETIC_TOOL_RESULT_PLACEHOLDER,
  is_error: true,
}))
// ...
if (getStrictToolResultPairing()) {
  throw new Error(
    `ensureToolResultPairing: tool_use/tool_result pairing mismatch detected (strict mode). ` +
      `Refusing to repair — would inject synthetic placeholders into model context. ` +
      `Message structure: ${messageTypes.join('; ')}. See inc-4977.`,
  )
}
```

Six invariants are enforced in one forward pass:
1. **No leading `tool_result` (`utils/messages.ts:5152-5203`):** Strips `tool_result` blocks from any `user` message not preceded by an `assistant`, substituting `'[Orphaned tool result removed due to conversation resume]'` at index 0 so requests open with `user`.
2. **Cross-message `tool_use` dedup (`utils/messages.ts:5147`, `utils/messages.ts:5225-5234`):** Tracks `allSeenToolUseIds` globally across turns (`CC-1212` `"tool_use ids must be unique"`).
3. **Same-message server/MCP pairing (`utils/messages.ts:5205-5211`, `utils/messages.ts:5235-5243`):** Strips `server_tool_use`/`mcp_tool_use` lacking a matching `*_tool_result` in the same assistant message.
4. **Non-empty assistant fallback (`utils/messages.ts:5248-5256`):** Inserts `'[Tool use interrupted]'` if stripping empties content.
5. **Bidirectional repair + role alternation (`utils/messages.ts:5267-5399`):** Prepends `is_error: true` `SYNTHETIC_TOOL_RESULT_PLACEHOLDER` (`'[Tool result missing due to internal error]'`, `utils/messages.ts:246-247`) for forward `missingIds`, strips reverse `orphanedIds` and duplicate `tool_result`s, and replaces an emptied `nextMsg` with `createUserMessage({ content: NO_CONTENT_MESSAGE, isMeta: true })` (`utils/messages.ts:5382-5387`) to preserve role alternation.
6. **HFI strict mode (`utils/messages.ts:5437-5456`):** Interactive turns repair and log `tengu_tool_result_pairing_repaired`; HFI enables `getStrictToolResultPairing()` (`bootstrap/state.ts:1093-1095`, default `false`) to throw citing `inc-4977` instead of tainting trajectories.

### Hidden Invariants & Failure Modes

- Because `ensureToolResultPairing` runs after Stage 1, prepending `syntheticBlocks` can create a `[tool_result, <system-reminder>]` sibling Stage 1 never saw—so `utils/messages.ts:5370-5374` re-runs `smooshSystemReminderSiblings` on `patchedNext` when `tengu_chair_sermon` is enabled.

---

## Putting Layer 1 Together

```text
Keyboard / SDK ContentBlockParam[] / Pasted Images / IDE / Bridge
   │
   ▼
processUserInput()  (utils/processUserInput/processUserInput.ts)
   ├─ resize inline & pasted images + storeImages() + imageMetadataTexts
   ├─ bridgeOrigin (isBridgeSafeCommand) + ULTRAPLAN rewrite (gated)
   ├─ getAttachmentMessages() (1s timeout; skipped for /slash in prompt)
   ├─ mode==='bash' -> processBashCommand.tsx          (shouldQuery: false)
   ├─ '/slash'      -> parseSlashCommand + processSlashCommand.tsx
   │                  [local/forked: false | local-jsx: opt-in | prompt: true]
   ├─ plain text    -> processTextPrompt.ts            (shouldQuery: true)
   └─ if (shouldQuery) -> executeUserPromptSubmitHooks() (10k cap)
   │
   ▼
Shared Message[] Transcript (user, assistant, attachment, progress, system)
   ├──> UI View   : normalizeMessages (1->N, deriveUUID) + reorderMessagesInUI
   └──> Model View:
          [Pre]  getMessagesAfterCompactBoundary + prependUserContext (Ch 04)
          [Stg1] normalizeMessagesForAPI() (utils/messages.ts:1989-2370)
                   ├─ reorderAttachmentsForAPI + drop isVirtual
                   ├─ stripTargets + drop progress/UI system/synth errors
                   ├─ promote local_command + merge user & split assistants
                   ├─ filterOrphaned -> filterTrailing -> filterWhitespace
                   │  -> ensureNonEmpty + smoosh + sanitizeErrorToolResult
                   └─ returns internal (UserMessage | AssistantMessage)[]
          [Stg2] services/api/claude.ts (Ch 05 seam)
                   ├─ !useToolSearch strip + ensureToolResultPairing()
                   └─ stripAdvisor/media(100) + addCacheBreakpoints -> wire
```

---

## How This Snaps Into the Next Layer

Layer 1 (`Tool`, `Command`, `processUserInput`, Stage 1 normalization) is complete and snaps directly into **Layer 2**, starting with [Chapter 04](04-prompt-engineering-and-cache-boundaries.md):

- **Skill inventory → dynamic prompt:** `constants/prompts.ts:458` awaits `getSkillToolCommands(cwd)` (`commands.ts:563`) inside `getSystemPrompt()` to populate the post-boundary `session_guidance` section (`constants/prompts.ts:491-494`).
- **Split context snapshots → `isMeta` user message & system prompt:** `context.ts` splits cached snapshots across `getUserContext()` (`CLAUDE.md` + `currentDate`, `context.ts:155-189`) and `getSystemContext()` (`git status`, `context.ts:116-150`, appended to the system prompt via `appendSystemContext` at `utils/api.ts:437-447`). `prependUserContext` (`utils/api.ts:449-474`, invoked at `query.ts:660`, no-op when `process.env.NODE_ENV === 'test'` at `utils/api.ts:453`) wraps `getUserContext()` via `createUserMessage({ ..., isMeta: true })` so Stage 1 merges it with the first user turn.
- **Reciprocal tool-input cleanup:** `utils/messages.ts:2215` calls back into `utils/api.ts:685-718` (`normalizeToolInputForAPI`) to strip runtime-injected fields before API serialization.
- **Stage 2 forward seam ([Chapter 05](05-talking-to-the-model.md)):** `services/api/claude.ts:588-674`, `services/api/claude.ts:1266-1315`, `services/api/claude.ts:1701-1709`, and `services/api/claude.ts:3063-3211` run `ensureToolResultPairing`, `addCacheBreakpoints`, `userMessageToMessageParam`, and `assistantMessageToMessageParam` to emit cached wire `MessageParam[]` payloads.

---

## Reading Exercises & Code Checkpoints

1. **Trace Remote Control bridge safety from registry to input router:**
   ```sh
   rg -n "isBridgeSafeCommand|BRIDGE_SAFE_COMMANDS|REMOTE_SAFE_COMMANDS" commands.ts utils/processUserInput/processUserInput.ts
   ```
   Why does `isBridgeSafeCommand()` automatically allow every `prompt` command while requiring an explicit allowlist for `local` commands and blocking every `local-jsx` command?

2. **Follow the Stage 1 normalization and Stage 2 tool-pairing boundary:**
   ```sh
   rg -n "normalizeMessagesForAPI|reorderAttachmentsForAPI|ensureToolResultPairing|filterTrailingThinkingFromLastAssistant" utils/messages.ts services/api/claude.ts
   ```
   Verify that `ensureToolResultPairing()` runs at `services/api/claude.ts:1301` rather than inside `normalizeMessagesForAPI()`. Why must same-`id` assistant merging and model-aware tool-search stripping finish before pairing runs?

3. **Audit input-pipeline gates, hook truncation, and `isMeta` image metadata:**
   ```sh
   rg -n "MAX_HOOK_OUTPUT_LENGTH|executeUserPromptSubmitHooks|ULTRAPLAN|addImageMetadataMessage" utils/processUserInput/
   ```
   Which early-return branch inside `processUserInputBase()` bypasses `addImageMetadataMessage()`, and why do `UserPromptSubmit` hooks never execute for `!` bash commands?

4. **Inspect the Chapter 03 → Chapter 04 and Stage 2 (Chapter 05) seams:**
   ```sh
   rg -n "getSkillToolCommands|prependUserContext|userMessageToMessageParam|assistantMessageToMessageParam" constants/prompts.ts utils/api.ts services/api/claude.ts
   ```
   Notice that `prependUserContext()` (`utils/api.ts:449-474`) constructs a `UserMessage` with `isMeta: true` while `userMessageToMessageParam()` (`services/api/claude.ts:588-631`) strips internal metadata into an Anthropic SDK `MessageParam`. Where in the pipeline does `isMeta` stop mattering?


---

<!-- chapters/04-prompt-engineering-and-cache-boundaries.md — https://reverseengineeringclaudecode.com/chapters/04-prompt-engineering-and-cache-boundaries -->

# Chapter 04 — Prompt Engineering as Systems Engineering: Context & Cache Boundaries

> **Layer:** Layer 2 (The Agent Engine)
> **Prerequisites:** [Chapter 01](01-atoms-types-stores-and-primitives.md), [Chapter 02](02-the-tool-contract.md), [Chapter 03](03-command-and-message-contracts.md)
> **Primary Source Files:**
> - [`context.ts`](../../context.ts) — conversation-memoized git snapshot (`getGitStatus`), `getSystemContext`, `getUserContext`, and `cachedClaudeMdContent` cycle breaker (189 lines)
> - [`utils/claudemd.ts`](../../utils/claudemd.ts) — `getMemoryFiles` / `filterInjectedMemoryFiles` / `getClaudeMds` injection seam (1,479 lines; scoped here to `getUserContext()` — full discovery in [Chapter 10](10-memory-systems-claudemd-auto-memory-and-dream.md))
> - [`constants/systemPromptSections.ts`](../../constants/systemPromptSections.ts) — `systemPromptSection`, `DANGEROUS_uncachedSystemPromptSection`, and `clearSystemPromptSections` (68 lines)
> - [`constants/prompts.ts`](../../constants/prompts.ts) — `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` and static-vs-dynamic `getSystemPrompt()` assembly (914 lines)
> - [`utils/systemPromptType.ts`](../../utils/systemPromptType.ts) — zero-dependency branded `SystemPrompt` type leaf (14 lines)
> - [`utils/systemPrompt.ts`](../../utils/systemPrompt.ts) — five-tier `buildEffectiveSystemPrompt()` priority cascade (123 lines)
> - [`utils/api.ts`](../../utils/api.ts) — `splitSysPromptPrefix`, `appendSystemContext`, `prependUserContext`, `toolToAPISchema`, `logAPIPrefix`, and `normalizeToolInputForAPI` (718 lines)
> - [`services/api/promptCacheBreakDetection.ts`](../../services/api/promptCacheBreakDetection.ts) — two-phase prompt-cache-break forensics and unified diff writer (727 lines)

---

## Why This Layer Exists

Layer 1 gave us tools (`Tool` and `assembleToolPool` in [Chapter 02](02-the-tool-contract.md)), commands and skills (`Command` and `getSkillToolCommands`), and Stage 1 normalized messages (`createUserMessage` and `normalizeMessagesForAPI` in [Chapter 03](03-command-and-message-contracts.md)). Layer 2 starts with a physical constraint: before sending a single HTTP request, Claude Code must assemble ~10–30K tokens of tool schemas, instructions, project rules, and repository state **without turning every turn into a cold cache miss**.

Anthropic's prompt cache hashes a request in strict prefix order: `tools[]` first, then `system[]`, then `messages[]`. Mutate a single byte early—a newly edited file in `git status`, a midnight date rollover, a GrowthBook flag flipping mid-session, or a conditional bullet inserted into the static system prompt—and every cached token after it degrades from a cheap read into full-price `cache_creation`.

Worse, on Anthropic's first-party API, Claude Code shares one cross-organization `scope: 'global'` cache across every user's static system prompt; leaking a single session-varying bit before that boundary fractures cross-org hit rates. Prompt engineering in Claude Code is therefore **cache-key systems engineering**.

---

## 1. Conversation-Memoized Context & the `CLAUDE.md` Cycle Breaker (`context.ts`, `utils/claudemd.ts`, `utils/queryContext.ts`)

### The Problem

Ambient repository state (`git status`, `CLAUDE.md`, today's date) is vital on turn 1 but toxic to prefix caching if recomputed. Re-running `git status` per turn would mutate the system prompt after every edit and invalidate the entire conversation cache; refreshing today's date inside `messages[0]` at midnight would wipe an overnight session's prefix.

### The Mechanism: Frozen Promises & Tail Rollovers

[`context.ts`](../../context.ts) freezes ambient state behind zero-argument `lodash-es/memoize` wrappers—caching the **in-flight `Promise`** so both cache stability and startup latency hiding fall out of one primitive.

1. **`getGitStatus()` (`context.ts:36-111`):** Skips when `process.env.NODE_ENV === 'test'` (`context.ts:37-40`) or `!await getIsGit()` (`context.ts:46-57`, a zero-subprocess upward `.git` stat walk in `utils/git.ts:218-229`). Inside a repository, it fans out five lookups in parallel (`context.ts:61-77`):
   - **Two zero-subprocess filesystem reads:** `getBranch()` and `getDefaultBranch()` (`utils/git.ts:261-267` → `computeBranch()` at `utils/git/gitFilesystem.ts:500-510` and `computeDefaultBranch()` at `utils/git/gitFilesystem.ts:544-566`), reading `.git/HEAD` and `refs/remotes/origin/HEAD` directly.
   - **Three `execFileNoThrow` calls:** `status --short` and `log --oneline -n 5` (with `--no-optional-locks` to avoid `.git/index.lock` contention), plus `config user.name`. Passing `{ preserveOutputOnError: false }` bypasses `execFileNoThrow`'s default options object (`utils/execFileNoThrow.ts:26-44` and `utils/execFileNoThrow.ts:94`), leaving `timeout` at its 10-minute inner fallback and `cwd` as `undefined` (inheriting `process.cwd()`), while resolving non-zero exits (e.g., an empty repo) cleanly to empty stdout.
   - **Truncation & snapshot warning:** Output above `MAX_STATUS_CHARS = 2000` (`context.ts:20`) truncates with a hint to call `BashTool`, and `context.ts:97` warns the model explicitly that the status is a point-in-time snapshot:

```ts
// context.ts:61-103
    const [branch, mainBranch, status, log, userName] = await Promise.all([
      getBranch(),
      getDefaultBranch(),
      execFileNoThrow(gitExe(), ['--no-optional-locks', 'status', '--short'], {
        preserveOutputOnError: false,
      }).then(({ stdout }) => stdout.trim()),
      // ... git log --oneline -n 5 (--no-optional-locks) & git config user.name
    ])
    // ...
    const truncatedStatus =
      status.length > MAX_STATUS_CHARS
        ? status.substring(0, MAX_STATUS_CHARS) +
          '\n... (truncated because it exceeds 2k characters. If you need more information, run "git status" using BashTool)'
        : status
    // ...
    return [
      `This is the git status at the start of the conversation. Note that this status is a snapshot in time, and will not update during the conversation.`,
      `Current branch: ${branch}`,
      `Main branch (you will usually use this for PRs): ${mainBranch}`,
      ...(userName ? [`Git user: ${userName}`] : []),
      `Status:\n${truncatedStatus || '(clean)'}`,
      `Recent commits:\n${log}`,
    ].join('\n\n')
```

Startup prefetches overlap these git spawns with command loading, but `prefetchSystemContextIfSafe()` (`main.tsx:360-380`) refuses to run `git` in interactive mode until `checkHasTrustDialogAccepted()` is true (preventing malicious `.git/config` execution before trust), kicking `void getSystemContext()` only after `TrustDialog` finishes (`interactiveHelpers.tsx:152-153`).

2. **`getSystemContext()` (`context.ts:116-150`):** Skips `getGitStatus()` when `isEnvTruthy(process.env.CLAUDE_CODE_REMOTE)` or `!shouldIncludeGitInstructions()` (`utils/gitSettings.ts:14-17`, honoring `CLAUDE_CODE_DISABLE_GIT_INSTRUCTIONS` and `includeGitInstructions`).

   Under build-time `feature('BREAK_CACHE_COMMAND')` (`context.ts:131-147`), it also emits `` cacheBreaker: `[CACHE_BREAKER: ${injection}]` `` from `getSystemPromptInjection()` / `setSystemPromptInjection()` (`context.ts:25-34`). In this checkout, [`commands/break-cache/index.js`](../../commands/break-cache/index.js) (`commands/break-cache/index.js:1`) is a stripped one-line stub (`isEnabled: () => false`), so no active caller passes a non-null string—only `setSystemPromptInjection(null)` in `commands/clear/caches.ts:66` remains live.

3. **`getUserContext()` (`context.ts:155-189`) & the Scoped `utils/claudemd.ts` Seam:** Loads `CLAUDE.md` plus a date-only string (`getLocalISODate()`, overridable via `CLAUDE_CODE_OVERRIDE_DATE` at `constants/common.ts:6`—commented as an ant-only override on `constants/common.ts:5`, though unchecked by `USER_TYPE` in code).

   At midnight, `messages[0]` deliberately stays stale while `getDateChangeAttachments()` (`utils/attachments.ts:1402-1444`, tracking `lastEmittedDate` in `bootstrap/state.ts:204-205`) appends a `date_change` attachment at the conversation **tail**—saving `~920K effective tokens per midnight crossing per overnight session` (`utils/attachments.ts:1411`). (`CLAUDE_CODE_SIMPLE` uses separately memoized `getSessionStartDate()` at `constants/common.ts:17-24`.)

```ts
// context.ts:165-187
    const shouldDisableClaudeMd =
      isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_CLAUDE_MDS) ||
      (isBareMode() && getAdditionalDirectoriesForClaudeMd().length === 0)
    // ...
    const claudeMd = shouldDisableClaudeMd
      ? null
      : getClaudeMds(filterInjectedMemoryFiles(await getMemoryFiles()))
    // ... caches claudeMd for yoloClassifier.ts without importing claudemd.ts
    setCachedClaudeMdContent(claudeMd || null)
    // ...
    return {
      ...(claudeMd && { claudeMd }),
      currentDate: `Today's date is ${getLocalISODate()}.`,
    }
```

In Chapter 04, [`utils/claudemd.ts`](../../utils/claudemd.ts) (1,479 lines) stays tightly scoped to this three-stage injection seam:

- **`getMemoryFiles()` (`utils/claudemd.ts:790-1075`):** Inner `memoize` loading Managed, User, Project, Local, `--add-dir` (opt-in via `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD`), `AutoMem`, and `TeamMem` (under `feature('TEAMMEM')` and GrowthBook `'tengu_herring_clock'`).
- **`filterInjectedMemoryFiles()` (`utils/claudemd.ts:1142-1151`):** Strips `AutoMem`/`TeamMem` under GrowthBook `'tengu_moth_copse'` when prefetch attachments replace them.
- **`getClaudeMds()` (`utils/claudemd.ts:1153-1195`):** Skips `Project`/`Local` under GrowthBook `'tengu_paper_halyard'`, wraps `TeamMem` in `<team-memory-content source="shared">` under `feature('TEAMMEM')`, and prepends `MEMORY_INSTRUCTION_PROMPT` (`utils/claudemd.ts:89-90`).

Note that `MAX_MEMORY_CHARACTER_COUNT = 40000` (`utils/claudemd.ts:92`) is an **advisory** UI warning threshold—unlike `AutoMem`/`TeamMem`, `CLAUDE.md` is not hard-truncated here. Hierarchical discovery, nested worktree dedup (`#29599`), `@include` recursion, HTML comment stripping, YAML `paths:` rules, and nested injection live in [Chapter 10](10-memory-systems-claudemd-auto-memory-and-dream.md).

### Hidden Invariants & Production Scars

- **The 4-hop `CLAUDE.md` cycle breaker (`context.ts:176`):** `utils/claudemd.ts:77` imports `pathInWorkingPath` from `utils/permissions/filesystem.ts`, which imports `getRuleByContentsForToolName` from `utils/permissions/permissions.ts` (`utils/permissions/filesystem.ts:49`), which imports `classifyYoloAction` from `utils/permissions/yoloClassifier.ts` (`utils/permissions/permissions.ts:102-105`).

  Writing `setCachedClaudeMdContent(claudeMd || null)` into [Chapter 01](01-atoms-types-stores-and-primitives.md)'s leaf store (`bootstrap/state.ts:1207-1209`) lets `utils/permissions/yoloClassifier.ts:460-477` read `getCachedClaudeMdContent()` (`bootstrap/state.ts:1211-1213`) without closing the cycle.

- **No `clearContextCaches` export & the nested-memoize trap:** `context.ts` exports no central reset helper; callers invoke `.cache.clear?.()` directly, and each lifecycle event clears a distinct slice:
  - **Full reset (`/clear`):** `clearSessionCaches()` (`commands/clear/caches.ts:52-55`, `commands/clear/caches.ts:66`, `commands/clear/caches.ts:69`, `commands/clear/caches.ts:74`, and `commands/clear/caches.ts:84`) wipes all four memoized caches (`getUserContext`, `getSystemContext`, `getGitStatus`, `getSessionStartDate`), clears `systemPromptInjection` and `lastEmittedDate`, runs `runPostCompactCleanup()`, and re-arms memory hooks with `'session_start'`.
  - **Compaction reset:** `services/compact/postCompactCleanup.ts:36-61` (and manual `/compact` at `commands/compact/compact.ts:63`, `commands/compact/compact.ts:117`, and `commands/compact/compact.ts:203`) clears outer `getUserContext.cache` alongside inner `resetGetMemoryFilesCache('compact')`—leaving `getGitStatus`/`getSystemContext` frozen—and gates both on `isMainThreadCompact` (`services/compact/postCompactCleanup.ts:36-39`) so compacting subagents cannot clobber main-thread caches.
  - **The nested-memoize trap:** Clearing only inner `getMemoryFiles` fails silently because the next turn hits outer `getUserContext.cache` and never fires `InstructionsLoaded`. Correctness-only callers (worktrees, settings sync, `/memory`) call silent `clearMemoryFileCaches()` (`utils/claudemd.ts:1119-1122`) rather than hook-arming `resetGetMemoryFilesCache()` (`utils/claudemd.ts:1124-1130`).

- **Import-DAG isolation via [`utils/queryContext.ts`](../../utils/queryContext.ts) (179 lines):** `constants/prompts.ts:26` imports `getSkillToolCommands` from `commands.ts`, which already reaches `utils/systemPrompt.ts` and `utils/sideQuestion.ts`. Hoisting `fetchSystemPromptParts()` (`utils/queryContext.ts:44-74`) and `buildSideQuestionFallbackParams()` (`utils/queryContext.ts:88-179`) into an entrypoint-only module (imported solely by `QueryEngine.ts:72` and `cli/print.ts:152`) avoids cycles.

  `fetchSystemPromptParts()` returns the three raw parts (skipping `getSystemPrompt()` and `getSystemContext()` when `customSystemPrompt !== undefined`, while still calling `getUserContext()`), and headless/SDK callers (`QueryEngine.ts:321-325` and `utils/queryContext.ts:127-132`) construct `asSystemPrompt([...])` directly instead of calling `buildEffectiveSystemPrompt()`.

  *(Snapshot note: `types/message.ts`, imported at `utils/queryContext.ts:19`, is absent from this checkout and observed via call sites such as `last.message.stop_reason === null` at `utils/queryContext.ts:138`.)*

---

## 2. The Prompt Section Registry & the Scary Function Name (`constants/systemPromptSections.ts`)

### The Problem

Dynamic sections after `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` still sit inside the prefix hashed by org-scoped message cache breakpoints on subsequent turns. Any feature that recomputes prompt text from mutable runtime state silently busts every cached token after it with zero errors.

### The Mechanism: Memoize by Default, Force Review Friction to Opt Out

[`constants/systemPromptSections.ts`](../../constants/systemPromptSections.ts) (68 lines) defaults to `systemPromptSection(name, compute)` (`constants/systemPromptSections.ts:20-25`, setting `cacheBreak: false`) and makes opting out loud and auditable via `DANGEROUS_uncachedSystemPromptSection(name, compute, _reason)`:

```ts
// constants/systemPromptSections.ts:32-68
export function DANGEROUS_uncachedSystemPromptSection(
  name: string,
  compute: ComputeFn,
  _reason: string,
): SystemPromptSection {
  return { name, compute, cacheBreak: true }
}
// ...
export async function resolveSystemPromptSections(
  sections: SystemPromptSection[],
): Promise<(string | null)[]> {
  const cache = getSystemPromptSectionCache()

  return Promise.all(
    sections.map(async s => {
      if (!s.cacheBreak && cache.has(s.name)) {
        return cache.get(s.name) ?? null
      }
      const value = await s.compute()
      setSystemPromptSectionCacheEntry(s.name, value)
      return value
    }),
  )
}
// ...
export function clearSystemPromptSections(): void {
  clearSystemPromptSectionState()
  clearBetaHeaderLatches()
}
```

Three design choices make this 68-line file load-bearing:
1. **`_reason: string` is pure compile-time friction:** The leading underscore tells the whole story—`_reason` is **never logged, stored, or read at runtime**. Contributors must justify cache-breaking directly in code review.
2. **Negative `null` caching:** Checking `cache.has(s.name)` against `STATE.systemPromptSectionCache` (`bootstrap/state.ts:202-203` and `bootstrap/state.ts:1641-1654`) caches `null` results too, preventing a mid-session flag flip from suddenly injecting a new section.
3. **Paired beta-latch invalidation (`clearSystemPromptSections`):** Resetting sections simultaneously calls `clearBetaHeaderLatches()` (`bootstrap/state.ts:1744-1749`), clearing all **four** sticky-on latches pinned by `services/api/claude.ts:1412-1456` (`afkModeHeaderLatched`, `fastModeHeaderLatched`, `cacheEditingHeaderLatched`, `thinkingClearLatched`; note minor comment drift at `constants/systemPromptSections.ts:63`, which names only three).

   Because dropping a beta header mid-session busts ~50–70K cached tokens, both surfaces reset together across six explicit invalidation sites: `services/compact/postCompactCleanup.ts:62` (`/clear`, `/compact`, auto-compact, partial compact), `utils/sessionRestore.ts:364`, `utils/sessionRestore.ts:388`, `tools/EnterWorktreeTool/EnterWorktreeTool.ts:99`, `tools/ExitWorktreeTool/ExitWorktreeTool.ts:143`, and `setup.ts:346` (ant startup check once `isInternalModelRepo()` clears undercover redaction).

> [!WARNING]
> **Two production scars prove the friction works:**
> 1. **Only ONE active call site remains:** `'mcp_instructions'` at `constants/prompts.ts:513-520` (`_reason = 'MCP servers connect/disconnect between turns'`), itself migrating to persisted `mcp_instructions_delta` attachments under `isMcpInstructionsDeltaEnabled()` (`CLAUDE_CODE_MCP_INSTR_DELTA`, else `process.env.USER_TYPE === 'ant'` or GrowthBook `'tengu_basalt_3kr'` in `utils/mcpInstructionsDelta.ts:37-44`).
>
>    Notice `constants/systemPromptSections.ts:54`: `resolveSystemPromptSections()` still calls `setSystemPromptSectionCacheEntry()` even for `cacheBreak: true`! That explains `constants/prompts.ts:511-512`—keeping the gate check *inside* `compute` avoids hitting a stale turn-1 entry if a descriptor switched from `DANGEROUS_uncached` to `systemPromptSection` mid-session.
> 2. **`token_budget` (`constants/prompts.ts:538-551`, `feature('TOKEN_BUDGET')`):** Formerly `DANGEROUS_uncached`, busting ~20K tokens per toggle; refactored into an unconditional cached section phrased as a conditional no-op (`"When the user specifies a token target..."`) because tail attachments weren't visible on first-response/continuation paths (`#21577`).

---

## 3. Static vs. Dynamic Split & the Branded Priority Cascade (`constants/prompts.ts`, `utils/systemPromptType.ts`, `utils/systemPrompt.ts`)

### The Problem

Keeping dynamic sections session-stable still leaves two hazards: runtime booleans before the global cache breakpoint fracture cross-org `scope: 'global'` prefixes across `2^N` variants, and overlapping prompt sources (`--system-prompt`, `--append-system-prompt`, `--agent`, coordinator, proactive, override) need a deterministic, type-safe precedence rule.

### The Mechanism: `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` (`constants/prompts.ts`)

`getSystemPrompt()` (`constants/prompts.ts:444-577`) first checks two boundary-less short-circuits: `isEnvTruthy(process.env.CLAUDE_CODE_SIMPLE)` (`constants/prompts.ts:450-454`) and proactive mode (`(feature('PROACTIVE') || feature('KAIROS')) && proactiveModule?.isProactiveActive()` at `constants/prompts.ts:466-489`). Otherwise, it splits assembly around `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` (`'__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__'`, `constants/prompts.ts:114-115`):

- **7 static cross-org slots (pre-boundary):** `getSimpleIntroSection`, `getSimpleSystemSection`, conditional `getSimpleDoingTasksSection` (four `process.env.USER_TYPE === 'ant'` blocks and `MACRO.ISSUES_EXPLAINER`), and `getActionsSection`, followed by three tool/style slots:
  - `getUsingYourToolsSection` (`constants/prompts.ts:277` and `constants/prompts.ts:289`, branching on `isReplModeEnabled()` and `hasEmbeddedSearchTools()` / `EMBEDDED_SEARCH_TOOLS`), `getSimpleToneAndStyleSection` (`constants/prompts.ts:433`, omitting the conciseness line when `USER_TYPE === 'ant'`), and `getOutputEfficiencySection` (branching on `USER_TYPE === 'ant'`).
- **10 baseline dynamic sections (post-boundary):** `session_guidance`, `memory`, `ant_model_override` (`constants/prompts.ts:136-140`, gated on `USER_TYPE === 'ant'` and `!isUndercover()`), `env_info_simple`, `language`, `output_style`, `mcp_instructions`, `scratchpad` (Statsig `'tengu_scratch'`), `frc` (`feature('CACHED_MICROCOMPACT')`), and `summarize_tool_results`.
- **Up to 3 additional gated dynamic sections:** `numeric_length_anchors` (`USER_TYPE === 'ant'`), `token_budget` (`feature('TOKEN_BUDGET')`), and `brief` (`feature('KAIROS') || feature('KAIROS_BRIEF')`):

```ts
// constants/prompts.ts:513-576
    DANGEROUS_uncachedSystemPromptSection(
      'mcp_instructions',
      () =>
        isMcpInstructionsDeltaEnabled()
          ? null
          : getMcpInstructionsSection(mcpClients),
      'MCP servers connect/disconnect between turns',
    ),
// ...
  return [
    // --- Static content (cacheable) ---
    getSimpleIntroSection(outputStyleConfig),
    getSimpleSystemSection(),
    outputStyleConfig === null ||
    outputStyleConfig.keepCodingInstructions === true
      ? getSimpleDoingTasksSection()
      : null,
    getActionsSection(),
    getUsingYourToolsSection(enabledTools),
    getSimpleToneAndStyleSection(),
    getOutputEfficiencySection(),
    // === BOUNDARY MARKER - DO NOT MOVE OR REMOVE ===
    ...(shouldUseGlobalCacheScope() ? [SYSTEM_PROMPT_DYNAMIC_BOUNDARY] : []),
    // --- Dynamic content (registry-managed) ---
    ...resolvedDynamicSections,
  ].filter(s => s !== null)
```

To stop `2^N` Blake2b prefix-hash fragmentation (citing PR `#24490` and `#24171`), `getSessionSpecificGuidanceSection()` (`constants/prompts.ts:343-400`) quarantines runtime booleans post-boundary:

- **Interactive & subagent toggles:** `AskUserQuestion`, interactive `! <command>`, `isForkSubagentEnabled()` (`feature('FORK_SUBAGENT')`, interactive non-coordinator only — `tools/AgentTool/forkSubagent.ts:32-39`), and `areExplorePlanAgentsEnabled()` (`feature('BUILTIN_EXPLORE_PLAN_AGENTS')` + GrowthBook `'tengu_amber_stoat'`).
- **Skills & verification toggles:** `hasSkills` (from Chapter 03's `getSkillToolCommands()` at `constants/prompts.ts:26` and `constants/prompts.ts:458`), `DiscoverSkills`, and `feature('VERIFICATION_AGENT')` + GrowthBook `'tengu_hive_evidence'`.

> [!IMPORTANT]
> **Gating `constants/prompts.ts:573` on `shouldUseGlobalCacheScope()` is load-bearing:** `shouldUseGlobalCacheScope()` (`utils/betas.ts:227-232`) holds only when `getAPIProvider() === 'firstParty' && !isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS)` (excluding Bedrock, Vertex, and Foundry). Branch 3 of `splitSysPromptPrefix()` (`utils/api.ts:411-435`) does **not** strip the sentinel—emitting it on 3P providers or with betas disabled would leak `'__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__'` straight to the model.

> [!NOTE]
> **Snapshot absences & stripped imports in `constants/prompts.ts`:** Four DCE-gated `require(...)` imports (`constants/prompts.ts:66-97`) are **absent from this snapshot** and observed via call sites only: `services/compact/cachedMCConfig.js` (`feature('CACHED_MICROCOMPACT')`), `proactive/index.js` (`feature('PROACTIVE') || feature('KAIROS')`), `tools/DiscoverSkillsTool/prompt.js`, and `services/skillSearch/featureCheck.js` (`feature('EXPERIMENTAL_SKILL_SEARCH')`).
>
> Separately, `constants/prompts.ts:139` calls `getAntModelOverrideConfig()` without an import line due to stripped `ANT-ONLY` markers (`constants/prompts.ts:1`); its definition is present at [`utils/model/antModels.ts`](../../utils/model/antModels.ts) (`utils/model/antModels.ts:34-42`, reading GrowthBook `'tengu_ant_model_override'`).

### Branded Leaf & Five-Tier Cascade (`utils/systemPromptType.ts`, `utils/systemPrompt.ts`)

[`utils/systemPromptType.ts`](../../utils/systemPromptType.ts) (14 lines) isolates `SystemPrompt = readonly string[] & { readonly __brand: 'SystemPrompt' }` and `asSystemPrompt()` with **zero imports**. **33 modules** import it—including `Tool.ts:61` (`ToolUseContext.renderedSystemPrompt` at `Tool.ts:299`, freezing parent prompt bytes for fork subagents)—while [`utils/systemPrompt.ts`](../../utils/systemPrompt.ts) imports `ToolUseContext` from `Tool.ts` (`utils/systemPrompt.ts:6`), breaking circular initialization.

`buildEffectiveSystemPrompt()` (`utils/systemPrompt.ts:41-123`) resolves interactive/compaction/agent precedence across five tiers:

```ts
// utils/systemPrompt.ts:56-122
  if (overrideSystemPrompt) {
    return asSystemPrompt([overrideSystemPrompt])
  }
  // ... Coordinator mode (inline env check + lazy require)
  if (
    feature('COORDINATOR_MODE') &&
    isEnvTruthy(process.env.CLAUDE_CODE_COORDINATOR_MODE) &&
    !mainThreadAgentDefinition
  ) {
    // ... returns [getCoordinatorSystemPrompt(), ...append]
  }
  // ... compute agentSystemPrompt via isBuiltInAgent() & log tengu_agent_memory_loaded
  if (
    agentSystemPrompt &&
    (feature('PROACTIVE') || feature('KAIROS')) &&
    isProactiveActive_SAFE_TO_CALL_ANYWHERE()
  ) {
    return asSystemPrompt([
      ...defaultSystemPrompt,
      `\n# Custom Agent Instructions\n${agentSystemPrompt}`,
      ...(appendSystemPrompt ? [appendSystemPrompt] : []),
    ])
  }

  return asSystemPrompt([
    ...(agentSystemPrompt
      ? [agentSystemPrompt]
      : customSystemPrompt
        ? [customSystemPrompt]
        : defaultSystemPrompt),
    ...(appendSystemPrompt ? [appendSystemPrompt] : []),
  ])
```

| Tier | Trigger (`utils/systemPrompt.ts`) | Output Shape | `appendSystemPrompt`? | Global Boundary Kept? |
|---|---|---|---|---|
| **0. Override** | `overrideSystemPrompt` (`utils/systemPrompt.ts:56-58`; no live caller in snapshot—observed via JSDoc/contract) | `[overrideSystemPrompt]` | **No** (dropped) | No |
| **1. Coordinator** | `feature('COORDINATOR_MODE') && CLAUDE_CODE_COORDINATOR_MODE && !mainThreadAgentDefinition` (`utils/systemPrompt.ts:62-75`) | `[getCoordinatorSystemPrompt(), ...append]` | Yes | No |
| **2a. Agent (Proactive)** | `agentSystemPrompt` + `(feature('PROACTIVE') \|\| feature('KAIROS')) && isProactiveActive_SAFE_TO_CALL_ANYWHERE()` (`utils/systemPrompt.ts:103-113`) | `[...defaultSystemPrompt, '\n# Custom Agent Instructions\n' + agentSystemPrompt, ...append]` | Yes | No |
| **2b. Agent (Standard)** | `agentSystemPrompt` non-proactive (`utils/systemPrompt.ts:116-117`) | `[agentSystemPrompt, ...append]` | Yes | No |
| **3. Custom** | `customSystemPrompt` (`--system-prompt`, `utils/systemPrompt.ts:118-119`) | `[customSystemPrompt, ...append]` | Yes | No |
| **4. Default** | Fallback (`utils/systemPrompt.ts:120`) | `[...defaultSystemPrompt, ...append]` | Yes | **Yes** (1P + betas on) |

Three invariants stand out:

1. **`--agent` beats Coordinator mode:** `!mainThreadAgentDefinition` (`utils/systemPrompt.ts:65`) ensures explicit agent selection takes precedence if both are set.
2. **Proactive mode appends rather than replacing:** Custom agents inherit the `<tick>`/`Sleep` autonomous skeleton (`proactive/index.js` is absent from this snapshot and observed via `utils/systemPrompt.ts:18-26` and `utils/systemPrompt.ts:106`).
3. **Built-in vs. markdown agent arity:** `isBuiltInAgent()` (`utils/systemPrompt.ts:77-83`) passes `{ toolUseContext: { options } }` to built-in agents but invokes custom/plugin markdown closures with zero arguments (logging `tengu_agent_memory_loaded` with `USER_TYPE === 'ant'`-gated `agent_type` at `utils/systemPrompt.ts:86-97`).

Whenever Tiers 0, 1, 2b, or 3 replace `defaultSystemPrompt`, `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` disappears and `splitSysPromptPrefix()` automatically drops to org-level caching.

---

## 4. Wire-Prefix Splitting, Context Placement & Tool Schema Stability (`utils/api.ts`, `utils/toolSchemaCache.ts`)

### The Problem

Translating `SystemPrompt` and `Tool[]` onto the wire must preserve two constraints simultaneously: staying within Anthropic's four-breakpoint ceiling (`services/api/claude.ts:3221`) while excluding per-request billing headers (`constants/system.ts:52-91`, behind `CLAUDE_CODE_ATTRIBUTION_HEADER`, GrowthBook `'tengu_attribution_header'`, and `feature('NATIVE_CLIENT_ATTESTATION')`), and locking `tools[]`—which hashes **before** `system[]`—against mid-session GrowthBook flips or per-user MCP divergence.

### The Mechanism: Three Wire Branches, Split Context Injection & Schema Freezing

1. **`splitSysPromptPrefix()` (`utils/api.ts:321-435`):** Matches blocks by content (`x-anthropic-billing-header` and `CLI_SYSPROMPT_PREFIXES` from `constants/system.ts:26-28`) across three mutually exclusive branches:
   - **Branch 2 — Global Active (`utils/api.ts:362-405`):** When `shouldUseGlobalCacheScope()`, `!skipGlobalCacheForSystemPrompt`, and `boundaryIndex !== -1`, emits up to **4 blocks**: `attributionHeader` (`null`), `systemPromptPrefix` (`null`—covered by block 3's breakpoint to save a slot), `staticBlocks` (**`'global'`**), and `dynamicBlocks` (`null`), logging `tengu_sysprompt_boundary_found`.
   - **Branch 1 — MCP Tool-Based Fallback (`utils/api.ts:326-360`):** When `shouldUseGlobalCacheScope()` and `skipGlobalCacheForSystemPrompt` (any non-deferred MCP tool in `services/api/claude.ts:1212-1214` diverges `tools[]` before byte 0 of `system[]`), strips the sentinel (`utils/api.ts:338`), emits up to **3 blocks** (`null`, `'org'`, `'org'`), and logs `tengu_sysprompt_using_tool_based_cache`.
   - **Branch 3 — Default Org Fallback (`utils/api.ts:405-435`):** Reached on 3P providers (`bedrock`, `vertex`, `foundry`), `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS`, or missing boundary (logging `tengu_sysprompt_missing_boundary_marker` only when `shouldUseGlobalCacheScope()` is true); emits up to **3 blocks** (`null`, `'org'`, `'org'`) without stripping the sentinel.

```ts
// utils/api.ts:372-396
      for (let i = 0; i < systemPrompt.length; i++) {
        const block = systemPrompt[i]
        if (!block || block === SYSTEM_PROMPT_DYNAMIC_BOUNDARY) continue

        if (block.startsWith('x-anthropic-billing-header')) {
          attributionHeader = block
        } else if (CLI_SYSPROMPT_PREFIXES.has(block)) {
          systemPromptPrefix = block
        } else if (i < boundaryIndex) {
          staticBlocks.push(block)
        } else {
          dynamicBlocks.push(block)
        }
      }

      const result: SystemPromptBlock[] = []
      if (attributionHeader)
        result.push({ text: attributionHeader, cacheScope: null })
      if (systemPromptPrefix)
        result.push({ text: systemPromptPrefix, cacheScope: null })
      const staticJoined = staticBlocks.join('\n\n')
      if (staticJoined)
        result.push({ text: staticJoined, cacheScope: 'global' })
      const dynamicJoined = dynamicBlocks.join('\n\n')
      if (dynamicJoined) result.push({ text: dynamicJoined, cacheScope: null })
```

2. **Context placement & prefix logging:**
   - **`appendSystemContext()` (`utils/api.ts:437-447`, called at `query.ts:449-451`):** Appends `systemContext` (`gitStatus`, optional `cacheBreaker`) at the post-boundary dynamic tail and re-brands the array via `asSystemPrompt()`.
   - **`prependUserContext()` (`utils/api.ts:449-474`, called at `query.ts:660`; no-op in `NODE_ENV === 'test'` or when empty):** Wraps `userContext` (`claudeMd`, `currentDate`) via Chapter 03's `createUserMessage({ content: '<system-reminder>...', isMeta: true })` at `messages[0]`—keeping repo/date data out of global `system[]` while riding org message caching and hiding from UI.
   - **`logAPIPrefix()` (`utils/api.ts:281-294`, called at `services/api/claude.ts:1372`):** Logs a 20-char snippet, length, and SHA-256 hash of `splitSysPromptPrefix(systemPrompt)[0]` (`tengu_sysprompt_block`).

3. **Session-frozen tool schemas (`toolToAPISchema` at `utils/api.ts:119-266` + [`utils/toolSchemaCache.ts`](../../utils/toolSchemaCache.ts), 26 lines):** Because `tools[]` hashes before `system[]` (`utils/toolSchemaCache.ts:3-8`), `utils/toolSchemaCache.ts` holds a leaf `Map` (avoiding a `utils/auth.ts → utils/api.ts` cycle) caching the base schema (`name`, `description`, `input_schema`, `strict`, `eager_input_streaming`) per session:

```ts
// utils/api.ts:147-209
  const cacheKey =
    'inputJSONSchema' in tool && tool.inputJSONSchema
      ? `${tool.name}:${jsonStringify(tool.inputJSONSchema)}`
      : tool.name
  const cache = getToolSchemaCache()
  let base = cache.get(cacheKey)
  if (!base) {
    // ... build input_schema from inputJSONSchema or zodToJsonSchema, filter swarm fields
    // ... await tool.prompt(...) and attach strict: true under tengu_tool_pear + model support
    // Gated to direct api.anthropic.com: proxies (LiteLLM etc.) and Bedrock/Vertex
    // with Claude 4.5 reject this field with 400. See GH#32742, PR #21729.
    if (
      getAPIProvider() === 'firstParty' &&
      isFirstPartyAnthropicBaseUrl() &&
      (getFeatureValue_CACHED_MAY_BE_STALE('tengu_fgts', false) ||
        isEnvTruthy(process.env.CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING))
    ) {
      base.eager_input_streaming = true
    }

    cache.set(cacheKey, base)
  }
```

### Hidden Invariants & Production Scars

- **PR `#25424` `StructuredOutput` key collision (`utils/api.ts:142-150`):** Multiple `StructuredOutput` tool instances share one name with different per-workflow `inputJSONSchema` payloads; name-only caching spiked errors from 5.4% to 51%, solved by keying on `${tool.name}:${jsonStringify(tool.inputJSONSchema)}`.
- **Field gates & proxy allowlist:**
  - `strict: true` requires Statsig `'tengu_tool_pear'`, `tool.strict === true`, and `modelSupportsStructuredOutputs(options.model)` (`utils/api.ts:185-192`).
  - `eager_input_streaming: true` is locked to direct 1P `api.anthropic.com` plus GrowthBook `'tengu_fgts'` or `CLAUDE_CODE_ENABLE_FINE_GRAINED_TOOL_STREAMING` (`utils/api.ts:199-206`).
  - When `!isAgentSwarmsEnabled()` (`utils/agentSwarmsEnabled.ts:24-44`: `USER_TYPE === 'ant'` or `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS`/`--agent-teams` with GrowthBook `'tengu_amber_flint'`), `filterSwarmFieldsFromSchema()` strips `launchSwarm`/`teammateCount` (`ExitPlanMode`) and `name`/`team_name`/`mode` (`Agent`).
  - Per-request `defer_loading` and `cache_control` overlay onto a shallow copy (`utils/api.ts:215-230`), and `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` allowlist-strips all keys outside `['name', 'description', 'input_schema', 'cache_control']` (`utils/api.ts:243-260`, logging once via `logStripOnce`).
- **Reciprocal Ch 03 seam (`normalizeToolInputForAPI`, `utils/api.ts:685-718`):** Called from Chapter 03's `normalizeMessagesForAPI` (`utils/messages.ts:2215`), this strips local fields injected by `normalizeToolInput()` (`utils/api.ts:566-681`: `plan`/`planFilePath` on `ExitPlanMode`, legacy pre-PR `#20357` `old_string`/`new_string`/`replace_all` on `FileEditTool`) before re-sending history.

---

## 5. Cache-Break Forensics in Production (`services/api/promptCacheBreakDetection.ts`)

### The Problem

Cache regressions fail silently—and blaming every drop in `cache_read_input_tokens` on client bugs wastes weeks chasing TTL expirations, intentional compaction, or server-side evictions.

### The Mechanism: Two-Phase State Diffing & Root-Cause Attribution

[`services/api/promptCacheBreakDetection.ts`](../../services/api/promptCacheBreakDetection.ts) (727 lines) pairs pre-call `recordPromptState()` (`services/api/promptCacheBreakDetection.ts:247-430`) with post-call `checkResponseForCacheBreak()` (`services/api/promptCacheBreakDetection.ts:437-666`).

Active callers are compile-time gated by `feature('PROMPT_CACHE_BREAK_DETECTION')` (`services/api/claude.ts:1460` and `services/api/claude.ts:2383`), except `resetPromptCacheBreakDetection()` (`commands/clear/caches.ts:63`), which runs ungated behind `if (!hasPreserved)` so `/clear` preserves active background agents' baselines.

*(Snapshot note: type-only imports `types/message.ts` at `services/api/promptCacheBreakDetection.ts:7` and `constants/querySource.ts` at `services/api/promptCacheBreakDetection.ts:13` are absent from this checkout; observed `QuerySource` values include `'repl_main_thread'`, `'sdk'`, `'compact'`, `'agent:custom'`, `'agent:default'`, and `'agent:builtin'`.)*

- **Phase 1 (`recordPromptState`):**
  - **12 orthogonal dimensions:** Hashes stripped `systemHash`, stripped `toolsHash`, separate `cacheControlHash` (`system.map(b => b.cache_control)` to catch `global↔org` and `1h↔5m` flips), `model`, `fastMode`, `globalCacheStrategy`, sorted `betas`, `autoModeActive`, `isUsingOverage`, `cachedMCEnabled`, `effortValue`, and `extraBodyHash` using `Bun.hash` (32-bit masked, `djb2Hash` fallback on Node.js at `services/api/promptCacheBreakDetection.ts:170-179`).
  - **Server-accurate inputs:** At `services/api/claude.ts:1465-1485`, `defer_loading` tools are filtered out (omitted from the server's cache key) and latched beta states are passed.
  - **Per-tool schema diffing:** After seeding `perToolHashes` eagerly on call #1 (`services/api/promptCacheBreakDetection.ts:325`), `computePerToolHashes()` (`services/api/promptCacheBreakDetection.ts:187-196`) runs lazily on subsequent turns only when `toolsHash` changes (`services/api/promptCacheBreakDetection.ts:369-378`)—diagnosing the 77% of tool breaks where the tool set itself didn't change.
- **Phase 2 (`checkResponseForCacheBreak`):** Excludes Haiku (`services/api/promptCacheBreakDetection.ts:129-131`), skips call #1, suppresses expected drops from `notifyCacheDeletion()` (`services/compact/microCompact.ts:366` and `services/compact/microCompact.ts:526`), and resets baselines on `notifyCompaction()` (`services/compact/compact.ts:699`, `services/compact/compact.ts:1048`, `services/compact/autoCompact.ts:303`, and `commands/compact/compact.ts:68`).

  Breaks require both a `> 5%` relative drop and `>= MIN_CACHE_MISS_TOKENS` (`2_000`, `services/api/promptCacheBreakDetection.ts:120`):

```ts
// services/api/promptCacheBreakDetection.ts:473-588
    if (state.cacheDeletionsPending) {
      state.cacheDeletionsPending = false
      // ... logs expected drop and clears pendingChanges
      return
    }
    // ... check >5% relative drop AND >= MIN_CACHE_MISS_TOKENS (2_000)
    const tokenDrop = prevCacheRead - cacheReadTokens
    if (
      cacheReadTokens >= prevCacheRead * 0.95 ||
      tokenDrop < MIN_CACHE_MISS_TOKENS
    ) {
      state.pendingChanges = null
      return
    }
    // ... build parts[] across 12 client flags
    let reason: string
    if (parts.length > 0) {
      reason = parts.join(', ')
    } else if (lastAssistantMsgOver1hAgo) {
      reason = 'possible 1h TTL expiry (prompt unchanged)'
    } else if (lastAssistantMsgOver5minAgo) {
      reason = 'possible 5min TTL expiry (prompt unchanged)'
    } else if (timeSinceLastAssistantMsg !== null) {
      reason = 'likely server-side (prompt unchanged, <5min gap)'
    } else {
      reason = 'unknown cause'
    }
```

### Hidden Invariants & Failure Modes

- **5-tier attribution cascade:** Client flags win (suppressing standalone `'cache_control changed (scope or TTL)'` at `services/api/promptCacheBreakDetection.ts:527-535` when `globalCacheStrategyChanged` or `systemPromptChanged` already explains it), then 1h TTL (`CACHE_TTL_1HOUR_MS`), 5m TTL (`CACHE_TTL_5MIN_MS`), server-side `<5min`, and unknown.
- **Telemetry privacy hygiene:** Before logging `tengu_prompt_cache_break` (`services/api/promptCacheBreakDetection.ts:590-644`), `sanitizeToolName()` (`services/api/promptCacheBreakDetection.ts:183-185`) collapses `mcp__*` to `'mcp'` to prevent filepath leaks.
- **Unified diff files:** On client-caused breaks, `writeCacheBreakDiff()` (`services/api/promptCacheBreakDetection.ts:708-727`) writes a unified patch to `<getClaudeTempDir()>/cache-break-xxxx.diff` (`services/api/promptCacheBreakDetection.ts:19-26`) with **no** internal `USER_TYPE`/`--debug` check—caller-side `feature('PROMPT_CACHE_BREAK_DETECTION')` gates it, while the path surfaces via `logForDebugging(..., { level: 'warn' })`.
- **FIFO eviction (not LRU) & crash isolation:** `previousStateBySource` enforces `MAX_TRACKED_SOURCES = 10` (`services/api/promptCacheBreakDetection.ts:107` and `services/api/promptCacheBreakDetection.ts:300-303`) via `Map` insertion-order **FIFO** eviction while retaining a lazy `buildDiffableContent` closure; subagents clean up on exit via `cleanupAgentTracking()` (`tools/AgentTool/runAgent.ts:825`), and both phases catch all errors via `try/catch` (`logError`).

---

## Putting the Layer Together

```text
Anthropic API Request Prefix Order (Cache Key Hashes Top -> Bottom)
+-------------------------------------------------------------------------+
| 1. tools[]          [sorted built-ins] ++ [sorted MCPs]                 |
|                     memoized via getToolSchemaCache() (utils/api.ts)    |
|                     * any non-deferred MCP -> skipGlobalCache = true    |
+-------------------------------------------------------------------------+
| 2. system[] (splitSysPromptPrefix -> buildSystemPromptBlocks)           |
|    [0] x-anthropic-billing-header     cacheScope: null                  |
|    [1] CLI_SYSPROMPT_PREFIX           cacheScope: null (global) / 'org' |
|    [2] Static instructions            cacheScope: 'global'  <-- BP #1   |
|    --- SYSTEM_PROMPT_DYNAMIC_BOUNDARY (stripped on wire) ---            |
|    [3] Dynamic sections + gitStatus   cacheScope: null (uncached tail)  |
+-------------------------------------------------------------------------+
| 3. messages[]                                                           |
|    [0] prependUserContext()           isMeta: true <system-reminder>    |
|        (CLAUDE.md + currentDate)      memoized per conversation         |
|    [1..N] Stage 1 normalized history  (Ch 03 -> Ch 05 wire conversion)  |
+-------------------------------------------------------------------------+
```

```mermaid
flowchart TD
    CMD["utils/claudemd.ts: getMemoryFiles() -> getClaudeMds()"]
    CTX["context.ts: getGitStatus() / getSystemContext() / getUserContext()"]
    STATE["bootstrap/state.ts: cachedClaudeMdContent & section cache"]
    SECS["constants/systemPromptSections.ts: resolveSystemPromptSections()"]
    PROMPTS["constants/prompts.ts: getSystemPrompt() + DYNAMIC_BOUNDARY"]
    EFF["utils/systemPrompt.ts & utils/queryContext.ts: resolve SystemPrompt"]
    QUERY["query.ts: appendSystemContext() & prependUserContext()"]
    API["services/api/claude.ts: toolToAPISchema() & buildSystemPromptBlocks()"]
    SPLIT["utils/api.ts: splitSysPromptPrefix() & getToolSchemaCache()"]
    DET["services/api/promptCacheBreakDetection.ts: record -> check"]
    LLM["Anthropic API Stream"]
    CMD --> CTX
    CTX -->|"setCachedClaudeMdContent()"| STATE
    SECS <--> STATE
    SECS --> PROMPTS
    PROMPTS --> EFF
    CTX --> EFF
    EFF -->|"branded SystemPrompt"| QUERY
    CTX -->|"systemContext & userContext"| QUERY
    QUERY --> API
    API <--> SPLIT
    API -->|"Phase 1: recordPromptState()"| DET
    API --> LLM
    LLM -->|"Phase 2: checkResponseForCacheBreak()"| DET
```

---

## How This Snaps Into the Next Layer

Everything in Chapter 04 plugs directly into [`services/api/claude.ts`](../../services/api/claude.ts) ([Chapter 05: Talking to the Model](05-talking-to-the-model.md)):

- `toolToAPISchema()` serializes `filteredTools` in parallel (`services/api/claude.ts:1235-1246`), while `needsToolBasedCacheMarker` (`services/api/claude.ts:1212-1214`) detects non-deferred MCP tools to flip `skipGlobalCacheForSystemPrompt`.
- `services/api/claude.ts:1358-1379` prepends `getAttributionHeader()` and `getCLISyspromptPrefix()`, calls `logAPIPrefix(systemPrompt)` (`services/api/claude.ts:1372`), and computes `enablePromptCaching` (`services/api/claude.ts:1374-1375`) via `getPromptCachingEnabled()` (`services/api/claude.ts:333-356`, honoring `DISABLE_PROMPT_CACHING`, `DISABLE_PROMPT_CACHING_HAIKU`, `DISABLE_PROMPT_CACHING_SONNET`, and `DISABLE_PROMPT_CACHING_OPUS`).
- `buildSystemPromptBlocks()` (`services/api/claude.ts:3213-3237`, carrying the HTTP 400 breakpoint warning at `services/api/claude.ts:3221`) maps `splitSysPromptPrefix()` blocks onto `getCacheControl()` / `should1hCacheTTL()` (`services/api/claude.ts:358-434`).
  - `getCacheControl()` omits `scope` for `'org'`, while `should1hCacheTTL()` attaches 1h TTL via `ENABLE_PROMPT_CACHING_1H_BEDROCK` (`services/api/claude.ts:396-401`) on Bedrock, or via latched `process.env.USER_TYPE === 'ant'` / non-overage subscriber eligibility (`services/api/claude.ts:406-413`) plus the latched GrowthBook `'tengu_prompt_cache_1h_config'` allowlist.
- Right before streaming, `services/api/claude.ts:1412-1486` pins the four sticky beta latches and calls `recordPromptState()` under `feature('PROMPT_CACHE_BREAK_DETECTION')`; right after streaming completes, `services/api/claude.ts:2383-2392` calls `checkResponseForCacheBreak()`.
- Two forward seams connect later layers back here: [Chapter 09](09-five-layer-compaction-pipeline.md) drives `runPostCompactCleanup()`, `notifyCacheDeletion()`, and `notifyCompaction()`, while [Chapter 10](10-memory-systems-claudemd-auto-memory-and-dream.md) unpacks full `utils/claudemd.ts` discovery, `@include` expansion, conditional rules, and auto-memory prefetch.

---

## Reading Exercises & Code Checkpoints

1. **Trace `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` from producer to wire splitter:**
   Run `rg -n "SYSTEM_PROMPT_DYNAMIC_BOUNDARY" constants/prompts.ts utils/api.ts utils/analyzeContext.ts` and verify why Branch 1 (`utils/api.ts:338`) and Branch 2 (`utils/api.ts:374`) strip the sentinel while Branch 3 (`utils/api.ts:415-425`) relies on `shouldUseGlobalCacheScope()` never emitting it.
2. **Audit every uncached section and section-reset site:**
   Run `rg -n "DANGEROUS_uncachedSystemPromptSection|clearSystemPromptSections" constants/ services/ utils/ tools/ setup.ts` to confirm only `'mcp_instructions'` remains uncached and trace all six `clearSystemPromptSections()` callers.
3. **Verify the `cachedClaudeMdContent` cycle breaker and git-cache reset:**
   Run `rg -n "setCachedClaudeMdContent|getCachedClaudeMdContent|getGitStatus\.cache" context.ts bootstrap/state.ts utils/permissions/yoloClassifier.ts commands/clear/caches.ts` and check why compaction clears `getUserContext.cache` without clearing `getGitStatus.cache`.
4. **Map the full `PROMPT_CACHE_BREAK_DETECTION` lifecycle:**
   Run `rg -n "recordPromptState|checkResponseForCacheBreak|notifyCacheDeletion|notifyCompaction|cleanupAgentTracking|resetPromptCacheBreakDetection" services/ commands/ tools/` and compare which call sites are gated by `feature('PROMPT_CACHE_BREAK_DETECTION')` versus ungated.


---

<!-- chapters/05-talking-to-the-model.md — https://reverseengineeringclaudecode.com/chapters/05-talking-to-the-model -->

# Chapter 05 — Talking to the Model: API Client, Streaming, Retries, and Accounting

> **Layer:** Layer 2 (The Agent Engine)
> **Prerequisites:** [Chapter 01](01-atoms-types-stores-and-primitives.md), [Chapter 02](02-the-tool-contract.md), [Chapter 03](03-command-and-message-contracts.md), [Chapter 04](04-prompt-engineering-and-cache-boundaries.md)
> **Primary Source Files:**
> - [`services/api/claude.ts`](../../services/api/claude.ts) — Stage 2 wire conversion, cache breakpoints, sticky beta latches, raw SSE streaming, dual fallback, usage merging (3,419 lines)
> - [`services/api/client.ts`](../../services/api/client.ts) — four-provider SDK factory (1P, Bedrock, Foundry, Vertex), auth refresh, proxy/keepalive wiring, `x-client-request-id` (389 lines)
> - [`services/api/withRetry.ts`](../../services/api/withRetry.ts) — `AsyncGenerator` retry loop, backoff/jitter, credential refresh, `UNATTENDED_RETRY`, `FallbackTriggeredError` (822 lines)
> - [`services/api/errors.ts`](../../services/api/errors.ts) — analytics error taxonomy, SDK retry categorizer, refusal handler, synthetic `AssistantMessage` error factory (1,207 lines)
> - [`services/api/usage.ts`](../../services/api/usage.ts) — claude.ai `/api/oauth/usage` quota utilization client with 5-second timeout (63 lines)
> - [`cost-tracker.ts`](../../cost-tracker.ts) — process-wide USD ledger in `bootstrap/state.ts`, OTel counters, recursive advisor billing, single-slot session restore (323 lines)
> - [`utils/model/model.ts`](../../utils/model/model.ts) — model precedence, canonicalization, 1M merge guard, legacy remap, API string normalization (618 lines)
> - [`utils/thinking.ts`](../../utils/thinking.ts) — `ThinkingConfig`, provider thinking/adaptive-thinking capabilities, `ULTRATHINK` dual gate, `MAX_THINKING_TOKENS` (162 lines)
> - [`utils/effort.ts`](../../utils/effort.ts) — `EFFORT_LEVELS`, ant-only numeric effort, persistence bounds, `resolveAppliedEffort`, `tengu_grey_step2` (329 lines)

---

## Why This Layer Exists

After [Chapter 04](04-prompt-engineering-and-cache-boundaries.md), Claude Code holds every turn ingredient in memory—`bootstrap/state.ts`/`returnValue()` (Ch 01), `assembleToolPool()` (Ch 02), Stage 1 `normalizeMessagesForAPI()`/`ensureToolResultPairing()` (Ch 03), and `splitSysPromptPrefix()`/`toolToAPISchema()`/`promptCacheBreakDetection.ts` (Ch 04)—none yet on a socket. Nine files (7,332 lines) bridge memory to wire: model/thinking/effort resolution → four-provider client → request assembly & Stage 2 conversion → generator retries & error taxonomy → raw SSE streaming & fallback → usage, cost, and quota accounting.

---

## 1. Target Configuration: Model Resolution, Thinking Modes, and Effort Levels

### The Problem

Before opening a client, Claude Code settles `model`, `thinking`, and `effort` across four providers, subscription tiers, Plan Mode, skills, and `USER_TYPE === 'ant'` builds—where mismatches degrade reasoning, trigger false autocompact, or return HTTP 400.

### The Real Implementation

**Model resolution (`utils/model/model.ts`):** `getMainLoopModel()` (`utils/model/model.ts:92-98`) evaluates `/model` or `--model` override (`bootstrap/state.ts`) → `ANTHROPIC_MODEL` → `settings.model` → tier default (`getUserSpecifiedModelSetting()` at `utils/model/model.ts:61-78`, `getDefaultMainLoopModelSetting()` at `utils/model/model.ts:178-200`); enterprise-disallowed overrides (`isModelAllowed()`, `utils/model/model.ts:73-75`) silently drop to default. Family defaults (`utils/model/model.ts:105-138`) check `ANTHROPIC_DEFAULT_{OPUS,SONNET,HAIKU}_MODEL` first, keeping 3P separate (`sonnet45` on 3P vs. `sonnet46` on 1P); `getSmallFastModel()` (`utils/model/model.ts:36-38`) reads `ANTHROPIC_SMALL_FAST_MODEL || getDefaultHaikuModel()`.

At turn time, `getRuntimeMainLoopModel()` (`utils/model/model.ts:145-167`) switches `'opusplan'` to Opus (unless `exceeds200kTokens`) and `'haiku'` to Sonnet in `'plan'` mode. `getCanonicalName()` reverses `settings.modelOverrides` ARNs before pure `firstPartyNameToCanonical()` (`utils/model/model.ts:217-283`). `parseUserSpecifiedModel()` (`utils/model/model.ts:445-506`) splits `[1m]`, expands aliases, remaps retired 1P Opus 4.0/4.1 IDs unless `CLAUDE_CODE_DISABLE_LEGACY_MODEL_REMAP` (`utils/model/model.ts:538-554`), and preserves custom Foundry casing; `normalizeModelStringForAPI()` (`utils/model/model.ts:616-618`) strips client-only `[(1|2)m]` (`services/api/claude.ts:1700`). Two scars anchor the file: `resolveSkillModelOverride()` (`utils/model/model.ts:523-536`) propagates `[1m]` onto `model: opus` skills so 230K sessions stay 1M, and `isOpus1mMergeEnabled()` fails closed on `is1mContextDisabled()` (`CLAUDE_CODE_DISABLE_1M_CONTEXT`, `utils/context.ts:32`) and partial VS Code OAuth tokens:

```ts
// utils/model/model.ts:314-332
export function isOpus1mMergeEnabled(): boolean {
  if (
    is1mContextDisabled() ||
    isProSubscriber() ||
    getAPIProvider() !== 'firstParty'
  ) {
    return false
  }
  // Fail closed when a subscriber's subscription type is unknown. The VS Code
  // config-loading subprocess can have OAuth tokens with valid scopes but no
  // subscriptionType field (stale or partial refresh). Without this guard,
  // isProSubscriber() returns false for such users and the merge leaks
  // opus[1m] into the model dropdown — the API then rejects it with a
  // misleading "rate limit reached" error.
  if (isClaudeAISubscriber() && getSubscriptionType() === null) {
    return false
  }
  return true
}
```

**Thinking (`utils/thinking.ts`) & effort (`utils/effort.ts`):** `ThinkingConfig` (`utils/thinking.ts:10-13`) is `{ type: 'adaptive' } | { type: 'enabled'; budgetTokens: number } | { type: 'disabled' }`. `shouldEnableThinkingByDefault()` (`utils/thinking.ts:146-162`) checks `MAX_THINKING_TOKENS` (`"0"` disables), then `settings.alwaysThinkingEnabled === false`, defaulting to `true`. `modelSupportsThinking()` (`utils/thinking.ts:90-110`) checks 3P capability overrides (`ANTHROPIC_DEFAULT_*_MODEL_SUPPORTED_CAPABILITIES`, `utils/model/modelSupportOverrides.ts:13-22`), ant models, then Claude 4+ on 1P/Foundry vs. Sonnet/Opus 4+ on Bedrock/Vertex; `modelSupportsAdaptiveThinking()` (`utils/thinking.ts:113-144`) allowlists 4.6 models and **fails open on 1P/Foundry** for unknown strings. `isUltrathinkEnabled()` (`utils/thinking.ts:19-24`) requires `feature('ULTRATHINK')` + GrowthBook `'tengu_turtle_carbon'`; `findThinkingTriggerPositions()` (`utils/thinking.ts:36-58`) allocates fresh `/\bultrathink\b/gi` per call to avoid `matchAll` `lastIndex` leakage.

`EFFORT_LEVELS` (`utils/effort.ts:13-18`) is `'low' | 'medium' | 'high' | 'max'`; `EffortValue = EffortLevel | number` (`utils/effort.ts:20`) adds internal numeric overrides. `modelSupportsEffort()` (`utils/effort.ts:23-49`) honors `CLAUDE_CODE_ALWAYS_ENABLE_EFFORT`/3P `'effort'` overrides, failing open on `firstParty` only (Foundry excluded per `#30795`). `toPersistableEffort()` (`utils/effort.ts:95-105`) rejects numbers and persists `'max'` only when `process.env.USER_TYPE === 'ant'` (`utils/effort.ts:101`, session-scoped for externals), re-enforced on read by `getInitialEffortSetting()` (`utils/effort.ts:107-111`). `getDefaultEffortForModel()` (`utils/effort.ts:279-329`) defaults external Opus 4.6 to `'medium'` for Pro and Max/Team under GrowthBook `'tengu_grey_step2'` (`utils/effort.ts:268-271`), plus `'medium'` under `isUltrathinkEnabled()`. `resolveAppliedEffort()` (`utils/effort.ts:152-167`) walks `CLAUDE_CODE_EFFORT_LEVEL` (`'unset'`/`'auto'` → `undefined`) → `AppState` → model default, clamping `'max'` to `'high'` whenever `!modelSupportsMaxEffort(model)`.

### Hidden Invariants & Failure Modes

> [!NOTE]
> **Snapshot Absences & Stripped `ANT-ONLY` Imports:**
> 1. `entrypoints/sdk/runtimeTypes.ts` is **absent from this snapshot** (`utils/effort.ts:9` imports `type { EffortLevel }`); its union is observed at `utils/effort.ts:13-18`.
> 2. **Two** internal symbols—`resolveAntModel` (`utils/model/model.ts:402`, `utils/model/model.ts:489`, `utils/thinking.ts:96`, `utils/effort.ts:61`, `utils/effort.ts:290`) and `getAntModelOverrideConfig` (`utils/model/model.ts:182`, `utils/effort.ts:283`)—are called inside `USER_TYPE === 'ant'` guards **without imports**. Both exist in [`utils/model/antModels.ts`](../../utils/model/antModels.ts) (`utils/model/antModels.ts:34-64`, GrowthBook `'tengu_ant_model_override'`). Line 1 of all three callers retains `// biome-ignore-all assist/source/organizeImports: ANT-ONLY import markers must not be reordered`, proving a redaction pass stripped the marked import block.

---

## 2. Four Providers Behind One Client (`services/api/client.ts`)

### The Problem

Routing across 1P, Bedrock, Foundry, and Vertex behind one `Promise<Anthropic>` contract must avoid eager SDK imports, stdout log corruption, strict-proxy header rejections, and a 12-second GCP metadata hang outside GCE.

### The Real Implementation

`getAnthropicClient()` (`services/api/client.ts:88-316`) builds shared headers (`x-app: 'cli'`, `User-Agent`, `X-Claude-Code-Session-Id`, `CLAUDE_CODE_CONTAINER_ID`/`CLAUDE_CODE_REMOTE_SESSION_ID`/`CLAUDE_AGENT_SDK_CLIENT_APP` at `services/api/client.ts:101-116`, `CLAUDE_CODE_ADDITIONAL_PROTECTION`, and `ANTHROPIC_CUSTOM_HEADERS` via ReDoS-free `indexOf(':')` in `getCustomHeaders()`, `services/api/client.ts:330-354`), awaits `checkAndRefreshOAuthTokenIfNeeded()` (`services/api/client.ts:132`), calls `configureApiKeyHeaders()` (`ANTHROPIC_AUTH_TOKEN`/`apiKeyHelper`, `services/api/client.ts:318-328`) under `!isClaudeAISubscriber()` (`services/api/client.ts:135-137`), and sets `ARGS` (`services/api/client.ts:141-152`): `API_TIMEOUT_MS` (default **600,000 ms**), `getProxyFetchOptions({ forAnthropicAPI: true })` (`utils/proxy.ts:288-319`, isolating `ANTHROPIC_UNIX_SOCKET` and honoring `disableKeepAlive()`), and `fetch: buildFetch(...)`. Each provider constructor separately attaches `logger: createStderrLogger()` (`services/api/client.ts:73-86`) only when `isDebugToStdErr()` (`--debug-to-stderr`/`-d2e`, `utils/debug.ts:85-89`) is active (`services/api/client.ts:168`, `services/api/client.ts:216`, `services/api/client.ts:294`, `services/api/client.ts:312`).

It then lazily `await import(...)`s one SDK:
- **Bedrock (`services/api/client.ts:153-190`, `CLAUDE_CODE_USE_BEDROCK`):** `@anthropic-ai/bedrock-sdk`, `ANTHROPIC_SMALL_FAST_MODEL_AWS_REGION`, and `AWS_BEARER_TOKEN_BEDROCK` (`skipAuth: true`) or `refreshAndGetAwsCredentials()` (unless `CLAUDE_CODE_SKIP_BEDROCK_AUTH`).
- **Foundry (`services/api/client.ts:191-220`, `CLAUDE_CODE_USE_FOUNDRY`):** `@anthropic-ai/foundry-sdk`, using `ANTHROPIC_FOUNDRY_API_KEY`, a stub under `CLAUDE_CODE_SKIP_FOUNDRY_AUTH`, or lazy `@azure/identity` `DefaultAzureCredential`.
- **Vertex (`services/api/client.ts:221-298`, `CLAUDE_CODE_USE_VERTEX`):** `@anthropic-ai/vertex-sdk` + `google-auth-library` with `getVertexRegionForModel(model)`, skipping GCP refresh with a mock `GoogleAuth` under `CLAUDE_CODE_SKIP_VERTEX_AUTH` (`services/api/client.ts:224`, `services/api/client.ts:266`). **Scar (`services/api/client.ts:241-288`):** Passes `projectId: ANTHROPIC_VERTEX_PROJECT_ID` *only* when `GCLOUD_PROJECT`/`GOOGLE_CLOUD_PROJECT`/`GOOGLE_APPLICATION_CREDENTIALS` (and lowercase variants) are unset, blocking a 12s GCE metadata hang without clobbering billing overrides.
- **1P Anthropic (`services/api/client.ts:300-316`):** Sets `apiKey: null` with OAuth `authToken` for subscribers and honors `USER_TYPE === 'ant' && USE_STAGING_OAUTH`.

`buildFetch()` (`services/api/client.ts:356-389`) injects a correlatable UUID on 1P without tripping strict proxies:

```ts
// services/api/client.ts:356-389
export const CLIENT_REQUEST_ID_HEADER = 'x-client-request-id'

function buildFetch(
  fetchOverride: ClientOptions['fetch'],
  source: string | undefined,
): ClientOptions['fetch'] {
  // eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins
  const inner = fetchOverride ?? globalThis.fetch
  // Only send to the first-party API — Bedrock/Vertex/Foundry don't log it
  // and unknown headers risk rejection by strict proxies (inc-4029 class).
  const injectClientRequestId =
    getAPIProvider() === 'firstParty' && isFirstPartyAnthropicBaseUrl()
  return (input, init) => {
    // eslint-disable-next-line eslint-plugin-n/no-unsupported-features/node-builtins
    const headers = new Headers(init?.headers)
    // Generate a client-side request ID so timeouts (which return no server
    // request ID) can still be correlated with server logs by the API team.
    // Callers that want to track the ID themselves can pre-set the header.
    if (injectClientRequestId && !headers.has(CLIENT_REQUEST_ID_HEADER)) {
      headers.set(CLIENT_REQUEST_ID_HEADER, randomUUID())
    }
    // ...
    return inner(input, { ...init, headers })
  }
}
```

### Hidden Invariants & Failure Modes

- **Type-cast lie (`services/api/client.ts:188-189`, `services/api/client.ts:218-219`, `services/api/client.ts:296-297`):** Bedrock, Foundry, and Vertex all cast `as unknown as Anthropic`; only `.beta.messages.create` is shared across all four SDKs.
- **Precedence skew:** `services/api/client.ts:153-221` tests `BEDROCK` → `FOUNDRY` → `VERTEX`, whereas `utils/model/providers.ts:6-14` (`getAPIProvider()`) tests `BEDROCK` → `VERTEX` → `FOUNDRY`.

---

## 3. Request Assembly, Stage 2 Wire Conversion, and Sticky Cache Latches (`services/api/claude.ts`)

### The Problem

[Chapter 03](03-command-and-message-contracts.md)'s `normalizeMessagesForAPI()` stops at internal messages; [Chapter 04](04-prompt-engineering-and-cache-boundaries.md)'s `splitSysPromptPrefix()`/`toolToAPISchema()` emit structured pieces. `services/api/claude.ts` strips incompatible blocks, places one message-level KV breakpoint, stops beta headers and 1h TTL from oscillating (~50–70K token cache busts), and routes Bedrock body-only betas into `anthropic_beta`.

### The Real Implementation

`queryModelWithStreaming()` (`services/api/claude.ts:752-780`) wraps `queryModel()` (`services/api/claude.ts:1017-1062`) in `withStreamingVCR()`, checking GrowthBook `'tengu-off-switch'` (`getDynamicConfig_BLOCKS_ON_INIT`) for non-subscriber Opus, reading `previousRequestId` from local `messages`, and resolving Bedrock `application-inference-profile` ARNs into `resolvedModel` (`services/api/claude.ts:1057-1062`).

Assembly runs in four stages (`services/api/claude.ts:1120-1486`):
1. **Tools & suffix advisor (`services/api/claude.ts:1120-1255`, `services/api/claude.ts:1385-1396`):** Computes `useToolSearch`/`deferredToolNames` once, retains non-deferred tools, `ToolSearchTool`, and `extractDiscoveredToolNames(messages)`, defers unready LSP tools (`shouldDeferLspTool()`), calls Ch 04's `toolToAPISchema()`, disables global system-prompt cache (`shouldUseGlobalCacheScope()`: strictly `firstParty` + `!CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS`, `utils/betas.ts:227-232`) when a non-deferred MCP tool renders (`needsToolBasedCacheMarker`), and—when `isAdvisorEnabled()` holds (GrowthBook `'tengu_sage_compass'` defaulting `false`, `!CLAUDE_CODE_DISABLE_ADVISOR_TOOL`, `shouldIncludeFirstPartyOnlyBetas()`, `utils/advisor.ts:53-69`)—appends `{ type: 'advisor_20260301', name: 'advisor', model: advisorModel }` *after* `toolSchemas` so `/advisor` toggles spare the prefix.
2. **Stage 1 hygiene (`services/api/claude.ts:1265-1315`):** Runs Ch 03's `normalizeMessagesForAPI()`, strips `tool_reference`/`caller` when `!useToolSearch`, runs `ensureToolResultPairing()`, strips `advisor` blocks without `ADVISOR_BETA_HEADER`, and drops oldest images/documents above `API_MAX_MEDIA_PER_REQUEST` (`100`, `constants/apiLimits.ts:94`) via `stripExcessMediaItems()` (`services/api/claude.ts:956-1015`).
3. **System blocks & latched 1h TTL (`services/api/claude.ts:333-434`, `services/api/claude.ts:3213-3237`):** Calls `buildSystemPromptBlocks()` → Ch 04's `splitSysPromptPrefix()` + `getCacheControl()` (`DISABLE_PROMPT_CACHING*`). `should1hCacheTTL()` honors `ENABLE_PROMPT_CACHING_1H_BEDROCK` on Bedrock and otherwise **latches** eligibility (`USER_TYPE === 'ant' || (isClaudeAISubscriber() && !currentLimits.isUsingOverage)`) and GrowthBook `'tengu_prompt_cache_1h_config'`'s allowlist in `bootstrap/state.ts`.
4. **Sticky beta latches (`services/api/claude.ts:1405-1456`) & cache snapshot (`services/api/claude.ts:1460-1486`):** Four flags latch `true` in `bootstrap/state.ts:1744-1749` until `/clear` or `/compact` (`clearBetaHeaderLatches()`): `afkModeHeaderLatched` (local `afkHeaderLatched`, `services/api/claude.ts:1412`; `feature('TRANSCRIPT_CLASSIFIER')`), `fastModeHeaderLatched` (fast mode gated by `!CLAUDE_CODE_DISABLE_FAST_MODE` and GrowthBook `'tengu_penguins_off'`/`'tengu_marble_sandcastle'`, `utils/fastMode.ts:38-94`), `cacheEditingHeaderLatched` (`feature('CACHED_MICROCOMPACT')`, importing snapshot-absent `services/compact/cachedMicrocompact.ts` at `services/api/claude.ts:1195` and stripped `CACHE_EDITING_BETA_HEADER` from `constants/betas.ts` at `services/api/claude.ts:1196-1197`), and `thinkingClearLatched`. Under `feature('PROMPT_CACHE_BREAK_DETECTION')`, Ch 04's `recordPromptState()` hashes non-deferred tools, system blocks, and latched headers.

`getMergedBetas()` (`utils/betas.ts:397-428`) runs once up front per `queryModel()` call (`services/api/claude.ts:1071`); per attempt, `paramsFromContext(retryContext)` (`services/api/claude.ts:1538-1729`) clones `[...betas]` (`services/api/claude.ts:1539`), routes Bedrock's `getBedrockExtraBodyParamsBetas()` (`services/api/claude.ts:1553`) + `toolSearchHeader` into `getExtraBodyParams()`'s `anthropic_beta`, applies `configureEffortParams()` (`services/api/claude.ts:440-466`: `output_config.effort` + `EFFORT_BETA_HEADER`, or ant-only `anthropic_internal.effort_override`) and `configureTaskBudgetParams()` (`services/api/claude.ts:479-501`: `output_config.task_budget` + `TASK_BUDGETS_BETA_HEADER` via `shouldIncludeFirstPartyOnlyBetas()`—both `firstParty` and `foundry` when `!CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS`, `utils/betas.ts:215-220`), computes `max_tokens` via `getMaxOutputTokensForModel()` (`services/api/claude.ts:3399-3419`, 8,000-token cap under GrowthBook `'tengu_otk_slot_v1'` unless overridden by `CLAUDE_CODE_MAX_OUTPUT_TOKENS`), selects adaptive vs. budgeted thinking (`budget_tokens <= maxOutputTokens - 1`, honoring `CLAUDE_CODE_DISABLE_THINKING`/`CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING`, omitting `temperature`), and runs **Stage 2 conversion** via `addCacheBreakpoints()` (`services/api/claude.ts:3063-3211`):

```ts
// services/api/claude.ts:3078-3110
// Exactly one message-level cache_control marker per request. Mycro's
// turn-to-turn eviction (page_manager/index.rs: Index::insert) frees
// local-attention KV pages at any cached prefix position NOT in
// cache_store_int_token_boundaries. With two markers the second-to-last
// position is protected and its locals survive an extra turn even though
// nothing will ever resume from there — with one marker they're freed
// immediately. For fire-and-forget forks (skipCacheWrite) we shift the
// marker to the second-to-last message: that's the last shared-prefix
// point, so the write is a no-op merge on mycro (entry already exists)
// and the fork doesn't leave its own tail in the KVCC. Dense pages are
// refcounted and survive via the new hash either way.
const markerIndex = skipCacheWrite ? messages.length - 2 : messages.length - 1
const result = messages.map((msg, index) => {
  const addCache = index === markerIndex
  if (msg.type === 'user') {
    return userMessageToMessageParam(
      msg,
      addCache,
      enablePromptCaching,
      querySource,
    )
  }
  return assistantMessageToMessageParam(
    msg,
    addCache,
    enablePromptCaching,
    querySource,
  )
})

if (!useCachedMC) {
  return result
}
```

### Hidden Invariants & Failure Modes

> [!IMPORTANT]
> **Wire-Conversion & Cache Invariants:**
> 1. **Clone even when `addCache` is `false` (`services/api/claude.ts:622-630`):** `userMessageToMessageParam()` shallow-clones array content so cached-microcompact `cache_edits` splices never duplicate across retries.
> 2. **Skip invalid assistant blocks (`services/api/claude.ts:658-665`):** `assistantMessageToMessageParam()` never attaches `cache_control` to `thinking`, `redacted_thinking`, or (`feature('CONNECTOR_TEXT')`) `isConnectorTextBlock(_)` (imported from snapshot-absent `types/connectorText.ts`, observed at `services/api/claude.ts:44`, `services/api/claude.ts:2070-2081`).
> 3. **Clone `CLAUDE_CODE_EXTRA_BODY` (`services/api/claude.ts:283-286`):** `safeParseJSON()` is LRU-cached; cloning stops `anthropic_beta` and 4-way gated `anti_distillation: ['fake_tools']` (`feature('ANTI_DISTILLATION_CC')` + `process.env.CLAUDE_CODE_ENTRYPOINT === 'cli'` + `shouldIncludeFirstPartyOnlyBetas()` (`firstParty`/`foundry`, `!CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS`) + GrowthBook `'tengu_anti_distill_fake_tool_injection'`, `services/api/claude.ts:302-313`) from poisoning cached objects.
> 4. **Sticky header, dynamic speed (`services/api/claude.ts:1642-1657`):** `FAST_MODE_BETA_HEADER` stays latched while `speed: 'fast'` drops during cooldown, preserving the cache key. Scalar log fields are pre-computed before `.then()` (`services/api/claude.ts:1731-1759`) so telemetry closures never pin `messagesForAPI` in RAM.

---

## 4. Retries as an `AsyncGenerator`, Overload Fallbacks, and Error Taxonomy (`services/api/withRetry.ts`, `services/api/errors.ts`)

### The Problem

Passing `maxRetries: 0` to `getAnthropicClient()` (`services/api/claude.ts:846`, `services/api/claude.ts:1781`) gives Claude Code sole outage-recovery control: visible countdowns, shedding background 529s, refreshing credentials/sockets, repairing `max_tokens` overflows, escaping 529 storms via fallback, and smuggling raw error text past exact-string UI matchers.

### The Real Implementation

**`withRetry<T>` (`services/api/withRetry.ts:170-517`):** As `AsyncGenerator<SystemAPIErrorMessage, T>`, it yields `createSystemAPIErrorMessage()` before standard `APIError` retry sleeps (`services/api/withRetry.ts:508-511`; fast-mode `<20s` retries at `services/api/withRetry.ts:285-289` and non-`APIError` AWS/GCP credential retries at `services/api/withRetry.ts:375-376`, `services/api/withRetry.ts:508` sleep without yielding)—driving TUI timers and SDK `api_retry` events (`QueryEngine.ts:943-955`)—and returns `T` on success (drained via Ch 01's `returnValue()` in `verifyApiKey()`, `services/api/claude.ts:543`). Defaults: `DEFAULT_MAX_RETRIES = 10` (`CLAUDE_CODE_MAX_RETRIES`, `services/api/withRetry.ts:789-797`), `signal.aborted` checks before each step/sleep, and ant-only `/mock-limits` (`USER_TYPE === 'ant'`, `services/api/withRetry.ts:202-210`).

**Client, auth & socket healing (`services/api/withRetry.ts:218-251`, `services/api/withRetry.ts:375-382`, `services/api/withRetry.ts:623-694`):** On `ECONNRESET`/`EPIPE`, GrowthBook `'tengu_disable_keepalive_on_econnreset'` trips sticky `disableKeepAlive()` (`utils/proxy.ts:27-31`). `withRetry` rebuilds `client = await getClient()` after 401 (`handleOAuth401Error()` + `clearApiKeyHelperCache()`), 403 `"OAuth token has been revoked"`, Bedrock auth (`CLAUDE_CODE_USE_BEDROCK` + `CredentialsProviderError`/403 → `clearAwsCredentialsCache()`), Vertex auth (`CLAUDE_CODE_USE_VERTEX` + string-matched `google-auth-library` `Error`/401 → `clearGcpCredentialsCache()`), or stale sockets. AWS/GCP handlers precede `error instanceof APIError` because cloud auth throws non-`APIError`s.

**Classification, backoff & `UNATTENDED_RETRY` (`services/api/withRetry.ts:57-110`, `services/api/withRetry.ts:261-548`, `services/api/withRetry.ts:696-822`):**
- **Fast-mode & 529 load shedding:** Fast-mode `<20s` `retry-after` sleeps while keeping fast mode; longer/missing `retry-after` on 429/529 enters `Math.max(retryAfterMs ?? 30m, 10m)` cooldown (10m floor, 30m default, unbounded above if `retry-after` exceeds 30m; `services/api/withRetry.ts:293-296`, `services/api/withRetry.ts:799-801`) and sets `retryContext.fastMode = false` (`services/api/withRetry.ts:261-314`). `FOREGROUND_529_RETRY_SOURCES` (`services/api/withRetry.ts:57-89`) allowlists 14 interactive/agent/security `QuerySource`s plus `feature('BASH_CLASSIFIER')`-gated `'bash_classifier'`; background queries drop immediately on 529 (`tengu_api_529_background_dropped`).
- **Overflow repair & `shouldRetry()` (`services/api/withRetry.ts:384-427`, `services/api/withRetry.ts:550-595`, `services/api/withRetry.ts:696-787`):** `parseMaxTokensContextOverflowError()` trims `retryContext.maxTokensOverride` (1k buffer, `FLOOR_OUTPUT_TOKENS = 3000`) and retries without sleep. `shouldRetry()` forces `CLAUDE_CODE_REMOTE` 401/403 retry over `x-should-retry: false`, lets `USER_TYPE === 'ant'` ignore `x-should-retry: false` on `>= 500`, and retries `APIConnectionError`, `408`/`409`/`401`/`403`-revoked/`>= 500`, and non-subscriber/Enterprise `429` (else `CannotRetryError`).
- **Backoff & persistent heartbeats (`services/api/withRetry.ts:433-548`, `services/api/withRetry.ts:814-822`):** `getRetryDelay()` honors integer `retry-after` immediately; else `Math.min(500 * 2^(attempt - 1), 32000)` + `0–25%` jitter. Under `feature('UNATTENDED_RETRY')` + `CLAUDE_CODE_UNATTENDED_RETRY` (`services/api/withRetry.ts:100-104`), HTTP `429` honors `anthropic-ratelimit-unified-reset` (6h cap, `services/api/withRetry.ts:433-447`) while `529` skips it for `getRetryDelay()` (5m backoff cap, 6h `retry-after` cap, `services/api/withRetry.ts:448-460`), sleeping in **30s chunks** with keep-alive `SystemAPIErrorMessage`s and clamping `attempt` at `maxRetries`.

**Overload fallback (`services/api/withRetry.ts:326-365`, `services/api/withRetry.ts:610-621`):** `is529Error()` matches `status === 529` or mid-stream `"type":"overloaded_error"`. At `MAX_529_RETRIES` (`3`), eligible primary models trigger model fallback or external early exit:

```ts
// services/api/withRetry.ts:327-365
if (
  is529Error(error) &&
  // If FALLBACK_FOR_ALL_PRIMARY_MODELS is not set, fall through only if the primary model is a non-custom Opus model.
  // TODO: Revisit if the isNonCustomOpusModel check should still exist, or if isNonCustomOpusModel is a stale artifact of when Claude Code was hardcoded on Opus.
  (process.env.FALLBACK_FOR_ALL_PRIMARY_MODELS ||
    (!isClaudeAISubscriber() && isNonCustomOpusModel(options.model)))
) {
  consecutive529Errors++
  if (consecutive529Errors >= MAX_529_RETRIES) {
    // Check if fallback model is specified
    if (options.fallbackModel) {
      // ...
      // Throw special error to indicate fallback was triggered
      throw new FallbackTriggeredError(
        options.model,
        options.fallbackModel,
      )
    }

    if (
      process.env.USER_TYPE === 'external' &&
      !process.env.IS_SANDBOX &&
      !isPersistentRetryEnabled()
    ) {
      logEvent('tengu_api_custom_529_overloaded_error', {})
      throw new CannotRetryError(
        new Error(REPEATED_529_ERROR_MESSAGE),
        retryContext,
      )
    }
  }
}
```

**Error taxonomy (`services/api/errors.ts`):** Failures project onto three surfaces: (1) `classifyAPIError()` (`services/api/errors.ts:965-1161`) emits **25** distinct Datadog tags across 26 returns (`'image_too_large'` repeats at `services/api/errors.ts:1042`, `services/api/errors.ts:1052`; `services/api/logging.ts:282`); (2) `categorizeRetryableAPIError()` (`services/api/errors.ts:1163-1182`) maps retryables onto the 7-variant `SDKAssistantMessageError` union (`QueryEngine.ts:951`; snapshot-absent `entrypoints/sdk/coreTypes.generated.ts`, live `SDKAssistantMessageErrorSchema` at `entrypoints/sdk/coreSchemas.ts:1256-1266`); and (3) `getAssistantMessageFromError()` (`services/api/errors.ts:425-934`; helper `get3PModelFallbackSuggestion()` at `services/api/errors.ts:940-959`) plus `getErrorMessageIfRefusal()` (`services/api/errors.ts:1184-1207`) synthesize `isApiErrorMessage: true` `AssistantMessage`s (branching on `getIsNonInteractiveSession()`, returning `'invalid_request'` for disabled stale-`ANTHROPIC_API_KEY` orgs at `services/api/errors.ts:785-811` so VS Code avoids `showLogin()` loops, and logging `logToolUseToolResultMismatch()` on 400 pairing errors). Only prompt-too-long (`services/api/errors.ts:562-574`) holds the fixed UI string `'Prompt is too long'` while smuggling raw text in **`msg.errorDetails`**; inside media branches (`services/api/errors.ts:576-639`), PDF-page-limit (`services/api/errors.ts:577-586`), image-size (`services/api/errors.ts:613-623`), and many-image (`services/api/errors.ts:626-639`) pair per-variant UI `content` with raw `error.message` in `errorDetails` (password-protected/invalid PDF at `services/api/errors.ts:589-610` do not), feeding `getPromptTooLongTokenGap()` (`services/api/errors.ts:104-118`, `services/compact/compact.ts:260`) and `isMediaSizeErrorMessage()` (`services/api/errors.ts:147-153`) for withheld recovery in `query.ts:15-20`, `query.ts:799-825` (`feature('REACTIVE_COMPACT')`/`feature('CONTEXT_COLLAPSE')`, importing snapshot-absent `services/compact/reactiveCompact.ts` / `services/contextCollapse/`).

### Hidden Invariants & Failure Modes

- **Forensic Scar — `consecutive529Errors` Is Cumulative:** Despite its name (`services/api/withRetry.ts:326`), `services/api/withRetry.ts` has **no `consecutive529Errors = 0` reset** on non-529 errors; three total 529s in one call (including `initialConsecutive529Errors`) trigger fallback.
- **Snapshot Absences:** `types/message.ts` and `constants/querySource.ts` are absent from this checkout; concrete fields and 15+ literal `QuerySource` values are observed at `services/api/withRetry.ts:62-82` and `utils/messages.ts:435-458`, `utils/messages.ts:4585-4603`.

---

## 5. Raw SSE Streaming, Watchdog, Non-Streaming Fallback, and Socket Hygiene (`services/api/claude.ts`)

### The Problem

`BetaMessageStream` runs `partialParse()` on every `input_json_delta`—**O(n²) CPU** on large writes. Raw SSE restores O(n) accumulation, making Claude Code own half-open hangs, empty HTTP 200 bodies, double tool execution, and native TLS leaks on early abort.

### The Real Implementation

Inside `queryModel()` (`services/api/claude.ts:1777-1857`), `withRetry` generates a 1P `clientRequestId` and calls `anthropic.beta.messages.create({ ...params, stream: true }, { signal, headers }).withResponse()` (`services/api/claude.ts:1810-1836`)—skipping `BetaMessageStream` while capturing raw `Stream`, `streamRequestId`, and `streamResponse` (for `extractQuotaStatusFromHeaders` at `services/api/claude.ts:2400`). Pumping `withRetry` re-yields any `SystemAPIErrorMessage` (`!('controller' in e.value)`, `services/api/claude.ts:1853-1855`).

Next, `queryModel()` arms an opt-in idle watchdog (`CLAUDE_ENABLE_STREAM_WATCHDOG`, `CLAUDE_STREAM_IDLE_TIMEOUT_MS` default 90s, `services/api/claude.ts:1868-1929`) and a 30s passive stall logger (`services/api/claude.ts:1936-1966`), then drives the SSE loop (`services/api/claude.ts:1979-2304`):
- **`message_start` (`services/api/claude.ts:1980-1994`):** Captures `partialMessage`, `ttftMs`, initial `usage`, and ant-only `research`.
- **`content_block_start` / `content_block_delta` (`services/api/claude.ts:1995-2170`):** Clones blocks with empty accumulators (`input: ''`, `text: ''`, `thinking: ''`, `signature: ''`), appends `partial_json`/`text`/`thinking`/`connector_text` (`feature('CONNECTOR_TEXT')`), assigns `signature`, and throws on index/type mismatch.
- **`content_block_stop` (`services/api/claude.ts:2171-2212`):** Parses tool JSON once in O(n) via Ch 03's `normalizeContentFromAPI()`, pushes the single-block `AssistantMessage`, and **immediately `yield m`**—feeding `StreamingToolExecutor` mid-stream.
- **`message_delta` (`services/api/claude.ts:2213-2294`) & `stream_event` (`services/api/claude.ts:2299-2303`):** Updates usage, mutates `lastMsg.message` in place, bills USD cost before yielding, emits synthetic errors on `refusal`/`max_tokens`/`model_context_window_exceeded` (reusing `apiError: 'max_output_tokens'`), and forwards every `part` as `{ type: 'stream_event', event: part }`.

The `message_delta` mutation invariant (`services/api/claude.ts:2229-2256`):

```ts
// services/api/claude.ts:2229-2256
// Write final usage and stop_reason back to the last yielded
// message. Messages are created at content_block_stop from
// partialMessage, which was set at message_start before any tokens
// were generated (output_tokens: 0, stop_reason: null).
// message_delta arrives after content_block_stop with the real
// values.
//
// IMPORTANT: Use direct property mutation, not object replacement.
// The transcript write queue holds a reference to message.message
// and serializes it lazily (100ms flush interval). Object
// replacement ({ ...lastMsg.message, usage }) would disconnect
// the queued reference; direct mutation ensures the transcript
// captures the final values.
stopReason = part.delta.stop_reason

const lastMsg = newMessages.at(-1)
if (lastMsg) {
  lastMsg.message.usage = usage
  lastMsg.message.stop_reason = stopReason
}

// Update cost
const costUSDForPart = calculateUSDCost(resolvedModel, usage)
costUSD += addToTotalSessionCost(
  costUSDForPart,
  usage,
  options.model,
)
```

Post-loop, `services/api/claude.ts:2337-2392` rejects empty HTTP 200 bodies (`!partialMessage || (newMessages.length === 0 && !stopReason)`, preserving empty `end_turn` `StructuredOutput` turns) and calls Ch 04's `checkResponseForCacheBreak()` (`feature('PROMPT_CACHE_BREAK_DETECTION')`). Errors enter two fallback paths (`services/api/claude.ts:2434-2694`):
1. **Mid-stream fallback (`services/api/claude.ts:2434-2594`):** Separates real `signal.aborted` ESC aborts from SDK timeouts (`services/api/claude.ts:2434-2462`), then honors `CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK` and GrowthBook `'tengu_disable_streaming_to_non_streaming_fallback'` (**`inc-4258`** double-tool-execution guard). Otherwise calls `options.onStreamingFallback?.()` (telling `query.ts:712-741` to tombstone partials and `streamingToolExecutor.discard()`) and runs `executeNonStreamingRequest()` (`services/api/claude.ts:818-917`) with `initialConsecutive529Errors: is529Error(streamingError) ? 1 : 0`.
2. **Outer 404 stream-creation fallback (`services/api/claude.ts:2598-2694`):** First **unconditionally re-throws `FallbackTriggeredError`** (`services/api/claude.ts:2603-2605`, `services/api/claude.ts:2692-2694`) so `query.ts` switches models; then catches 404 `CannotRetryError` and calls `executeNonStreamingRequest()` (timeout defaults to 120s in `CLAUDE_CODE_REMOTE`/300s locally, overridden by `API_TIMEOUT_MS` at `services/api/claude.ts:807-811`; `adjustParamsForNonStreaming()` at `services/api/claude.ts:3354-3392` caps `max_tokens` at `MAX_NON_STREAMING_TOKENS = 64_000` and `thinking.budget_tokens <= cappedMaxTokens - 1`). Note `queryModelWithoutStreaming()` (`services/api/claude.ts:709-750`, backing `queryHaiku()`/`queryWithModel()`) still streams SSE internally; only `executeNonStreamingRequest()` and `verifyApiKey()` (`services/api/claude.ts:530-586`) omit `stream: true`.

### Hidden Invariants & Failure Modes

> [!WARNING]
> **Early-Exit Socket Leaks (`GH #32920`):**
> Breaking out of `for await` invokes `.return()`, running `finally` and skipping post-`try/finally` code. Placing `releaseStreamResources()` (`cleanupStream()` + `streamResponse.body?.cancel()`, `services/api/claude.ts:1515-1526`, `services/api/claude.ts:2898-2912`) **and** `fallbackMessage` cost accounting in `finally` (`services/api/claude.ts:2808-2831`) prevents off-heap TLS/socket leaks and guarantees fallback billing survives abort.

---

## 6. Token Usage, USD Cost Accounting, and Quota Utilization

### The Problem

Streaming splits usage across `message_start` and `message_delta` (whose `0`s can wipe prompt/cache counts), turns mix models (Bedrock ARNs, 6× fast mode, advisor sub-calls), `/resume` restores spend/wall time, and subscribers need quota windows.

### The Real Implementation

1. **Per-chunk merge (`services/api/emptyUsage.ts`, `services/api/claude.ts:2924-2987`):** Each attempt resets `usage = EMPTY_USAGE` (`services/api/claude.ts:1765`, `services/api/claude.ts:1864`; 22-line `services/api/emptyUsage.ts` stops `bridge/replBridge.ts` pulling `BashTool.tsx` via `logging.ts`). `updateUsage()` guards `input_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens` with `!== null && > 0` so `message_delta` zeros never erase `message_start`, casts `partUsage as BetaUsage` for `cache_creation.{ephemeral_1h,ephemeral_5m}_input_tokens` and `speed`, and spreads `cache_deleted_input_tokens` behind `feature('CACHED_MICROCOMPACT')` (`services/api/claude.ts:2970-2982`).
2. **USD pricing (`utils/modelCost.ts:27-180`):** `calculateUSDCost(resolvedModel, usage)` canonicalizes Bedrock's backing model via `getCanonicalName()` across six per-Mtok tiers (`COST_HAIKU_35` $0.80/$4, `COST_HAIKU_45` $1/$5, `COST_TIER_3_15` $3/$15, `COST_TIER_5_25` $5/$25, `COST_TIER_15_75` $15/$75, and **6× Opus 4.6 fast mode** `COST_TIER_30_150` $30/$150 when `isFastModeEnabled() && usage.speed === 'fast'`, `utils/modelCost.ts:94-99`, `utils/modelCost.ts:148-153`) plus `$0.01` per `web_search_requests`; unknown models flip `setHasUnknownModelCost()` (`formatTotalCost()` at `cost-tracker.ts:228-244`) and fall back to default pricing.
3. **Process ledger, OTel & recursive advisor billing (`cost-tracker.ts:250-323`):** `addToTotalSessionCost()` writes per-model `ModelUsage` to `bootstrap/state.ts` (`addToTotalCostState()`), emits OTel counters (tagging `speed: 'fast'`), and recursively bills `advisor_message` iterations via `getAdvisorUsage(usage)` (`utils/advisor.ts:115-128`):

```ts
// cost-tracker.ts:278-323
export function addToTotalSessionCost(
  cost: number,
  usage: Usage,
  model: string,
): number {
  const modelUsage = addToTotalModelUsage(cost, usage, model)
  addToTotalCostState(cost, modelUsage, model)

  const attrs =
    isFastModeEnabled() && usage.speed === 'fast'
      ? { model, speed: 'fast' }
      : { model }

  getCostCounter()?.add(cost, attrs)
  getTokenCounter()?.add(usage.input_tokens, { ...attrs, type: 'input' })
  // ...

  let totalCost = cost
  for (const advisorUsage of getAdvisorUsage(usage)) {
    const advisorCost = calculateUSDCost(advisorUsage.model, advisorUsage)
    // ...
    totalCost += addToTotalSessionCost(
      advisorCost,
      advisorUsage,
      advisorUsage.model,
    )
  }
  return totalCost
}
```

4. **Cross-turn rollup, single-slot restore & utilization (`services/api/claude.ts:2993-3038`, `cost-tracker.ts:87-175`, `services/api/usage.ts:33-63`):** `QueryEngine.ts:789-816` folds turns into `totalUsage` via `accumulateUsage()`. Across `/resume`, `saveCurrentSessionCosts()`/`restoreCostStateForSession()` keep a **single last-session slot** keyed by `projectConfig.lastSessionId` (read before overwrite), with `setCostStateForRestore()` (`bootstrap/state.ts:881-916`) back-dating `STATE.startTime = Date.now() - lastDuration`. Separately, `fetchUtilization()` (`services/api/usage.ts:33-63`) polls `${BASE_API_URL}/api/oauth/usage` (**5,000 ms** timeout), returning `{}` for non-subscribers or tokens lacking profile scope (`!isClaudeAISubscriber() || !hasProfileScope()`, `services/api/usage.ts:34-36`) and `null` *before* network I/O if `isOAuthTokenExpired(tokens.expiresAt)`.

### Hidden Invariants & Failure Modes

- **Flat 1.25× cache-write caveat (`utils/modelCost.ts:131-142`):** Client-side `tokensToUSDCost()` bills all `cache_creation_input_tokens` at `1.25×` input without splitting 1h vs. 5m buckets.
- **Pricing vs. ledger keys (`services/api/claude.ts:2251-2256`, `cost-tracker.ts:181-226`):** `claude.ts` prices via `resolvedModel` while keying `STATE.modelUsage` by `options.model`; `formatModelUsage()` collapses raw provider IDs via `getCanonicalName(model)` before printing `/cost`.

---

## Putting the Layer Together

```text
Config (model/thinking/effort)  -> canonical model, thinking, effort
   ▼
Client Factory (client.ts)      -> 1P|Bedrock|Foundry|Vertex + proxy
   ▼
Request & Stage 2 (claude.ts)   -> sticky betas + 1 cache marker
   ▼
withRetry<T> (withRetry.ts)     -> backoff, auth heal, 3x 529 throw
   ▼
Raw SSE / Fallback (claude.ts)  -> block yield, mutate usage, finally
   ▼
Accounting (cost-tracker/usage) -> bootstrap/state.ts, OTel, /usage
```

```mermaid
sequenceDiagram
    participant Q as query.ts (Ch 07)
    participant C as queryModelWithStreaming
    participant R as withRetry
    participant A as Model API
    participant Cost as cost-tracker.ts

    Q->>C: iterate queryModelWithStreaming()
    C->>R: open raw stream (maxRetries=0)
    R->>A: beta.messages.create({ stream: true }).withResponse()
    alt transient 429 / 5xx / auth / ECONNRESET
        A-->>R: APIError
        R-->>C: yield SystemAPIErrorMessage (backoff / 30s heartbeat)
        C-->>Q: yield SystemAPIErrorMessage
    else cumulative 529 >= 3 with fallbackModel
        R--xC: throw FallbackTriggeredError
        C--xQ: re-throw FallbackTriggeredError
    end
    A-->>C: content_block_stop
    C-->>Q: yield AssistantMessage (mid-stream tools)
    A-->>C: message_delta (usage, stop_reason)
    C->>C: mutate lastMsg.message in place
    C->>Cost: addToTotalSessionCost() + advisor recursion
    opt mid-stream error (fallback enabled)
        C->>Q: onStreamingFallback() (tombstone + discard)
        C->>R: executeNonStreamingRequest()
    end
    C->>C: finally: releaseStreamResources() + fallback cost
```

---

## How This Snaps Into the Next Layer

`queryModelWithStreaming()` turns Layer 1 tools/messages and Layer 2 prompt boundaries into per-block `AssistantMessage`s (carrying parsed `ToolUseBlock`s) and `StreamEvent`s, signaling resets via `onStreamingFallback()` or `FallbackTriggeredError`. [Chapter 06](06-executing-tools.md)'s executors ([`services/tools/StreamingToolExecutor.ts`](../../services/tools/StreamingToolExecutor.ts), [`services/tools/toolOrchestration.ts`](../../services/tools/toolOrchestration.ts), [`services/tools/toolExecution.ts`](../../services/tools/toolExecution.ts)) never import `services/api/claude.ts` directly; `query.ts` in [Chapter 07](07-the-heartbeat-query-loop.md) (`query/deps.ts:35` wiring `deps.callModel = queryModelWithStreaming`) bridges both halves—feeding `ToolUseBlock`s into `StreamingToolExecutor.addTool()` mid-stream (`query.ts:826-862`) or `runTools()` post-stream (`query.ts:1380-1382`), calling `streamingToolExecutor.discard()` on `onStreamingFallback()` (`query.ts:712-741`) and `FallbackTriggeredError` (`query.ts:894-919`), and withholding recoverable `prompt_too_long`/media-size (`feature('CONTEXT_COLLAPSE')`/`feature('REACTIVE_COMPACT')`) and `max_output_tokens` errors (`query.ts:15-20`, `query.ts:799-825`). Next, [Chapter 06](06-executing-tools.md) dissects tool validation, hooks, concurrency, and disk spill.

---

## Reading Exercises & Code Checkpoints

1. **Provider dispatch & `inc-4029` client request ID:**
   ```sh
   rg -n "CLAUDE_CODE_USE_|CLIENT_REQUEST_ID_HEADER|getProxyFetchOptions|API_TIMEOUT_MS" services/api/client.ts utils/model/providers.ts
   ```
   Compare check order in `services/api/client.ts` (`BEDROCK`→`FOUNDRY`→`VERTEX`) vs. `utils/model/providers.ts` (`BEDROCK`→`VERTEX`→`FOUNDRY`).
2. **Sticky cache latches, single-marker breakpoints & `finally` socket hygiene:**
   ```sh
   rg -n "HeaderLatched|ThinkingClearLatched|markerIndex|addCacheBreakpoints|releaseStreamResources" services/api/claude.ts
   ```
   Verify why `releaseStreamResources()` and fallback billing both sit in `finally` (`services/api/claude.ts:2808-2831`).
3. **Cumulative 529 counter & `errorDetails` recovery side-channel:**
   ```sh
   rg -n "consecutive529Errors|FallbackTriggeredError|errorDetails|getPromptTooLongTokenGap|isMediaSizeErrorMessage" services/api/withRetry.ts services/api/errors.ts services/api/claude.ts query.ts
   ```
   Confirm `consecutive529Errors` has no non-529 reset and trace `FallbackTriggeredError` into `query.ts:894`.
4. **Recursive advisor billing & stripped `ANT-ONLY` imports:**
   ```sh
   rg -n "addToTotalSessionCost|getAdvisorUsage|resolveAntModel|getAntModelOverrideConfig|ANT-ONLY import markers" cost-tracker.ts services/api/claude.ts utils/model/model.ts utils/model/antModels.ts utils/thinking.ts utils/effort.ts
   ```
   Inspect how `resolveAntModel` and `getAntModelOverrideConfig` live in `utils/model/antModels.ts` while callers omit their import lines.


---

<!-- chapters/06-executing-tools.md — https://reverseengineeringclaudecode.com/chapters/06-executing-tools -->

# Chapter 06 — Executing Tools: Validation, Hooks, Concurrency, and Streaming Execution

> **Layer:** Layer 2 (The Agent Engine)
> **Prerequisites:** [Chapter 01](01-atoms-types-stores-and-primitives.md) (`utils/generators.ts` `all()`), [Chapter 02](02-the-tool-contract.md) (`Tool.ts`, `ToolUseContext`, `isConcurrencySafe`, `maxResultSizeChars`), [Chapter 03](03-command-and-message-contracts.md) (`utils/messages.ts` `normalizeMessagesForAPI`, `tool_use`/`tool_result` pairing), [Chapter 04](04-prompt-engineering-and-cache-boundaries.md) (prompt-cache prefix stability), [Chapter 05](05-talking-to-the-model.md) (`queryModelWithStreaming`, `AssistantMessage` / `ToolUseBlock[]`, `FallbackTriggeredError`)
> **Primary Source Files:**
> - [`services/tools/toolExecution.ts`](../../services/tools/toolExecution.ts) — single-tool 8-step lifecycle, streaming progress bridge, error classification, and telemetry (1,745 lines)
> - [`services/tools/toolHooks.ts`](../../services/tools/toolHooks.ts) — `PreToolUse` / `PostToolUse` / `PostToolUseFailure` adapters and hook-vs-rule permission arbitration (650 lines)
> - [`services/tools/toolOrchestration.ts`](../../services/tools/toolOrchestration.ts) — fail-closed concurrency partitioning, `all()` batching, and block-order `contextModifier` replay (188 lines)
> - [`services/tools/StreamingToolExecutor.ts`](../../services/tools/StreamingToolExecutor.ts) — mid-stream execution overlapping SSE chunks, 3-level `AbortController` tree, and fallback `discard()` (530 lines)
> - [`utils/toolResultStorage.ts`](../../utils/toolResultStorage.ts) — two-stage `<persisted-output>` spill-to-disk and prompt-cache-safe `ContentReplacementState` budgeting (1,040 lines)

---

## Why This Layer Exists

Once [Chapter 05](05-talking-to-the-model.md)'s `queryModelWithStreaming()` yields `AssistantMessage` records containing `ToolUseBlock[]`, executing them looks like a one-liner: `await tool.call(block.input)`. In production, that one-liner breaks in five ways:

1. **Untrusted inputs:** Models invoke deprecated aliases, guess deferred-tool schemas (stringifying arrays and booleans), forge internal fields, or send unexpanded `~` paths that evade hook allowlists.
2. **Policy bypasses:** User `PreToolUse` hooks can approve or rewrite calls, yet hook `allow` must never bypass `settings.json` `deny`/`ask` rules or protected-path safety guards.
3. **Throughput vs. determinism:** Serial reads waste seconds; concurrent edits corrupt files; applying `contextModifier` callbacks in completion order creates timing races.
4. **Streaming overlap & blast radius:** Launching tools mid-stream hides latency, but a failed `Bash` command must cancel sibling commands *without* killing the turn, a user permission rejection *must* abort the turn, and a streaming or model fallback must discard orphaned work.
5. **Context blowup vs. prompt cache:** Giant outputs overflow context, spilling `FileReadTool` creates an infinite `Read` → file → `Read` loop, and recomputing aggregate budgets on older turns mutates wire history and busts the prompt cache.

These five files (`4,153` lines) solve all five problems.

---

## 1. The Single-Tool Lifecycle: From `tool_use` to `tool_result`

### The Problem

One tool invocation spans schema validation, hooks, permissions, and arbitrary I/O while streaming live UI progress and guaranteeing every exit path emits a paired `tool_result` ([Chapter 03](03-command-and-message-contracts.md)).

### The Real Implementation (`services/tools/toolExecution.ts`)

Every call enters `runToolUse()` (`services/tools/toolExecution.ts:337-490`) and walks an exact 8-step pipeline:

1. **Lookup & alias-only fallback (`services/tools/toolExecution.ts:343-411`).** Searches `toolUseContext.options.tools` via `findToolByName()` (`Tool.ts:358-360`). If absent, checks `getAllBaseTools()` **only** when `fallbackTool.aliases?.includes(toolName)` (`services/tools/toolExecution.ts:350-356`), rescuing deprecated names like `KillShell` (alias on `TaskStopTool` at `tools/TaskStopTool/TaskStopTool.ts:44`) without bypassing `disallowedTools` for primary tool names. Unknown tools emit an `is_error: true` `<tool_use_error>` and return. Deferred tools remain in `options.tools` and pass Step 1; missing schemas surface in Step 4.
2. **Pre-execution abort check (`services/tools/toolExecution.ts:413-453`).** If `toolUseContext.abortController.signal.aborted` is set, yields `createToolResultStopMessage()` (`utils/messages.ts:622-631`) carrying `withMemoryCorrectionHint(CANCEL_MESSAGE)` (`services/tools/toolExecution.ts:444`, appending a memory hint when auto-memory and GrowthBook `'tengu_amber_prism'` are active at `utils/messages.ts:185-193`) and returns.
3. **Push-to-pull progress bridge (`services/tools/toolExecution.ts:455-570`).** `checkPermissionsAndCallTool()` (`services/tools/toolExecution.ts:599-1745`) returns `Promise<MessageUpdateLazy[]>`, while hooks and `tool.call()` push live progress via `onToolProgress`. `streamedCheckPermissionsAndCallTool()` (`services/tools/toolExecution.ts:492-570`) bridges them with `Stream<MessageUpdateLazy>` (`utils/stream.ts:1-76`), enqueueing each `ProgressMessage` immediately (`services/tools/toolExecution.ts:549-555`) before flushing final results in `.then()` and closing in `.finally()`. An outer `try/catch` (`services/tools/toolExecution.ts:414-489`) catches unexpected escapes into `<tool_use_error>`.
4. **Validation, prefetch & input isolation (`services/tools/toolExecution.ts:614-793`).**
   - **Zod parse + schema hint (`services/tools/toolExecution.ts:615-680`):** `tool.inputSchema.safeParse(input)` formats failures via `formatZodValidationError()` (`utils/toolErrors.ts:66-132`) and calls `buildSchemaNotSentHint()` (`services/tools/toolExecution.ts:578-597`): when `isToolSearchEnabledOptimistic()` (`utils/toolSearch.ts:270-320`; `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` at `utils/toolSearch.ts:181` inside `getToolSearchMode()` at `utils/toolSearch.ts:172-198`, `ENABLE_TOOL_SEARCH`, and `ANTHROPIC_BASE_URL` parsed in `isFirstPartyAnthropicBaseUrl()` at `utils/model/providers.ts:25-40`), `isToolSearchToolAvailable()`, and `isDeferredTool()` hold and the tool is absent from `extractDiscoveredToolNames(messages)`, it tells the model to call `ToolSearch` with `select:<tool.name>` and retry.
   - **Semantic validation & Bash prefetch (`services/tools/toolExecution.ts:683-752`):** Runs `tool.validateInput?.()` before hooks/permissions, then calls `startSpeculativeClassifierCheck()` (`tools/BashTool/bashPermissions.ts:1497-1527`) for `Bash` commands so allow-classification can overlap `PreToolUse` hooks—gated on `isClassifierPermissionsEnabled()`, an **ANT-ONLY stub hardcoded to `return false`** in this external checkout (`utils/permissions/bashClassifier.ts:1`, `utils/permissions/bashClassifier.ts:24-26`, making the prefetch a no-op here), and explicitly **skipped** when `feature('TRANSCRIPT_CLASSIFIER') && toolPermissionContext.mode === 'auto'` or `toolPermissionContext.mode === 'bypassPermissions'` (`tools/BashTool/bashPermissions.ts:1504-1507`).
   - **`_simulatedSedEdit` strip & `backfillObservableInput` clone (`services/tools/toolExecution.ts:761-793`):** First strips any model-supplied `_simulatedSedEdit` field from `Bash` inputs (`services/tools/toolExecution.ts:761-773`) as defense-in-depth against schema regressions. Then isolates observer normalization on a shallow clone:

```ts
// services/tools/toolExecution.ts:775-793
// Backfill legacy/derived fields on a shallow clone so hooks/canUseTool see
// them without affecting tool.call(). SendMessageTool adds fields; file
// tools overwrite file_path with expandPath — that mutation must not reach
// call() because tool results embed the input path verbatim (e.g. "File
// created successfully at: {path}"), and changing it alters the serialized
// transcript and VCR fixture hashes. If a hook/permission later returns a
// fresh updatedInput, callInput converges on it below — that replacement
// is intentional and should reach call().
let callInput = processedInput
const backfilledClone =
  tool.backfillObservableInput &&
  typeof processedInput === 'object' &&
  processedInput !== null
    ? ({ ...processedInput } as typeof processedInput)
    : null
if (backfilledClone) {
  tool.backfillObservableInput!(backfilledClone as Record<string, unknown>)
  processedInput = backfilledClone
}
```

   File tools expand `~`/relative paths in `backfillObservableInput()` (e.g., `tools/FileReadTool/FileReadTool.ts:388-394`) so hook allowlists see canonical paths, while `callInput` stays pinned to the model's input. Before `tool.call()` (`services/tools/toolExecution.ts:1181-1205`), even if a hook/permission flow returns a fresh object whose `file_path` still matches `backfilledClone.file_path`, Claude Code restores the model's original `file_path` to keep transcript and VCR fixture hashes stable while keeping other hook edits.
5. **`PreToolUse` hooks (`services/tools/toolExecution.ts:795-891`).** Runs `runPreToolUseHooks()` (Section 2), logs debug warnings past `SLOW_PHASE_LOG_THRESHOLD_MS` (`2000` ms at `services/tools/toolExecution.ts:137`), and—gated by `process.env.USER_TYPE === 'ant'`—emits an inline wall-clock timing summary above `HOOK_TIMING_DISPLAY_THRESHOLD_MS` (`500` ms at `services/tools/toolExecution.ts:134`, `services/tools/toolExecution.ts:874-891`) since hooks run in parallel.
6. **Permission reconciliation & `canUseTool` (`services/tools/toolExecution.ts:909-1132`).** Starts OTel spans (attaching `processedInput` JSON only under `isBetaTracingEnabled()`—env vars `ENABLE_BETA_TRACING_DETAILED`, `BETA_TRACING_ENDPOINT`, and for `process.env.USER_TYPE !== 'ant'`, SDK/non-interactive mode via `getIsNonInteractiveSession()` or GrowthBook `'tengu_trace_lantern'` at `utils/telemetry/betaSessionTracing.ts:78-98`), calls `resolveHookPermissionDecision()` (Section 2), and restricts the `>= 2000` ms slow-permission log to `permissionMode === 'auto'` (`services/tools/toolExecution.ts:937-946`) to ignore human think time. On denial (`services/tools/toolExecution.ts:995-1104`), emits a text-only `is_error: true` `tool_result` with any user-pasted rejection images placed as **top-level sibling blocks** (`services/tools/toolExecution.ts:1029-1062`), because the Anthropic API rejects non-text blocks inside `is_error: true` `tool_result`s.
7. **`tool.call()`, single pre-mapping & Stage A spill (`services/tools/toolExecution.ts:1134-1479`).** Guards OTel `toolParameters` behind `isToolDetailsLoggingEnabled()` (`OTEL_LOG_TOOL_DETAILS` at `services/analytics/metadata.ts:86-88`), starts `startSessionActivity('tool_exec')`, runs `tool.call()`, and maps `result.data` **once** via `mapToolResultToToolResultBlockParam()` (`services/tools/toolExecution.ts:1292-1301`) for telemetry size measurement and reuse. Non-MCP tools immediately call `addToolResult(toolOutput, mappedToolResultBlock)` (`services/tools/toolExecution.ts:1403-1479`), invoking Stage A `processPreMappedToolResultBlock()`, appending `acceptFeedback`/images, trimming `toolUseResult` (unless `preserveToolUseResults`) and `mcpMeta` for subagents (`services/tools/toolExecution.ts:1460-1464`), and wrapping `result.contextModifier`.
8. **`PostToolUse` vs. `PostToolUseFailure` hooks (`services/tools/toolExecution.ts:1481-1744`).** Success runs `runPostToolUseHooks()` (with the same `USER_TYPE === 'ant'` `> 500` ms wall-clock summary at `services/tools/toolExecution.ts:1546-1563`), appends `result.newMessages`, and emits `hook_stopped_continuation` if `PreToolUse` set `shouldPreventContinuation` (`services/tools/toolExecution.ts:1572-1582`). Exceptions inside `tool.call()`'s `try` enter `catch (error)` (`services/tools/toolExecution.ts:1589-1737`), transition `McpAuthError` clients to `'needs-auth'`, classify non-abort errors via `classifyToolError()`, and run `runPostToolUseFailureHooks()`. `finally` (`services/tools/toolExecution.ts:1738-1744`) always calls `stopSessionActivity('tool_exec')` and deletes `toolUseContext.toolDecisions?.delete(toolUseID)`.

### Hidden Invariants & Failure Modes

- **Minification-safe error classification (`services/tools/toolExecution.ts:150-171`):** Bundled builds mangle `error.constructor.name` to 3-char tokens (`"nJT"`). `classifyToolError()` checks `TelemetrySafeError`, then Node errno codes (`Error:ENOENT`), and accepts `error.name` only when `error.name.length > 3` (`services/tools/toolExecution.ts:165`), else `'Error'` or `'UnknownError'`.
- **Exact `runPostToolUseFailureHooks` boundary:** Fires **strictly** on `tool.call()`-region exceptions (`services/tools/toolExecution.ts:1589-1737`)—runtime errors (`isInterrupt: false`, including `ShellError` and `McpAuthError`) and mid-execution `AbortError` (`isInterrupt: true`). Never fires on unknown tools (`services/tools/toolExecution.ts:369-411`), pre-execution aborts (`services/tools/toolExecution.ts:415-453`), Zod/`validateInput` failures (`services/tools/toolExecution.ts:615-733`), `PreToolUse` `{ type: 'stop' }` (`services/tools/toolExecution.ts:848-860`), or permission denials (`services/tools/toolExecution.ts:995-1104`). Note that `catch` returns a fresh array `[{ message: createUserMessage(...) }, ...hookMessages]` (`services/tools/toolExecution.ts:1715-1737`), dropping earlier `PreToolUse` attachments in `resultingMessages`.

---

## 2. Hook Arbitration & Permission Handoff

### The Problem

Hooks allow custom linters, secret scanners, and input rewriters, yet an overly permissive `PreToolUse` hook returning `allow` must never become a privilege-escalation vector that overrides `settings.json` `deny` rules, `ask` rules, or sensitive-path guards (`.git/`, `.claude/`, `.vscode/`).

### The Real Implementation (`services/tools/toolHooks.ts`)

`services/tools/toolHooks.ts` bridges `utils/hooks.ts` into four typed lifecycle adapters (containing zero direct `feature()`, `USER_TYPE`, GrowthBook, or env-var gates):

1. **`runPreToolUseHooks()` (`services/tools/toolHooks.ts:435-650`):** Translates `executePreToolHooks()` (`utils/hooks.ts:3394-3436`) results into typed events:
   - `blockingError` (exit code 2 or JSON `decision: "block"`) → `{ type: 'hookPermissionResult', hookPermissionResult: { behavior: 'deny', ... } }` (`services/tools/toolHooks.ts:481-498`).
   - `permissionBehavior` (`'allow' | 'ask' | 'deny'`) → `hookPermissionResult` (with `updatedInput` for `'allow'`/`'ask'`).
   - Passthrough `updatedInput` without `permissionBehavior` → `{ type: 'hookUpdatedInput' }` (`services/tools/toolHooks.ts:558-563`), updating `processedInput` before permission evaluation.
   - `additionalContexts` → `hook_additional_context`; `preventContinuation`/`stopReason` → deferred post-call stop flag; signal abort or thrown hook error → `hook_cancelled`/`hook_error_during_execution` + `{ type: 'stop' }` (`services/tools/toolHooks.ts:582-648`), halting before `canUseTool`.
2. **`resolveHookPermissionDecision()` (`services/tools/toolHooks.ts:332-433`):** Arbitrates hook permission decisions against rule-based permissions and `canUseTool`:

```ts
// services/tools/toolHooks.ts:347-406
if (hookPermissionResult?.behavior === 'allow') {
  const hookInput = hookPermissionResult.updatedInput ?? input
  // ...
  const interactionSatisfied =
    requiresInteraction && hookPermissionResult.updatedInput !== undefined

  if ((requiresInteraction && !interactionSatisfied) || requireCanUseTool) {
    // ...
  }

  // Hook allow skips the interactive prompt, but deny/ask rules still apply.
  const ruleCheck = await checkRuleBasedPermissions(
    tool,
    hookInput,
    toolUseContext,
  )
  if (ruleCheck === null) {
    // ...
    return { decision: hookPermissionResult, input: hookInput }
  }
  if (ruleCheck.behavior === 'deny') {
    // ...
    return { decision: ruleCheck, input: hookInput }
  }
  // ask rule — dialog required despite hook approval
  // ...
}
```

   - **`'allow'`:** Only skips the interactive prompt when `requiresUserInteraction()` is false (or satisfied via `updatedInput`), `requireCanUseTool` is false, **and** `checkRuleBasedPermissions()` (`utils/permissions/permissions.ts:1071-1155`) returns `null`. A `'deny'` rule overrides immediately; an `'ask'` rule or `safetyCheck` sensitive-path guard forces `canUseTool()`.
   - **`'deny'` (`services/tools/toolHooks.ts:408-411`):** Short-circuits `canUseTool()`.
   - **`'ask'` or `undefined` (`services/tools/toolHooks.ts:413-432`):** Passes `forceDecision` on `'ask'` so `canUseTool()` prompts with the hook's message even when allow rules or modes would auto-approve.
3. **Auto-mode `PermissionDenied` hooks (`services/tools/toolExecution.ts:1075-1101`):** Behind compile-time `feature('TRANSCRIPT_CLASSIFIER')`, when the `auto-mode` classifier denies a tool, `executePermissionDeniedHooks()` runs; any `{ retry: true }` appends an `isMeta: true` retry hint.
4. **`runPostToolUseHooks()` & `runPostToolUseFailureHooks()` (`services/tools/toolHooks.ts:39-319`):**
   - Both fix `#31301`: JSON `{ decision: "block" }` hooks yield both `{ blockingError }` and `{ message: hook_blocking_error }`, so both adapters drop `hook_blocking_error` from `result.message` and emit it once from `result.blockingError` (`services/tools/toolHooks.ts:90-115`, `services/tools/toolHooks.ts:245-267`).
   - On `preventContinuation`, `runPostToolUseHooks()` yields `hook_stopped_continuation` and returns early (`services/tools/toolHooks.ts:118-130`).
   - **MCP-only `updatedMCPToolOutput` (`services/tools/toolHooks.ts:146-151`):** Explains the `// TOOD(hackyon)` split at `services/tools/toolExecution.ts:1476`: non-MCP tools run `addToolResult(toolOutput, mappedToolResultBlock)` *before* `PostToolUse` (reusing `processPreMappedToolResultBlock()`), while MCP tools run `PostToolUse` first—buffering hook messages in `hookResults` (`services/tools/toolExecution.ts:1498-1513`)—and then call `addToolResult(toolOutput)` (`services/tools/toolExecution.ts:1540-1542`) so `processToolResultBlock()` maps the possibly rewritten output from scratch before flushing `hookResults` (`services/tools/toolExecution.ts:1585-1587`).

> [!IMPORTANT]
> **The `inc-4788` Security Invariant (`services/tools/toolHooks.ts:324-325`, `services/tools/toolHooks.ts:372-405`):** A `PreToolUse` `allow` hook can **never** bypass settings `deny` rules, `ask` rules, `safetyCheck` sensitive-path guards, `requireCanUseTool`, or unsatisfied `requiresUserInteraction()` tools.

### Explicit Forward Seams

- **[Chapter 11](11-the-permission-engine.md):** `CanUseToolFn` (`hooks/useCanUseTool.tsx:27`), `PermissionDecision`/`PermissionResult` (`types/permissions.ts:174-324`), and `checkRuleBasedPermissions()` steps 1a–1d and 1f–1g (`utils/permissions/permissions.ts:1069-1156`; step 1e is pre-checked by `resolveHookPermissionDecision()`).
- **Chapter 13 (The Hook System):** Hook execution backends (`utils/hooks.ts:3394-3562`), multi-hook `deny > ask > allow` aggregation (`utils/hooks.ts:2820-2847`), and `suppressOutput` filtering (`utils/hooks.ts:2557-2596`).

---

## 3. Batch Orchestration: Partitioning Concurrency & Context Modifiers

### The Problem

An assistant turn emitting `[Read1, Read2, Edit1, Read3, Bash1, Bash2]` needs parallel reads without overlapping mutations. Worse, racing concurrent async generators delivers updates in completion order—eagerly applying `contextModifier` callbacks (`Tool.ts:329-330`) as tools finish would make `ToolUseContext` depend on I/O timing.

### The Real Implementation (`services/tools/toolOrchestration.ts`)

1. **Fail-closed partitioning (`partitionToolCalls()`, `services/tools/toolOrchestration.ts:91-116`):**

```ts
// services/tools/toolOrchestration.ts:91-116
function partitionToolCalls(
  toolUseMessages: ToolUseBlock[],
  toolUseContext: ToolUseContext,
): Batch[] {
  return toolUseMessages.reduce((acc: Batch[], toolUse) => {
    const tool = findToolByName(toolUseContext.options.tools, toolUse.name)
    const parsedInput = tool?.inputSchema.safeParse(toolUse.input)
    const isConcurrencySafe = parsedInput?.success
      ? (() => {
          try {
            return Boolean(tool?.isConcurrencySafe(parsedInput.data))
          } catch {
            // If isConcurrencySafe throws (e.g., due to shell-quote parse failure),
            // treat as not concurrency-safe to be conservative
            return false
          }
        })()
      : false
    if (isConcurrencySafe && acc[acc.length - 1]?.isConcurrencySafe) {
      acc[acc.length - 1]!.blocks.push(toolUse)
    } else {
      acc.push({ isConcurrencySafe, blocks: [toolUse] })
    }
    return acc
  }, [])
}
```

   Unknown tools, invalid Zod inputs, and throwing `isConcurrencySafe()` predicates all fail closed to `false`, isolating each unsafe call into a singleton serial batch while coalescing contiguous safe calls and preserving relative order (`[concurrent(Read1, Read2), serial(Edit1), concurrent(Read3), serial(Bash1), serial(Bash2)]`).
2. **Bounded concurrency via `all()` (`services/tools/toolOrchestration.ts:8-12`, `services/tools/toolOrchestration.ts:152-177`):** `runToolsConcurrently()` tracks `setInProgressToolUseIDs` and feeds per-tool `runToolUse()` generators into [Chapter 01](01-atoms-types-stores-and-primitives.md)'s `all()` (`utils/generators.ts:32-72`), capped by `getMaxToolUseConcurrency()`: `parseInt(process.env.CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY || '', 10) || 10`. Note honestly: there is no upper/lower clamp beyond `|| 10`—unset, `0`, or `NaN` fall back to `10`, positive integers pass through unbounded, and a negative integer like `'-1'` is truthy and would starve `all()`'s fill loop (`utils/generators.ts:51`).
3. **Deterministic block-order modifier replay (`services/tools/toolOrchestration.ts:30-80`):** During a concurrent batch (`services/tools/toolOrchestration.ts:31-63`), all tools share the pre-batch `currentContext`; any `update.contextModifier` is buffered in `queuedContextModifiers[toolUseID]` while messages yield with untouched `currentContext`. After the batch finishes, `services/tools/toolOrchestration.ts:54-63` replays `queuedContextModifiers[block.id]` in **original `blocks` order** and yields `{ newContext: currentContext }`. Serial batches (`runToolsSerially()`, `services/tools/toolOrchestration.ts:118-150`) apply each modifier immediately (`services/tools/toolOrchestration.ts:140-142`). Today, `tools/SkillTool/SkillTool.ts:775-839` (`allowedTools`, `mainLoopModel`, and `effortValue`, inheriting fail-closed `isConcurrencySafe: false`) is the sole `contextModifier` producer in this checkout.

---

## 4. Executing While the Model Still Talks: `StreamingToolExecutor`

### The Problem

Waiting for stream completion before launching tools leaves I/O idle while the model streams prose. Executing mid-stream requires three guarantees: serial tools must still block concurrent execution, parallel `Bash` failures must cancel sibling commands *without* killing the turn while permission rejections *must* end the turn, and streaming/model fallbacks must cleanly discard orphaned work.

### The Real Implementation (`services/tools/StreamingToolExecutor.ts`)

Enabled by GrowthBook gate `'tengu_streaming_tool_execution2'` (`query/config.ts:33-35`), `StreamingToolExecutor` (`services/tools/StreamingToolExecutor.ts:40-530`) tracks each tool through `'queued' | 'executing' | 'completed' | 'yielded'` (`services/tools/StreamingToolExecutor.ts:19-32`):

- **Admission & serial barrier (`services/tools/StreamingToolExecutor.ts:76-151`):** `query.ts:842` calls `addTool(block, message)` mid-stream. Unknown tools become `'completed'` immediately with `<tool_use_error>` (`services/tools/StreamingToolExecutor.ts:78-102`). Known tools run fail-closed `safeParse` + `isConcurrencySafe()`, enqueue, and invoke `processQueue()`. `canExecuteTool()` (`services/tools/StreamingToolExecutor.ts:129-135`) enforces exclusive access for unsafe tools; inside `processQueue()`, `if (!tool.isConcurrencySafe) break` (`services/tools/StreamingToolExecutor.ts:148`) prevents later safe tools from leapfrogging a waiting mutator.
- **Progress wake-up & draining (`services/tools/StreamingToolExecutor.ts:412-490`):** Mid-stream `getCompletedResults()` drains synchronously; post-stream `getRemainingResults()` races active tool promises against a `progressPromise` woken by `progressAvailableResolve` (`services/tools/StreamingToolExecutor.ts:371-374`, `services/tools/StreamingToolExecutor.ts:467-484`) so live progress streams immediately.
- **3-level `AbortController` tree (`utils/abortController.ts:68-99`):** `createChildAbortController()` links parent→child via `WeakRef` + `{ once: true }` for **downward-only** cascades:

```text
toolUseContext.abortController            (Level 1: turn-scoped, query.ts)
  │  downward WeakRef cascade               ▲  upward bubble-up ONLY if
  ▼                                         │  reason !== 'sibling_error'
this.siblingAbortController               (Level 2: batch-scoped, Bash cancel)
  │  downward WeakRef cascade               │  && !parent.aborted
  ▼                                         │  && !this.discarded
toolAbortController (per tool) ─────────────┘  (Level 3: passed to runToolUse)
```

`executeTool()` wires Level 3 (`services/tools/StreamingToolExecutor.ts:294-325`):

```ts
// services/tools/StreamingToolExecutor.ts:294-325
// Per-tool child controller. Lets siblingAbortController kill running
// subprocesses (Bash spawns listen to this signal) when a Bash error
// cascades. Permission-dialog rejection also aborts this controller
// (PermissionContext.ts cancelAndAbort) — that abort must bubble up to
// the query controller so the query loop's post-tool abort check ends
// the turn. Without bubble-up, ExitPlanMode "clear context + auto"
// sends REJECT_MESSAGE to the model instead of aborting (#21056 regression).
const toolAbortController = createChildAbortController(
  this.siblingAbortController,
)
toolAbortController.signal.addEventListener(
  'abort',
  () => {
    if (
      toolAbortController.signal.reason !== 'sibling_error' &&
      !this.toolUseContext.abortController.signal.aborted &&
      !this.discarded
    ) {
      this.toolUseContext.abortController.abort(
        toolAbortController.signal.reason,
      )
    }
  },
  { once: true },
)

const generator = runToolUse(
  tool.block,
  tool.assistantMessage,
  this.canUseTool,
  { ...this.toolUseContext, abortController: toolAbortController },
)
```

And handles errors and `contextModifier`s on completion (`services/tools/StreamingToolExecutor.ts:354-395`):

```ts
// services/tools/StreamingToolExecutor.ts:354-395
  if (isErrorResult) {
    thisToolErrored = true
    // Only Bash errors cancel siblings. Bash commands often have implicit
    // dependency chains (e.g. mkdir fails → subsequent commands pointless).
    // Read/WebFetch/etc are independent — one failure shouldn't nuke the rest.
    if (tool.block.name === BASH_TOOL_NAME) {
      this.hasErrored = true
      this.erroredToolDescription = this.getToolDescription(tool)
      this.siblingAbortController.abort('sibling_error')
    }
  }
// ...
// NOTE: we currently don't support context modifiers for concurrent
//       tools. None are actively being used, but if we want to use
//       them in concurrent tools, we need to support that here.
if (!tool.isConcurrencySafe && contextModifiers.length > 0) {
  for (const modifier of contextModifiers) {
    this.toolUseContext = modifier(this.toolUseContext)
  }
}
```

- **Why the asymmetry works:** `siblingAbortController.abort('sibling_error')` kills sibling `Bash` subprocesses without triggering the upward bubble-up, keeping `toolUseContext.abortController` un-aborted so `query.ts:1485` returns the error and synthetic sibling cancellations to the model. Permission-dialog rejection (`hooks/toolPermission/PermissionContext.ts:154-173`, `cancelAndAbort`) aborts `toolAbortController` with a non-`'sibling_error'` reason, bubbling up to Level 1 to end the turn (`#21056 regression`).
- **Interrupts, synthetic pairing & `discard()`:** `getAbortReason()` (`services/tools/StreamingToolExecutor.ts:210-231`) checks `discarded` → `hasErrored` → parent abort; on submit-interrupt (`reason === 'interrupt'`), only tools whose `interruptBehavior()` returns `'cancel'` (`Tool.ts:407-416`, fail-safe `'block'` at `services/tools/StreamingToolExecutor.ts:235`) cancel. `createSyntheticErrorMessage()` (`services/tools/StreamingToolExecutor.ts:153-205`, using `withMemoryCorrectionHint(REJECT_MESSAGE)` transitively behind GrowthBook `'tengu_amber_prism'`) guarantees valid `tool_result` pairing ([Chapter 03](03-command-and-message-contracts.md)). On streaming-to-non-streaming fallback (`query.ts:733-740`, triggered from `services/api/claude.ts:2509-2511` and `services/api/claude.ts:2629-2631`) and `FallbackTriggeredError` (`query.ts:912-919`), `query.ts` calls `discard()` (`services/tools/StreamingToolExecutor.ts:69-71`), which drops future yields and blocks orphaned bubble-up via `!this.discarded`.

> [!WARNING]
> **Four Real-Code Caveats in `StreamingToolExecutor.ts`:**
> 1. **Completion order across safe tools (`services/tools/StreamingToolExecutor.ts:436`):** Despite the docstring (`services/tools/StreamingToolExecutor.ts:38`), `getCompletedResults()` only `break`s on `tool.status === 'executing' && !tool.isConcurrencySafe`. Unsafe tools are strict barriers and `pendingProgress` yields immediately, but concurrent safe tools yield in **completion order**.
> 2. **No concurrency cap:** `CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY` is never consulted here.
> 3. **Passive `discard()` (`services/tools/StreamingToolExecutor.ts:69-71`):** Sets `this.discarded = true` without aborting `siblingAbortController`; running subprocesses stop on their next yield or exit (with output dropped).
> 4. **Serial-only `contextModifier` & uncalled `getUpdatedContext()`:** `services/tools/StreamingToolExecutor.ts:388-395` skips modifiers on safe tools (matching `Tool.ts:329-330` and serial `SkillTool`), and `getUpdatedContext()` (`services/tools/StreamingToolExecutor.ts:516-518`) has zero callers—`query.ts:1402-1407` relies solely on `update.newContext` from `getRemainingResults()`, while mid-stream `query.ts:851-861` does not copy `result.newContext`.

---

## 5. Two-Stage Result Persistence & Cache-Safe Budgeting

### The Problem

Naive output capping breaks in three ways: spilling `FileReadTool` to disk traps the model in an infinite `Read` → file → `Read` cycle; ten parallel 40K tools slip past a 50K per-tool cap to form a 400K wire message (`constants/toolLimits.ts:43-44`); and re-evaluating an aggregate budget on historical turns mutates wire bytes and busts the prompt cache ([Chapter 04](04-prompt-engineering-and-cache-boundaries.md)).

### The Real Implementation (`utils/toolResultStorage.ts`)

#### Stage A — Per-Tool Spill at Execution Time (`utils/toolResultStorage.ts:55-365`)

Called from `services/tools/toolExecution.ts:1409-1415` (`processPreMappedToolResultBlock()` for non-MCP; `processToolResultBlock()` for MCP after `PostToolUse`). Both resolve thresholds via `getPersistenceThreshold()` (`utils/toolResultStorage.ts:55-78`):

```ts
// utils/toolResultStorage.ts:55-78
export function getPersistenceThreshold(
  toolName: string,
  declaredMaxResultSizeChars: number,
): number {
  // Infinity = hard opt-out. Read self-bounds via maxTokens; persisting its
  // output to a file the model reads back with Read is circular. Checked
  // before the GB override so tengu_satin_quoll can't force it back on.
  if (!Number.isFinite(declaredMaxResultSizeChars)) {
    return declaredMaxResultSizeChars
  }
  const overrides = getFeatureValue_CACHED_MAY_BE_STALE<Record<
    string,
    number
  > | null>(PERSIST_THRESHOLD_OVERRIDE_FLAG, {})
  const override = overrides?.[toolName]
  if (
    typeof override === 'number' &&
    Number.isFinite(override) &&
    override > 0
  ) {
    return override
  }
  return Math.min(declaredMaxResultSizeChars, DEFAULT_MAX_RESULT_SIZE_CHARS)
}
```

Checking `!Number.isFinite` **before** GrowthBook `'tengu_satin_quoll'` (`utils/toolResultStorage.ts:43`) guarantees a remote flag can never force `FileReadTool`—the sole `maxResultSizeChars: Infinity` tool (`tools/FileReadTool/FileReadTool.ts:342`, self-bounded by `DEFAULT_MAX_OUTPUT_TOKENS = 25000` in `tools/FileReadTool/limits.ts:18`, env var `CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS` at `tools/FileReadTool/limits.ts:25`)—into a circular spill loop. Finite declarations clamp to `DEFAULT_MAX_RESULT_SIZE_CHARS = 50_000` (`constants/toolLimits.ts:13`) while keeping lower caps (`BashTool`/`PowerShellTool` `30_000`, `GrepTool` `20_000`).

Four scars shape `maybePersistLargeToolResult()` (`utils/toolResultStorage.ts:272-334`) and `persistToolResult()` (`utils/toolResultStorage.ts:137-184`):
- **`inc-4586` empty-result guard (`utils/toolResultStorage.ts:280-295`):** Bare `</function_results>\n\n` at the prompt tail caused `capybara` to emit `\n\nHuman:` and end its turn empty; empty results become `(${toolName} completed with no output)`.
- **Image bypass & non-text fail-open (`utils/toolResultStorage.ts:144-151`, `utils/toolResultStorage.ts:302-319`):** Image blocks pass untouched; arrays with non-`text` blocks fail persistence and fail open.
- **`flag: 'wx'` & `EEXIST` idempotency (`utils/toolResultStorage.ts:153-183`):** Writes `<projectDir>/<sessionId>/tool-results/<toolUseId>.(txt|json)` exclusively with `flag: 'wx'`, avoiding stat-then-write races and treating `EEXIST` as an idempotent hit on microcompact replay.
- **Line-snapped preview (`utils/toolResultStorage.ts:189-199`, `utils/toolResultStorage.ts:339-356`):** `generatePreview()` slices `PREVIEW_SIZE_BYTES = 2000` chars (`utils/toolResultStorage.ts:109`), snapping back to `lastNewline` only if `> maxBytes * 0.5`, then wraps size, path, and preview inside `<persisted-output>` ... `</persisted-output>`.

#### Stage B — Per-Message Aggregate Budget & Cache Invariance (`utils/toolResultStorage.ts:367-1012`)

Invoked at the top of `query.ts` (`query.ts:376-394`) via `applyToolResultBudget()`, gated by GrowthBook master kill-switch `'tengu_hawthorn_steeple'` (default `false` in `provisionContentReplacementState()`, `utils/toolResultStorage.ts:447-463`) and window override `'tengu_hawthorn_window'` (default `MAX_TOOL_RESULTS_PER_MESSAGE_CHARS = 200_000` at `constants/toolLimits.ts:49`, `utils/toolResultStorage.ts:421-434`).

`ContentReplacementState` (`utils/toolResultStorage.ts:390-393`) freezes every decision in `seenIds: Set<string>` and stores exact `<persisted-output>` strings in `replacements: Map<string, string>` for zero-I/O, byte-identical replay. `collectCandidatesByMessage()` (`utils/toolResultStorage.ts:600-639`) mirrors [Chapter 03](03-command-and-message-contracts.md)'s `normalizeMessagesForAPI()`—flushing groups only on unseen assistant `message.id` (`seenAsstIds`, `utils/toolResultStorage.ts:623-632`) and matching compacted blocks via `.startsWith('<persisted-output>')` (`utils/toolResultStorage.ts:498-505`) so reading `utils/toolResultStorage.ts` itself is never misclassified. `enforceToolResultBudget()` (`utils/toolResultStorage.ts:769-909`) repeats the `Infinity` skip (`query.ts:389-393`) and enforces atomic state updates:

```ts
// utils/toolResultStorage.ts:816-846
    // Tools with maxResultSizeChars: Infinity (Read) — never persist.
    // Mark as seen (frozen) so the decision sticks across turns. They don't
    // count toward freshSize; if that lets the group slip under budget and
    // the wire message is still large, that's the contract — Read's own
    // maxTokens is the bound, not this wrapper.
    const skipped = fresh.filter(c => shouldSkip(c.toolUseId))
    skipped.forEach(c => state.seenIds.add(c.toolUseId))
    const eligible = fresh.filter(c => !shouldSkip(c.toolUseId))

    const frozenSize = frozen.reduce((sum, c) => sum + c.size, 0)
    const freshSize = eligible.reduce((sum, c) => sum + c.size, 0)

    const selected =
      frozenSize + freshSize > limit
        ? selectFreshToReplace(eligible, frozenSize, limit)
        : []

    // Mark non-persisting candidates as seen NOW (synchronously). IDs
    // selected for persist are marked seen AFTER the await, alongside
    // replacements.set — keeps the pair atomic under observation so no
    // concurrent reader (once subagents share state) ever sees X∈seenIds
    // but X∉replacements, which would misclassify X as frozen and send
    // full content while the main thread sends the preview → cache miss.
    const selectedIds = new Set(selected.map(c => c.toolUseId))
    candidates
      .filter(c => !selectedIds.has(c.toolUseId))
      .forEach(c => state.seenIds.add(c.toolUseId))

    if (selected.length === 0) continue
    messagesOverBudget++
    toPersist.push(...selected)
```

Selected blocks are chosen largest-first (`selectFreshToReplace()`, `utils/toolResultStorage.ts:675-692`), persisted concurrently via `Promise.all()`, and committed to `seenIds` + `replacements` **together post-await** (`utils/toolResultStorage.ts:855-869`). Cache-sharing forks call `cloneContentReplacementState()` (`utils/forkedAgent.ts:399-403`, `utils/toolResultStorage.ts:405-412`); resumable transcripts (`agent:*`, `repl_main_thread*`) persist records via `recordContentReplacement()` (`utils/sessionStorage.ts:1494-1499`) and rebuild state on resume via `reconstructContentReplacementState()` (`screens/REPL.tsx:1924`, `utils/toolResultStorage.ts:960-988`) and `reconstructForSubagentResume()` (`tools/AgentTool/resumeAgent.ts:75-79`, `utils/toolResultStorage.ts:1001-1012`).

---

## Putting the Layer Together

```mermaid
flowchart TD
  Stream["Ch 05 queryModelWithStreaming() yields ToolUseBlock list"] --> Gate{"tengu_streaming_tool_execution2?"}
  Gate -->|"true (mid-stream)"| STE["StreamingToolExecutor.addTool() + processQueue()"]
  Gate -->|"false (post-stream)"| Orch["runTools(): partitionToolCalls() + all() cap 10"]
  STE --> Run["runToolUse() 8-step lifecycle (toolExecution.ts)"]
  Orch --> Run
  Run --> Pre["Zod safeParse -> validateInput -> backfillObservableInput clone"]
  Pre --> Hooks["runPreToolUseHooks() -> resolveHookPermissionDecision()"]
  Hooks -->|"deny / error / abort"| Err["is_error: true tool_result (no PostToolUseFailure)"]
  Pre -->|"invalid"| Err
  Hooks -->|"allow"| Call["tool.call() + Stage A (persisted-output spill / Infinity opt-out)"]
  Call -->|"success"| Post["runPostToolUseHooks() (MCP defers addToolResult)"]
  Call -->|"exception / AbortError"| Fail["classifyToolError() (non-abort) + runPostToolUseFailureHooks()"]
  Post --> Drain["getCompletedResults() / getRemainingResults() / runTools()"]
  Err --> Drain
  Fail --> Drain
  Drain --> StageB["Next turn query.ts: Stage B applyToolResultBudget()"]
```

> [!NOTE]
> **Snapshot Absences & Comment-Only Flag Mentions:** All five primary files import message types from `types/message.ts` (`services/tools/toolExecution.ts:53-59`, `services/tools/toolHooks.ts:10-14`, `services/tools/toolOrchestration.ts:4`, `services/tools/StreamingToolExecutor.ts:10`, `utils/toolResultStorage.ts:18`), which is **absent from this snapshot**—all `Message` fields above are observed from call sites only. Likewise, `services/tools/toolHooks.ts:329-330` mentions `REPLTool/toolWrappers.ts` (`tools/REPLTool/toolWrappers.ts`) only in JSDoc; that file is **absent from this snapshot** (`services/tools/toolExecution.ts` is the sole caller present). Finally, `utils/toolResultStorage.ts:997-999` cites `feature('TRANSCRIPT_CLASSIFIER')` strictly inside a comment explaining `AgentTool.tsx`'s DCE complexity cliff—it is **not** an executed gate in `utils/toolResultStorage.ts`.

---

## How This Snaps Into the Next Layer

Every mechanism in this chapter snaps directly into `query.ts` in [Chapter 07](07-the-heartbeat-query-loop.md):

1. **Pre-API Stage B budget (`query.ts:379-394`):** Runs `applyToolResultBudget()` with `toolUseContext.contentReplacementState` and the `!Number.isFinite(t.maxResultSizeChars)` opt-out set.
2. **Mid-stream bridge & fallback resets (`query.ts:561-568`, `query.ts:733-740`, `query.ts:826-862`, `query.ts:912-919`):** Under `config.gates.streamingToolExecution` (`query/config.ts:33-35`), `query.ts` feeds `ToolUseBlock`s into `StreamingToolExecutor.addTool()`, drains `getCompletedResults()` mid-stream, and calls `discard()` + swaps in a fresh executor on streaming fallback or `FallbackTriggeredError`.
3. **Post-stream drain, hook stop & next turn (`query.ts:1380-1408`, `query.ts:1485-1521`, `query.ts:1715-1727`):** Drains `getRemainingResults()` or calls `runTools()`, sets `shouldPreventContinuation` on `hook_stopped_continuation` (`query.ts:1388-1393`), carries `update.newContext` into `updatedToolUseContext` (`query.ts:1402-1407`), checks `toolUseContext.abortController.signal.aborted` (`query.ts:1485-1516`), and loops `[...messagesForQuery, ...assistantMessages, ...toolResults]` with `updatedToolUseContext` into the next turn.

Downstream seams continue in [Chapter 09](09-five-layer-compaction-pipeline.md) (compaction Stages 2–5 after `applyToolResultBudget()`), [Chapter 11](11-the-permission-engine.md) (`canUseTool` and `checkRuleBasedPermissions()`), and **Chapter 13 (The Hook System)** (`utils/hooks.ts`).

---

## Reading Exercises & Code Checkpoints

1. **Audit the `inc-4788` hook-vs-rule permission boundary:**
   ```sh
   rg -n "checkRuleBasedPermissions|requiresUserInteraction|forceDecision" services/tools/toolHooks.ts
   ```
   Trace all three branches in `resolveHookPermissionDecision()` (`services/tools/toolHooks.ts:332-433`) and verify which combinations of hook `allow` + `updatedInput` still invoke `canUseTool()`.
2. **Verify concurrency partitioning and block-order `contextModifier` replay:**
   ```sh
   rg -n "partitionToolCalls|queuedContextModifiers|CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY" services/tools/toolOrchestration.ts
   ```
   Trace how `runTools()` (`services/tools/toolOrchestration.ts:19-82`) handles `[Read, Read, Skill, Read]`, and explain what happens when `CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY` is `'0'` versus `'-1'`.
3. **Inspect the 3-level `AbortController` tree and real-code caveats in `StreamingToolExecutor`:**
   ```sh
   rg -n "createChildAbortController|siblingAbortController|BASH_TOOL_NAME|sibling_error|isConcurrencySafe && contextModifiers" services/tools/StreamingToolExecutor.ts
   ```
   Cross-reference `services/tools/StreamingToolExecutor.ts:304-318` and `services/tools/StreamingToolExecutor.ts:359-363` with `query.ts:1485-1516` to see why a failed `Bash` command keeps the turn alive while a permission rejection aborts it.
4. **Trace `maxResultSizeChars: Infinity` and all three GrowthBook gates across Stages A and B:**
   ```sh
   rg -n "Number\.isFinite|maxResultSizeChars: Infinity|tengu_(satin_quoll|hawthorn_)" utils/toolResultStorage.ts tools/FileReadTool/FileReadTool.ts query.ts
   ```
   Verify why `!Number.isFinite` is checked in both `getPersistenceThreshold()` (`utils/toolResultStorage.ts:62`) and `query.ts:391`, and trace what happens when `'tengu_hawthorn_steeple'` is `false`.


---

<!-- chapters/07-the-heartbeat-query-loop.md — https://reverseengineeringclaudecode.com/chapters/07-the-heartbeat-query-loop -->

# Chapter 07 — The Heartbeat: `query.ts` and the Agentic Turn State Machine

> **Layer:** Layer 2 (The Agent Engine)
> **Prerequisites:** [Chapter 01](01-atoms-types-stores-and-primitives.md), [Chapter 02](02-the-tool-contract.md), [Chapter 03](03-command-and-message-contracts.md), [Chapter 04](04-prompt-engineering-and-cache-boundaries.md), [Chapter 05](05-talking-to-the-model.md), [Chapter 06](06-executing-tools.md)
> **Primary Source Files:**
> - [`query.ts`](../../query.ts) — `query()` wrapper and `queryLoop()` single-turn, multi-step `AsyncGenerator` state machine (1,729 lines)
> - [`query/config.ts`](../../query/config.ts) — `QueryConfig` and `buildQueryConfig()` immutable per-turn runtime gate snapshot (46 lines)
> - [`query/deps.ts`](../../query/deps.ts) — `QueryDeps` and `productionDeps()` narrow I/O dependency injection seam (40 lines)
> - [`query/stopHooks.ts`](../../query/stopHooks.ts) — `handleStopHooks()` end-of-turn hooks, `CacheSafeParams` snapshot, and background forks (473 lines)
> - [`query/tokenBudget.ts`](../../query/tokenBudget.ts) — `BudgetTracker`, `createBudgetTracker()`, and `checkTokenBudget()` auto-continue guard (93 lines)
> - `query/transitions.ts` *(absent from this snapshot — `Continue` and `Terminal` unions are reconstructed verbatim from `query.ts` call sites only)*

---

## Why This Layer Exists

[Chapter 06](06-executing-tools.md) delivered the tool primitives: `applyToolResultBudget()`, `StreamingToolExecutor`, and `runTools()`. Earlier chapters built normalized messages ([Chapter 03](03-command-and-message-contracts.md)), cache-stable prompts ([Chapter 04](04-prompt-engineering-and-cache-boundaries.md)), and streaming model I/O with `FallbackTriggeredError` ([Chapter 05](05-talking-to-the-model.md)).

[`query.ts`](../../query.ts) and its four `query/` companions (`2,381` lines total) stitch those pieces into a single-turn, multi-step `AsyncGenerator` state machine. One prompt can span ten model calls, overlapped tools, mid-stream fallbacks, silent overflow or truncation recovery, and stop-hook or budget continuations—driving every REPL turn, SDK request, subagent, fork, background task, and agent hook.

---

## 1. The Wrapper, the Flat State Machine, and Absent `query/transitions.ts`

### The Problem

An early agent loop starts as a recursive `AsyncGenerator`: call the model, run tools, `yield* query(next)`. At scale, recursion retains O(turns) nested frames holding stale `messagesForQuery` arrays, complicates one-time setup, and scatters flag resets across closures.

### The Mechanism: `QueryParams`, No-`finally` `query()`, and Whole-Object `State`

`QueryParams` (`query.ts:181-199`) defines 13 fields: 7 required (`messages`, `systemPrompt`, `userContext`, `systemContext`, `canUseTool`, `toolUseContext`, `querySource`) and 6 optional (`fallbackModel`, `maxOutputTokensOverride`, `maxTurns`, `skipCacheWrite`, `taskBudget`, `deps`). Notably, `abortController` lives on `toolUseContext`, and queued commands live in `utils/messageQueueManager.ts:525-547`.

Cross-iteration state lives in a 10-field `State` record (`query.ts:204-217`), wrapped by the public `query()` entrypoint (`query.ts:219-239`):

```ts
// query.ts:204-217
type State = {
  messages: Message[]
  toolUseContext: ToolUseContext
  autoCompactTracking: AutoCompactTrackingState | undefined
  maxOutputTokensRecoveryCount: number
  hasAttemptedReactiveCompact: boolean
  maxOutputTokensOverride: number | undefined
  pendingToolUseSummary: Promise<ToolUseSummaryMessage | null> | undefined
  stopHookActive: boolean | undefined
  turnCount: number
  // Why the previous iteration continued. Undefined on first iteration.
  // Lets tests assert recovery paths fired without inspecting message contents.
  transition: Continue | undefined
}
```

```ts
// query.ts:219-239
export async function* query(
  params: QueryParams,
): AsyncGenerator<
  | StreamEvent
  | RequestStartEvent
  | Message
  | TombstoneMessage
  | ToolUseSummaryMessage,
  Terminal
> {
  const consumedCommandUuids: string[] = []
  const terminal = yield* queryLoop(params, consumedCommandUuids)
  // Only reached if queryLoop returned normally. Skipped on throw (error
  // propagates through yield*) and on .return() (Return completion closes
  // both generators). This gives the same asymmetric started-without-completed
  // signal as print.ts's drainCommandQueue when the turn fails.
  for (const uuid of consumedCommandUuids) {
    notifyCommandLifecycle(uuid, 'completed')
  }
  return terminal
}
```

At `query.ts:229-238`, there is **deliberately no `finally` block**. Mid-turn consumed commands push their UUIDs into `consumedCommandUuids` and emit `notifyCommandLifecycle(cmd.uuid, 'started')` (`query.ts:1632-1643`). Omitting `finally` fires `'completed'` only on a normal `Terminal` return; throws or `.return()` closes preserve the asymmetric `started`-without-`completed` failure signal from `cli/print.ts:2006-2008` and `cli/print.ts:2248-2250`.

Contrast that with `using pendingMemoryPrefetch = startRelevantMemoryPrefetch(...)` (`query.ts:301-304`): TC39 `using` invokes `[Symbol.dispose]()` (`utils/attachments.ts:2410-2418`) on **every** exit path (`return`, `throw`, `.return()`), aborting prefetches across all 12 `return` sites automatically.

`queryLoop()` (`query.ts:241-1729`) runs a flat `while (true)` loop (`query.ts:307-1728`) retaining recursion fossils (`query.ts:1411`, `query.ts:1678`, `queryCheckpoint('query_recursive_call')` at `query.ts:1714`). Each iteration destructures `State` (`query.ts:311-321`), reassigning only `toolUseContext` mid-iteration (`query.ts:360`, `query.ts:546`) and omitting `transition`.

Every `continue` writes a full `State` literal with no `{ ...state }` spread (`state = next` at six sites; direct literal at `query.ts:1321`), forcing explicit reset choices on all 10 fields. Five bindings stay off `State` (`query.ts:243`, `query.ts:280-304`): `consumedCommandUuids`, `budgetTracker`, `taskBudgetRemaining` (kept loop-local at `query.ts:289-291`), `config`, and `using pendingMemoryPrefetch`.

### Reconstructing Snapshot-Absent `query/transitions.ts` from Call Sites

`query.ts:104` executes `import type { Terminal, Continue } from './query/transitions.js'`, the sole code import in the repo. `query/transitions.ts` is **absent from this snapshot**. Every variant below is observed directly at `query.ts`'s 7 `transition` writes and 12 `return` sites; any unused union members or helper guards in the absent file are unobservable here.

| # | `Continue` literal (`query.ts` lines) | Trigger & key `State` updates |
|---:|---|---|
| 1 | `{ reason: 'collapse_drain_retry', committed }` (`query.ts:1109-1112`) | `feature('CONTEXT_COLLAPSE')` PTL drain (`committed > 0`); `turnCount` unchanged |
| 2 | `{ reason: 'reactive_compact_retry' }` (`query.ts:1162`) | `feature('REACTIVE_COMPACT')` PTL/media compact; latches `hasAttemptedReactiveCompact: true`, resets `autoCompactTracking` |
| 3 | `{ reason: 'max_output_tokens_escalate' }` (`query.ts:1217`) | `'tengu_otk_slot_v1'` 8k-to-64k clean retry; sets `maxOutputTokensOverride: ESCALATED_MAX_TOKENS` |
| 4 | `{ reason: 'max_output_tokens_recovery', attempt }` (`query.ts:1245-1248`) | Truncation nudge (`attempt` 1..3); increments `maxOutputTokensRecoveryCount`, clears `maxOutputTokensOverride` |
| 5 | `{ reason: 'stop_hook_blocking' }` (`query.ts:1302`) | Stop/teammate hook blocking errors; sets `stopHookActive: true`, preserves `hasAttemptedReactiveCompact` |
| 6 | `{ reason: 'token_budget_continuation' }` (`query.ts:1338`) | `feature('TOKEN_BUDGET')` under 90%; resets `hasAttemptedReactiveCompact: false` and `stopHookActive: undefined` |
| 7 | `{ reason: 'next_turn' }` (`query.ts:1725`) | Tools done; **sole site incrementing `turnCount`** (`turnCount + 1`), preserves `stopHookActive` |

All 10 `Terminal` variants appear across 12 `return` sites in `queryLoop()` (line `1175` uses a ternary across two variants, while `'image_error'`, `'prompt_too_long'`, and `'completed'` each have two sites):

| Variant (`Terminal.reason`) | Return line(s) in `query.ts` | Exit condition & payload |
|---|---|---|
| `'blocking_limit'` | `query.ts:646` | Pre-API hard token limit (skipped when compact/collapse/reactive owns recovery) |
| `'image_error'` | `query.ts:977`, `query.ts:1175` | `ImageSizeError`/`ImageResizeError` throw, or unrecovered withheld media error (`query.ts:1175` ternary) |
| `'model_error'` | `query.ts:996` | Uncaught `callModel` throw (carries `error`); pairs missing `tool_result`s first |
| `'aborted_streaming'` | `query.ts:1051` | Signal aborted after stream; drains executor or emits cancelled `tool_result`s |
| `'prompt_too_long'` | `query.ts:1175`, `query.ts:1182` | Unrecovered withheld 413 after `reactiveCompact` (`query.ts:1175` ternary) or `CONTEXT_COLLAPSE`-only fallback |
| `'completed'` | `query.ts:1264`, `query.ts:1357` | Unrecovered API error bailout (`query.ts:1264`) or normal turn end (`query.ts:1357`) |
| `'stop_hook_prevented'` | `query.ts:1279` | `handleStopHooks()` returned `preventContinuation: true` (or aborted mid-hook) |
| `'aborted_tools'` | `query.ts:1515` | Signal aborted after tool drain; mirrors `maxTurns` attachment check |
| `'hook_stopped'` | `query.ts:1520` | Tool update yielded `hook_stopped_continuation` (`query.ts:1388-1393`) |
| `'max_turns'` | `query.ts:1711` | `nextTurnCount > maxTurns` after tools (carries `turnCount: nextTurnCount`) |

### Hidden Invariants

- **Only `next_turn` increments `turnCount`:** Starting at `1` (`query.ts:276`), recoveries, stop hooks, and budget nudges never consume `maxTurns`; only tool rollovers increment `turnCount` (`query.ts:1679`, `query.ts:1719`).
- **One runtime reader of `state.transition`:** Every `Continue` logs provenance for tests, yet `state.transition?.reason !== 'collapse_drain_retry'` (`query.ts:1092`) is the *sole* runtime branch reading it.
- **`Terminal` is an exhaustiveness & test contract:** All six production callers use `for await`, discarding `TReturn`. `Terminal` enforces exhaustive exits in `queryLoop()`, supports `.next()` assertions, and scaffolds `step()` extraction (`query/config.ts:8-11`).

---

## 2. Decoupling I/O and Runtime Gates: `QueryDeps`, `QueryConfig`, and Bun DCE

### The Problem

Unit-testing a 1,700-line loop that imports model streaming, compaction, and global flags directly forced 6–8 test files to duplicate per-module `spyOn` boilerplate (`query/deps.ts:8-11`). Yet bundling *every* gate into a config struct breaks Bun's dead-code elimination (DCE) and risks dragging heavy transitive graphs into isolated test shards.

### The Mechanism: Narrow `QueryDeps` and DCE-Safe `QueryConfig`

[`query/deps.ts`](../../query/deps.ts) (`query/deps.ts:21-31`) exposes four narrow I/O seams, paired with `productionDeps()` (`query/deps.ts:33-40`) and wired via `params.deps ?? productionDeps()` (`query.ts:263`):

```ts
// query/deps.ts:21-31
export type QueryDeps = {
  // -- model
  callModel: typeof queryModelWithStreaming

  // -- compaction
  microcompact: typeof microcompactMessages
  autocompact: typeof autoCompactIfNeeded

  // -- platform
  uuid: () => string
}
```

Typing each field with `typeof fn` keeps fakes synchronized with production signatures automatically (`query/deps.ts:13-17`) with zero added module-graph cost for tests already importing `query.ts`. Paired with `State.transition`, tests drive deterministic `callModel`/`autocompact` sequences without ES-module mocking. The four seams plug in at `query.ts:353`, `query.ts:414-418`, `query.ts:454-467`, `query.ts:523`, and `query.ts:659-708`.

[`query/config.ts`](../../query/config.ts) (`query/config.ts:13-46`) snapshots `sessionId` and four runtime gates once at `queryLoop()` entry (`query.ts:295`):

```ts
// query/config.ts:13-46
// Intentionally excludes feature() gates — those are tree-shaking boundaries
// and must stay inline at the guarded blocks for dead-code elimination.
export type QueryConfig = {
  sessionId: SessionId

  // Runtime gates (env/statsig). NOT feature() gates — see above.
  gates: {
    // Statsig — CACHED_MAY_BE_STALE already admits staleness, so snapshotting
    // once per query() call stays within the existing contract.
    streamingToolExecution: boolean
    emitToolUseSummaries: boolean
    isAnt: boolean
    fastModeEnabled: boolean
  }
}

export function buildQueryConfig(): QueryConfig {
  return {
    sessionId: getSessionId(),
    gates: {
      streamingToolExecution: checkStatsigFeatureGate_CACHED_MAY_BE_STALE(
        'tengu_streaming_tool_execution2',
      ),
      emitToolUseSummaries: isEnvTruthy(
        process.env.CLAUDE_CODE_EMIT_TOOL_USE_SUMMARIES,
      ),
      isAnt: process.env.USER_TYPE === 'ant',
      // Inlined from fastMode.ts to avoid pulling its heavy module graph
      // (axios, settings, auth, model, oauth, config) into test shards that
      // didn't previously load it — changes init order and breaks unrelated tests.
      fastModeEnabled: !isEnvTruthy(process.env.CLAUDE_CODE_DISABLE_FAST_MODE),
    },
  }
}
```

### Production Scars & Snapshot Absences

Two hard-won scars live inside `query/config.ts`:

1. **Bun DCE exclusion (`query/config.ts:13-14`, `query.ts:796-798`):** Per [Chapter 00](00-how-to-read-a-1900-file-agent.md), Bun only tree-shakes `feature('...')` branches when `feature()` sits directly inside an `if` or ternary condition. Moving `feature()` into `QueryConfig` would retain internal code in external builds. Note also that `query.ts:588` reads `config.gates.isAnt`, while `query.ts:927` still checks `process.env.USER_TYPE === 'ant'` inline before `stripSignatureBlocks()`.
2. **Inlining `fastModeEnabled` (`query/config.ts:40-43`):** `utils/fastMode.ts:38-40` exports the identical one-line `isFastModeEnabled()`. Importing `utils/fastMode.ts` (`utils/fastMode.ts:1-36`) pulls `axios`, `oauth.js`, `auth.js`, `config.js`, `model.js`, and `settings.js`, shifting init order and breaking unrelated test shards—so `query/config.ts` inlines the check directly.

> [!NOTE]
> **Snapshot Absences Across Chapter 07's Five Files:** Exactly **9 imported modules are absent** (none in `config.ts`, `deps.ts`, or `tokenBudget.ts`):
> - **3 unconditional `import type` absences:** `query/transitions.js` (`query.ts:104`), `types/message.js` (`query.ts:30-39`, `query/stopHooks.ts:10-18`), `constants/querySource.js` (`query.ts:94`, `query/stopHooks.ts:51`).
> - **6 `feature()`-gated `require()` absences:** `services/compact/reactiveCompact.js` (`REACTIVE_COMPACT`, `query.ts:15-17`), `services/contextCollapse/index.js` (`CONTEXT_COLLAPSE`, `query.ts:18-20`), `services/skillSearch/prefetch.js` (`EXPERIMENTAL_SKILL_SEARCH`, `query.ts:66-68`), `jobs/classifier.js` (`TEMPLATES`, live at `query/stopHooks.ts:45-47`; unused `jobClassifier` leftover at `query.ts:69-71`), `services/compact/snipCompact.js` (`HISTORY_SNIP`, `query.ts:115-117`), `utils/taskSummary.js` (`BG_SESSIONS`, `query.ts:118-120`).
> - **2 `feature()`-gated modules ARE present on disk:** [`utils/computerUse/cleanup.ts`](../../utils/computerUse/cleanup.ts) (`CHICAGO_MCP`) and [`services/extractMemories/extractMemories.ts`](../../services/extractMemories/extractMemories.ts) (`EXTRACT_MEMORIES`).

---

## 3. Streaming Dispatch, `needsFollowUp`, Dual Fallbacks, and Turn Rollover

### The Problem

Streaming into live tools poses four hazards: `stop_reason === 'tool_use'` is unreliable, SDK field backfills must not mutate prompt-cache bytes, streaming and model fallbacks clean up orphans differently, and queued commands cannot interleave with `tool_result` blocks.

### The Mechanism: `needsFollowUp`, Executor Bridging, and Dual Fallbacks

Before streaming (`query.ts:551-568`), `queryLoop()` defines `needsFollowUp` and instantiates `StreamingToolExecutor` behind `config.gates.streamingToolExecution`:

```ts
// query.ts:551-568
const assistantMessages: AssistantMessage[] = []
const toolResults: (UserMessage | AttachmentMessage)[] = []
// @see https://docs.claude.com/en/docs/build-with-claude/tool-use
// Note: stop_reason === 'tool_use' is unreliable -- it's not always set correctly.
// Set during streaming whenever a tool_use block arrives — the sole
// loop-exit signal. If false after streaming, we're done (modulo stop-hook retry).
const toolUseBlocks: ToolUseBlock[] = []
let needsFollowUp = false

queryCheckpoint('query_setup_start')
const useStreamingToolExecution = config.gates.streamingToolExecution
let streamingToolExecutor = useStreamingToolExecution
  ? new StreamingToolExecutor(
      toolUseContext.options.tools,
      canUseTool,
      toolUseContext,
    )
  : null
```

Three production failure modes disqualify `stop_reason === 'tool_use'`:

1. **Per-block emission with late `message_delta` mutation (`services/api/claude.ts:2229-2248`):** `queryModelWithStreaming()` yields each `AssistantMessage` at `content_block_stop` with `stop_reason: null`, mutating only `newMessages.at(-1).message.stop_reason` when `message_delta` arrives. A mid-stream drop leaves `stop_reason` `null` despite an emitted `tool_use`.
2. **Mixed `tool_use` + `max_tokens` truncation (`services/api/claude.ts:2266-2292`):** If a completed `tool_use` block precedes a `max_tokens` cutoff, `claude.ts` appends a synthetic `apiError: 'max_output_tokens'` message. Because `needsFollowUp` flipped `true` on the `tool_use` block (`query.ts:829-835`), `queryLoop()` runs the tool to keep [Chapter 03](03-command-and-message-contracts.md)'s pairing intact while `normalizeMessagesForAPI()` drops `isSyntheticApiErrorMessage` (`utils/messages.ts:2069`) next turn.
3. **3P provider drift:** Bedrock, Vertex, Foundry, and gateways occasionally emit `end_turn` or omit `stop_reason` alongside `tool_use` blocks. Deriving `needsFollowUp` strictly from observed `content.type === 'tool_use'` blocks locks loop continuation to the exact set of `ToolUseBlock`s needing paired `tool_result`s.

Inside the streaming loop (`query.ts:659-863`), three seams connect Ch 05 to Ch 06:

- **Yield-isolated `backfillObservableInput` (`query.ts:742-787`):** `queryLoop()` runs `tool.backfillObservableInput(inputCopy)` on a shallow copy and clones `yieldMessage` **only** when backfill *adds* new keys (`query.ts:771-773`). In-place overwrites (e.g., `~` path expansion) are skipped to keep transcript hashes stable, and unmodified `message` is always pushed into `assistantMessages` (`query.ts:827`) to preserve prompt-cache bytes.
- **`StreamingToolExecutor` vs. `runTools()` (`query.ts:837-862`, `query.ts:1366-1408`):** Mid-stream, `queryLoop()` enqueues blocks via `addTool()` and drains `getCompletedResults()` into `toolResults` (skipping `result.newContext`). On abort (`query.ts:1016-1029`), it drains `getRemainingResults()` or runs `yieldMissingToolResultBlocks()`. Normally, `query.ts:1380-1408` drains `getRemainingResults()` or `runTools()`, flags `hook_stopped_continuation`, and merges `update.newContext`; `getUpdatedContext()` is never called.
- **Dual fallbacks inside `while (attemptWithFallback)` (`query.ts:654-954`):**

| Mechanism | Streaming-to-non-streaming (`query.ts:678-741`) | Model fallback (`query.ts:894-953`) |
|---|---|---|
| Trigger | `onStreamingFallback()` (`query.ts:678-680`) sets `streamingFallbackOccured = true` | `FallbackTriggeredError` caught if `fallbackModel` is set (`query.ts:894`; else rethrows to `model_error`) |
| Orphan cleanup | Yields `{ type: 'tombstone', message }` (`query.ts:716-718`) to drop broken thinking signatures | Calls `yield* yieldMissingToolResultBlocks(assistantMessages, 'Model fallback triggered')` (`query.ts:900-903`) |
| Reset & retry | Clears arrays/`needsFollowUp`, calls `discard()` + fresh executor (`query.ts:725-740`), stays in stream | Same reset (`query.ts:904-919`), swaps `currentModel` & `mainLoopModel` (`query.ts:896`, `query.ts:922`), `USER_TYPE === 'ant'` `stripSignatureBlocks()` (`query.ts:927-929`), yields `'warning'`, `continue`s inner loop (`query.ts:950`) |

### Post-Tool Housekeeping, Exit Guards, and Turn Rollover (`query.ts:1411-1728`)

After tools finish (`query.ts:1409`), `queryLoop()` runs an exact four-part housekeeping pass:

1. **Latency-hidden summaries (`query.ts:1412-1482`, `query.ts:1055-1060`):** When `config.gates.emitToolUseSummaries` is true, `!aborted`, and `!agentId`, fires Haiku `generateToolUseSummary()` without `await`ing into `nextPendingToolUseSummary`, awaiting and yielding it after the *next* iteration's 5–30s stream.
2. **Abort & hook-stop guards (`query.ts:1485-1521`):** Like `aborted_streaming` (`query.ts:1033-1051`), `aborted_tools` runs `feature('CHICAGO_MCP') && !agentId` cleanup (`query.ts:1489-1498`) and skips interruption text when `signal.reason === 'interrupt'`; unlike `aborted_streaming` (`toolUse: false`), `aborted_tools` yields `createUserInterruptionMessage({ toolUse: true })`, mirrors the `maxTurns` attachment check (`query.ts:1507-1514`), and returns `{ reason: 'aborted_tools' }`.
   - Next, `shouldPreventContinuation` returns `{ reason: 'hook_stopped' }` (`query.ts:1519-1521`).
3. **Post-tool queue & attachment drain (`query.ts:1535-1643`):** Delayed after tools so user messages never interleave with `tool_result`s (`query.ts:1535-1536`). `sleepRan` (`SLEEP_TOOL_NAME`, `query.ts:1566`) bumps max priority to `'later'` (`utils/messageQueueManager.ts:525-532`); `isSlashCommand` (`utils/messageQueueManager.ts:541-547`) skips slash commands; main threads drain `agentId === undefined` while subagents drain matching `task-notification`s (`query.ts:1567-1578`). Consumed commands then log `'started'` (`query.ts:1632-1643`).
4. **Tool refresh & 1-indexed `maxTurns` (`query.ts:1660-1727`):** `refreshTools()` exposes newly connected MCP servers mid-turn; `feature('BG_SESSIONS')` with `!toolUseContext.agentId` runs `maybeGenerateTaskSummary()` (`query.ts:1685-1702`, `utils/taskSummary.js` absent); then `nextTurnCount = turnCount + 1 > maxTurns` (`query.ts:1679` and `query.ts:1705-1712`) exits `{ reason: 'max_turns', turnCount: nextTurnCount }` (so `maxTurns: 1` allows one model+tool step) or writes `transition: { reason: 'next_turn' }`.

---

## 4. Withheld Error Recovery: Suppress, Recover, Surface Once

### The Problem

`queryModelWithStreaming()` reports prompt-too-long (`services/api/errors.ts:62-77`), media-size rejections, and `max_tokens` cutoffs (`services/api/claude.ts:2266-2292`) by yielding synthetic `AssistantMessage`s with `isApiErrorMessage: true`. SDK clients like Cowork and Desktop tear down the session on *any* yielded error (`query.ts:167-172`), so forwarding recoverable errors mid-stream disconnects the consumer while recovery retries into a dead pipe.

### The Mechanism: Pre-API Skip, Streaming Withholding, and the 4-Stage Ladder

Pre-API (`query.ts:612-648`), `calculateTokenWarningState(...).isAtBlockingLimit` normally returns `{ reason: 'blocking_limit' }` (`query.ts:646`). `queryLoop()` skips that preempt when compaction just ran, `querySource` is `'compact'` or `'session_memory'`, or `reactiveCompact` or `contextCollapse` owns real-API 413 recovery *while* `isAutoCompactEnabled()` (`services/compact/autoCompact.ts:147-158`) is true—honoring `DISABLE_AUTO_COMPACT`.

Immediately above (`query.ts:621-627`), `queryLoop()` hoists `const mediaRecoveryEnabled = reactiveCompact?.isReactiveCompactEnabled() ?? false` once per turn. Because `CACHED_MAY_BE_STALE` can flip during a 5–30s stream, unhoisted reads could withhold a media error mid-stream and then skip post-stream recovery, silently dropping the error.

During streaming (`query.ts:796-827`), four predicates suppress `yield yieldMessage` while retaining `message` in `assistantMessages`:

```ts
// query.ts:796-827
// feature() only works in if/ternary conditions (bun:bundle
// tree-shaking constraint), so the collapse check is nested
// rather than composed.
let withheld = false
if (feature('CONTEXT_COLLAPSE')) {
  if (
    contextCollapse?.isWithheldPromptTooLong(
      message,
      isPromptTooLongMessage,
      querySource,
    )
  ) {
    withheld = true
  }
}
if (reactiveCompact?.isWithheldPromptTooLong(message)) {
  withheld = true
}
if (
  mediaRecoveryEnabled &&
  reactiveCompact?.isWithheldMediaSizeError(message)
) {
  withheld = true
}
if (isWithheldMaxOutputTokens(message)) {
  withheld = true
}
if (!withheld) {
  yield yieldMessage
}
if (message.type === 'assistant') {
  assistantMessages.push(message)
```

Post-stream inside `if (!needsFollowUp)` (`query.ts:1062`), `queryLoop()` checks `lastMessage = assistantMessages.at(-1)` (`query.ts:1063`) against a strict **4-stage recovery ladder** (`query.ts:1070-1265`):

1. **`collapse_drain_retry` (`query.ts:1085-1118`):** Behind `feature('CONTEXT_COLLAPSE')` (`services/contextCollapse/index.js` absent), handles `isWithheld413` only (media skips collapse because collapse does not strip images, `query.ts:1075-1076`). Guarded one-shot by `state.transition?.reason !== 'collapse_drain_retry'` (`query.ts:1092`); retries when `drained.committed > 0`.
2. **`reactive_compact_retry` (`query.ts:1119-1183`):** Behind `feature('REACTIVE_COMPACT')` (`services/compact/reactiveCompact.js` absent), handles PTL and media errors using `hasAttemptedReactiveCompact` as a one-shot guard. On success, decrements `taskBudgetRemaining` (`query.ts:1138-1146`), yields `postCompactMessages`, sets `hasAttemptedReactiveCompact: true`, clears `autoCompactTracking`, and continues.
3. **`max_output_tokens_escalate` (`query.ts:1188-1221`):** Fires on `isWithheldMaxOutputTokens(lastMessage)` (`query.ts:175-179`) when GrowthBook `'tengu_otk_slot_v1'` (default `false`, `query.ts:1197`, `services/api/claude.ts:3396`) is on, `maxOutputTokensOverride === undefined`, and `CLAUDE_CODE_MAX_OUTPUT_TOKENS` is unset; `services/api/claude.ts:3394-3419` caps defaults to `CAPPED_DEFAULT_MAX_TOKENS = 8_000` (`utils/context.ts:24-25`, p99 4,911), retrying `messages: messagesForQuery` once cleanly at `ESCALATED_MAX_TOKENS = 64_000`.
4. **`max_output_tokens_recovery` (`query.ts:1223-1256`):** Runs up to `MAX_OUTPUT_TOKENS_RECOVERY_LIMIT = 3` (`query.ts:164`) continuations, appending `...assistantMessages` plus an unyielded `isMeta: true` resume nudge and clearing `maxOutputTokensOverride`. `services/api/claude.ts:2279-2292` reuses `apiError: 'max_output_tokens'` for `model_context_window_exceeded`, and [Chapter 03](03-command-and-message-contracts.md)'s `normalizeMessagesForAPI()` strips `isSyntheticApiErrorMessage` (`utils/messages.ts:2069`) next call.

> [!IMPORTANT]
> **Three Recovery Invariants:**
> 1. **Exactly-once surfacing:** Withheld errors are either absorbed silently or yielded **once** on failure (`query.ts:1173`, `query.ts:1180`, and `query.ts:1255`).
> 2. **No stop-hook death spirals:** Every unrecovered API error fires `void executeStopFailureHooks(lastMessage, toolUseContext)` and exits **before** `handleStopHooks()` (`query.ts:1168-1183` and `query.ts:1258-1265`), preventing an `error -> hook blocking -> retry -> error` loop.
> 3. **Asymmetric terminals:** Unrecovered PTL/media exit `{ reason: 'prompt_too_long' }` or `{ reason: 'image_error' }` (`query.ts:1175`, `query.ts:1182`), whereas exhausted `max_output_tokens` falls through to `if (lastMessage?.isApiErrorMessage)` and returns `{ reason: 'completed' }` (`query.ts:1262-1265`).

---

## 5. End-of-Turn Orchestration: `handleStopHooks` and `checkTokenBudget`

### The Problem

When `needsFollowUp` is `false` with no API error, three systems still run at turn end: background forks need a byte-identical cache snapshot, stop hooks may block or halt completion, and token budgets must nudge progress without looping when output stalls.

### The Mechanism: Four-Phase `handleStopHooks()` (`query/stopHooks.ts`)

Invoked at `query.ts:1267-1276`, [`query/stopHooks.ts`](../../query/stopHooks.ts) (`query/stopHooks.ts:65-473`) builds `stopHookContext` (`query/stopHooks.ts:84-91`) and runs four ordered phases:

1. **`CacheSafeParams` snapshot (`query/stopHooks.ts:92-98`):** For `repl_main_thread` or `sdk` (never subagents), saves `createCacheSafeParams(stopHookContext)` via `saveCacheSafeParams()` (`utils/forkedAgent.ts:57-81`). Kept outside `!isBareMode()` and `CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION` so `/btw` and SDK `side_question` inherit [Chapter 04](04-prompt-engineering-and-cache-boundaries.md)'s prompt prefix and [Chapter 06](06-executing-tools.md)'s `cloneContentReplacementState()` (`utils/forkedAgent.ts:399-403`).
2. **`TEMPLATES` job classifier (`query/stopHooks.ts:108-132`):** Under `feature('TEMPLATES') && process.env.CLAUDE_JOB_DIR && querySource.startsWith('repl_main_thread') && !agentId`, runs `classifyAndWriteState()` (`jobs/classifier.js`, absent) over all assistant messages in `stopHookContext.messages`, raced against a 60s `setTimeout(...).unref()` timer so `state.json` flushes without blocking exit.
3. **`!isBareMode()` background fan-out (`query/stopHooks.ts:133-157`):** When neither `CLAUDE_CODE_SIMPLE` nor `--bare` is set (`utils/envUtils.ts:60-65`), fires three background forks: `executePromptSuggestion()` (`!isEnvDefinedFalsy(process.env.CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION)`), `executeExtractMemories()` (`feature('EXTRACT_MEMORIES') && !agentId && isExtractModeActive()`, checking GrowthBook `'tengu_passport_quail'` and `'tengu_slate_thimble'` at `memdir/paths.ts:69-77`), and `executeAutoDream()` (`!agentId`).
   - **Session Memory runs elsewhere:** `extractSessionMemory` registers via `registerPostSamplingHook()` (`services/SessionMemory/sessionMemory.ts:374`) and runs per sampling step in `query.ts:1000-1009` (`executePostSamplingHooks()`), *not* inside `query/stopHooks.ts`.
   - **Computer Use cleanup (`query/stopHooks.ts:164-173`):** Outside `!isBareMode()`, `feature('CHICAGO_MCP') && !agentId` awaits `cleanupComputerUseAfterTurn()` (`utils/computerUse/cleanup.ts`), releasing the process-wide lock on main-thread exit only.
4. **Stop, SubagentStop, and Teammate hooks (`query/stopHooks.ts:175-472`):** Calls `executeStopHooks()` (`utils/hooks.ts:3639-3685`, switching to `'SubagentStop'` when `agentId` is set and passing `stop_hook_active: stopHookActive ?? false`). Blocking errors become yielded `isMeta: true` user messages; `preventContinuation` yields `hook_stopped_continuation` and beats `blockingErrors` (`query/stopHooks.ts:325-332`); mid-hook aborts return `preventContinuation: true` (`query/stopHooks.ts:283-294`).
   - **Teammate pass & fail-open catch:** If Stop hooks pass and `isTeammate()` is true, `TaskCompleted` (for owned `in_progress` tasks) and `TeammateIdle` run sequentially (`query/stopHooks.ts:335-453`), sharing one accumulator with the same precedence. Unexpected throws log `tengu_stop_hook_error`, yield a `'warning'` system message, and fail open (`query/stopHooks.ts:456-472`).

Back in `query.ts:1278-1306`, `preventContinuation` returns `{ reason: 'stop_hook_prevented' }`, while `blockingErrors` transitions via `{ reason: 'stop_hook_blocking' }` with `stopHookActive: true` (`query.ts:1300`). That flag is **preserved across `next_turn`** (`query.ts:1724`) so hooks see `stop_hook_active: true` on re-entry and can self-terminate, since no hardcoded retry cap exists.

> [!WARNING]
> **The `hasAttemptedReactiveCompact` Death-Spiral Scar (`query.ts:1292-1297`):** `stop_hook_blocking` intentionally **preserves** `hasAttemptedReactiveCompact` instead of resetting it to `false`. Resetting it previously caused an infinite loop (`compact -> still too long -> error -> stop hook blocking -> compact -> ...`) burning thousands of API calls.

### The Mechanism: `checkTokenBudget()` vs. API `taskBudget` (`query/tokenBudget.ts`)

After `handleStopHooks()` passes cleanly, `query.ts:1308-1355` runs `checkTokenBudget()` behind `feature('TOKEN_BUDGET')` (`budgetTracker` initialized at `query.ts:280`). Turn target and output deltas come from `bootstrap/state.ts:724-743` (`getCurrentTurnTokenBudget()`, `getTurnOutputTokens()`), populated from user shorthands like `+500k` (`utils/tokenBudget.ts:21-29`).

```ts
// query/tokenBudget.ts:45-76
export function checkTokenBudget(
  tracker: BudgetTracker,
  agentId: string | undefined,
  budget: number | null,
  globalTurnTokens: number,
): TokenBudgetDecision {
  if (agentId || budget === null || budget <= 0) {
    return { action: 'stop', completionEvent: null }
  }

  const turnTokens = globalTurnTokens
  const pct = Math.round((turnTokens / budget) * 100)
  const deltaSinceLastCheck = globalTurnTokens - tracker.lastGlobalTurnTokens

  const isDiminishing =
    tracker.continuationCount >= 3 &&
    deltaSinceLastCheck < DIMINISHING_THRESHOLD &&
    tracker.lastDeltaTokens < DIMINISHING_THRESHOLD

  if (!isDiminishing && turnTokens < budget * COMPLETION_THRESHOLD) {
    tracker.continuationCount++
    tracker.lastDeltaTokens = deltaSinceLastCheck
    tracker.lastGlobalTurnTokens = globalTurnTokens
    return {
      action: 'continue',
      nudgeMessage: getBudgetContinuationMessage(pct, turnTokens, budget),
      continuationCount: tracker.continuationCount,
      pct,
      turnTokens,
      budget,
    }
  }
```

Two constants govern continuation (`query/tokenBudget.ts:3-4`): `COMPLETION_THRESHOLD = 0.9` (90%) and `DIMINISHING_THRESHOLD = 500` output tokens; subagents always no-op. Once `continuationCount >= 3`, two consecutive deltas below `500` trip `isDiminishing`, logging `tengu_token_budget_completed` (`query.ts:1343-1354`) and returning `{ reason: 'completed' }` (`query.ts:1357`).

Otherwise `queryLoop()` calls `incrementBudgetContinuationCount()`, appends the `isMeta: true` nudge (`utils/tokenBudget.ts:66-73`), resets `hasAttemptedReactiveCompact: false` and `stopHookActive: undefined`, and continues with `{ reason: 'token_budget_continuation' }` (`query.ts:1316-1340`).

Keep this client-side `feature('TOKEN_BUDGET')` loop distinct from server-side `params.taskBudget` (`query.ts:193-197`, `query.ts:699-706`): `params.taskBudget` sends `output_config.task_budget` to the API while `query.ts` subtracts pre-compact tokens from loop-local `taskBudgetRemaining` (`query.ts:291`, `query.ts:508-515`, `query.ts:1138-1146`).

---

## 6. Forward Seams Inside `queryLoop()` (Compaction & Memory)

`queryLoop()` delegates Layer 3 compression and memory through two crisp seams without absorbing their internals:

- **Compaction seam ([Chapter 09](09-five-layer-compaction-pipeline.md)):** Slices via `getMessagesAfterCompactBoundary()` (`query.ts:365`), then runs `applyToolResultBudget()` (`query.ts:376-394`), `feature('HISTORY_SNIP')` `snipCompactIfNeeded()` (`query.ts:400-410`), `deps.microcompact()` + `feature('CACHED_MICROCOMPACT')` (`query.ts:413-426`, `query.ts:870-892`), `feature('CONTEXT_COLLAPSE')` `applyCollapsesIfNeeded()` (`query.ts:440-447`), `deps.autocompact()` (`query.ts:453-543`), and reactive 413 recovery (`query.ts:1089-1166`).
- **Memory seam ([Chapter 10](10-memory-systems-claudemd-auto-memory-and-dream.md)):** Connects via `using pendingMemoryPrefetch` (`query.ts:301-304`, gated on `isAutoMemoryEnabled()` and `'tengu_moth_copse'` at `utils/attachments.ts:2361-2424`, consumed zero-wait at `query.ts:1599-1614`), per-sampling `executePostSamplingHooks()` (`query.ts:1000-1009`) for Session Memory, and end-of-turn forks (`executeExtractMemories`, `executeAutoDream`) in `query/stopHooks.ts:141-156`.

---

## Putting the Layer Together

All 7 `Continue` transitions and all 10 `Terminal` exits (12 `return` sites) compose into one state machine inside `queryLoop()`:

```mermaid
flowchart TD
  Entry["query() wrapper: no-finally lifecycle sweep"] --> Init["queryLoop(): State, config, using memoryPrefetch"]
  Init --> PreAPI["Pre-API seams (Ch 09) + blocking_limit guard"]
  PreAPI -->|"blocking limit"| TermBlock["Terminal: blocking_limit"]
  PreAPI -->|"ok"| Stream["deps.callModel() + fallbacks + withholding"]
  Stream -->|"ImageSize/ResizeError"| TermImg["Terminal: image_error"]
  Stream -->|"uncaught throw"| TermModel["Terminal: model_error"]
  Stream -->|"aborted mid-stream"| TermAbortS["Terminal: aborted_streaming"]
  Stream -->|"needsFollowUp == false"| Recover["4-stage withheld error recovery ladder"]
  Recover -->|"collapse / reactive / escalate / resume"| PreAPI
  Recover -->|"unrecovered 413 / media"| TermPTL["Terminal: prompt_too_long / image_error"]
  Recover -->|"other API error / exhausted"| TermErrDone["Terminal: completed (StopFailure hooks)"]
  Recover -->|"clean reply"| StopHooks["handleStopHooks(): CacheSafeParams + hooks"]
  StopHooks -->|"preventContinuation"| TermStopPrev["Terminal: stop_hook_prevented"]
  StopHooks -->|"blockingErrors"| PreAPI
  StopHooks -->|"clean + TOKEN_BUDGET"| Budget["checkTokenBudget(): < 90% and active"]
  Budget -->|"continue nudge"| PreAPI
  Budget -->|"stop"| TermDone["Terminal: completed"]
  StopHooks -->|"clean (no budget)"| TermDone
  Stream -->|"needsFollowUp == true"| Tools["StreamingToolExecutor / runTools() + housekeeping"]
  Tools -->|"aborted mid-tools"| TermAbortT["Terminal: aborted_tools"]
  Tools -->|"hook_stopped_continuation"| TermHookStop["Terminal: hook_stopped"]
  Tools -->|"nextTurnCount > maxTurns"| TermMax["Terminal: max_turns"]
  Tools -->|"next_turn (turnCount + 1)"| PreAPI
```

And the exact ownership split across `query()`, loop-local resources, and 10-field `State`:

```text
query(params) [query.ts:219-239]
  | yield* queryLoop(params, consumedCommandUuids)
  | NO finally -> notifyCommandLifecycle(uuid, 'completed') on normal return
  v
queryLoop() [query.ts:241-1729]
  | Once: deps, config (QueryConfig), budgetTracker, taskBudgetRemaining
  | Once: using pendingMemoryPrefetch  <-- Symbol.dispose on ALL exits
  |
  +-> while (true) over 10-field State (whole-object state = next)
      1. Pre-API compaction seams (Ch 09) -> [blocking_limit]
      2. deps.callModel() + fallbacks -> [image_error | model_error]
         - withhold 413/media/max_output_tokens; retain in assistantMessages
         - needsFollowUp = any content.type === 'tool_use'
      3. executePostSamplingHooks() -> [aborted_streaming]
      4a. !needsFollowUp:
          413/media: collapse_drain_retry -> reactive_compact_retry
            -> unrecovered? StopFailure -> [prompt_too_long | image_error]
          max_output_tokens_escalate -> max_output_tokens_recovery
            -> exhausted / API error? StopFailure -> [completed]
          -> handleStopHooks() -> [stop_hook_prevented] | stop_hook_blocking
          -> checkTokenBudget() -> token_budget_continuation | [completed]
      4b. needsFollowUp:
          drain tools -> [aborted_tools | hook_stopped]
          -> attachments/queue/prefetches/refreshTools -> [max_turns]
          -> next_turn (SOLE turnCount + 1 transition)
```

---

## How This Snaps Into the Next Layer

`query()` owns exactly **one user turn**, from accepted input through all intermediate tool calls and recoveries until a `Terminal` exit. Conversation-lifetime state belongs to [`QueryEngine.ts`](../../QueryEngine.ts) in [Chapter 08](08-session-envelope-query-engine-and-transcripts.md):

- **Conversation envelope (`QueryEngine.ts:184-207`):** `class QueryEngine` persists `mutableMessages`, `readFileState`, `permissionDenials`, `totalUsage`, `hasHandledOrphanedPermission`, and `loadedNestedMemoryPaths` across consecutive `submitMessage()` calls (`QueryEngine.ts:209-1156`), while clearing turn-scoped `discoveredSkillNames` at the start of each `submitMessage()` (`QueryEngine.ts:192-197`, `QueryEngine.ts:238`).
- **Consuming `query()` (`QueryEngine.ts:675-1049`):** `submitMessage()` consumes `for await (const message of query({ ..., querySource: 'sdk', maxTurns, taskBudget }))`, writing transcripts via `recordTranscript()` (fire-and-forget for `assistant` messages so `message_delta` mutations land before lazy 100ms JSON serialization, `QueryEngine.ts:717-732`) and framing events into `SDKMessage`s.
- **Post-turn result scan & `ask()` (`QueryEngine.ts:1058-1060`, `QueryEngine.ts:1186-1295`):** Scans `messages.findLast(m => m.type === 'assistant' || m.type === 'user')` so trailing `handleStopHooks()` attachments never blank out `-p` results, and enforces `maxBudgetUsd` and structured-output retry caps outside `query()`. One-shot `ask()` wraps `QueryEngine` and syncs `readFileState` in `finally`.
- **The other five `query()` callers:** Interactive TUI (`screens/REPL.tsx:2793`, Chapter 21), subagents (`tools/AgentTool/runAgent.ts:748`) and cache-sharing forks (`utils/forkedAgent.ts:545`, Chapter 18), background main-session tasks (`tasks/LocalMainSessionTask.ts:383`, Chapter 17), and agent lifecycle hooks (`utils/hooks/execAgentHook.ts:167`, Chapter 13).

---

## Reading Exercises & Code Checkpoints

1. **Reconstruct snapshot-absent `query/transitions.ts` across all 19 state-machine edges:**
   ```sh
   rg -n "return \{ reason:|reason: '" query.ts
   ```
   Verify all 7 `Continue` variants and all 10 `Terminal` variants across 12 `return` sites—noting why `return \{ reason:` is needed to catch `query.ts:1175`'s ternary `isWithheldMedia ? 'image_error' : 'prompt_too_long'`.
2. **Compare snapshotted `QueryConfig` runtime gates and `QueryDeps` against inline `feature()` DCE boundaries:**
   ```sh
   rg -n "feature\('|QueryConfig|buildQueryConfig|QueryDeps|productionDeps" query.ts query/config.ts query/deps.ts
   ```
   Inspect `query/config.ts:13-14` and `query/deps.ts:8-20` to see why `feature('...')` stays inline in `query.ts` while `'tengu_streaming_tool_execution2'` and env gates snapshot into `QueryConfig`, and verify that `query.ts:69` (`jobClassifier`) has zero references in `query.ts`.
3. **Trace `needsFollowUp`, withheld error suppression, and `tengu_otk_slot_v1` 8k-to-64k escalation:**
   ```sh
   rg -n "needsFollowUp|let withheld|isWithheldMaxOutputTokens|tengu_otk_slot_v1|MAX_OUTPUT_TOKENS_RECOVERY_LIMIT" query.ts
   ```
   Follow `withheld` from `query.ts:799-825` to `query.ts:1188-1256` and confirm why `CLAUDE_CODE_MAX_OUTPUT_TOKENS` (`query.ts:1202`) bypasses `max_output_tokens_escalate` even when `'tengu_otk_slot_v1'` is enabled.
4. **Audit turn-end orchestration: `CacheSafeParams`, `!isBareMode()`, `stopHookActive`, and `checkTokenBudget()`:**
   ```sh
   rg -n "saveCacheSafeParams|isBareMode|stopHookActive|COMPLETION_THRESHOLD|DIMINISHING_THRESHOLD|checkTokenBudget" query.ts query/stopHooks.ts query/tokenBudget.ts
   ```
   Compare `stopHookActive` across all 7 `Continue` sites in `query.ts` (identifying the 2 sites that set or preserve it vs. the 5 sites that reset it to `undefined`), and trace `checkTokenBudget()` at `continuationCount === 3` (after three continuations) when `lastDeltaTokens` is `400` and `deltaSinceLastCheck` is `450` output tokens.


---

<!-- chapters/08-session-envelope-query-engine-and-transcripts.md — https://reverseengineeringclaudecode.com/chapters/08-session-envelope-query-engine-and-transcripts -->

# Chapter 08 — The Session Envelope: `QueryEngine.ts` and Transcript Persistence

> **Layer:** Layer 2 (The Agent Engine)
> **Prerequisites:** [Chapter 01](01-atoms-types-stores-and-primitives.md) (`bootstrap/state.ts`, `FileStateCache`), [Chapter 02](02-the-tool-contract.md) (`ToolUseContext`), [Chapter 03](03-command-and-message-contracts.md) (`processUserInput`, `normalizeMessages`), [Chapter 04](04-prompt-engineering-and-cache-boundaries.md) (`asSystemPrompt`), [Chapter 05](05-talking-to-the-model.md) (`cost-tracker.ts`), [Chapter 06](06-executing-tools.md) (`runTools`, `ContentReplacementState`), [Chapter 07](07-the-heartbeat-query-loop.md) (`query()`)
> **Primary Source Files:**
> - [`QueryEngine.ts`](../../QueryEngine.ts) — conversation-lifetime envelope wrapping `query()`, SDK framing, persistence timing, and guardrails (1,295 lines)
> - [`utils/queryHelpers.ts`](../../utils/queryHelpers.ts) — SDK normalization, `isResultSuccessful`, orphaned-permission replay, and resume cache extraction (552 lines)
> - [`utils/sessionStorage.ts`](../../utils/sessionStorage.ts) — lazy-materialized `Project` JSONL writer, `parentUuid` DAG, read-side repair, and scale guards (5,105 lines)
> - [`utils/sessionRestore.ts`](../../utils/sessionRestore.ts) — resume hydration, worktree restoration, and `--fork-session` orchestration (551 lines)
> - [`utils/conversationRecovery.ts`](../../utils/conversationRecovery.ts) — resume loader, turn-interruption repair, and skill-state replay (597 lines)
> - [`utils/fileHistory.ts`](../../utils/fileHistory.ts) — three-phase path-hashed file checkpointing and `/rewind` disk rollback (1,115 lines)

---

## Why This Layer Exists

[Chapter 07](07-the-heartbeat-query-loop.md)'s `query()` runs one prompt to a `Terminal` exit. Four production problems remain above it:

1. **Cross-turn state & SDK framing:** Retaining `mutableMessages`, `readFileState`, `permissionDenials`, `totalUsage`, guardrails, and `SDKMessage` framing.
2. **Append-only durability:** Persisting JSONL without empty-file leaks, kill-before-flush loss, or 150 MB OOMs.
3. **Crash recovery & forking:** Repairing truncated lines and interrupted turns while isolating `--fork-session` from parent worktrees/caches.
4. **Coherent `/rewind`:** Rolling back conversation history and disk edits together.

These six files (plus [`utils/json.ts`](../../utils/json.ts) and [`utils/sessionStoragePortable.ts`](../../utils/sessionStoragePortable.ts)) close Layer 2.

---

## 1. The Session Envelope: `QueryEngine` vs. `query()` (`QueryEngine.ts`)

### The Problem

`query()` holds only a turn-local `State.messages` slice and knows nothing about SDK wire types, JSONL flushing, budget caps, or post-compaction GC. Worse, Desktop and Cowork kill the CLI subprocess milliseconds after reading `result`—or seconds after a user hits Stop before the API replies.

### The Real Implementation (`QueryEngine.ts`)

`QueryEngine` (`QueryEngine.ts:184-1177`) owns nine instance fields (`QueryEngine.ts:184-207`):

```ts
// QueryEngine.ts:184-207
export class QueryEngine {
  private config: QueryEngineConfig
  private mutableMessages: Message[]
  private abortController: AbortController
  private permissionDenials: SDKPermissionDenial[]
  private totalUsage: NonNullableUsage
  private hasHandledOrphanedPermission = false
  private readFileState: FileStateCache
  // Turn-scoped skill discovery tracking (feeds was_discovered on
  // tengu_skill_tool_invocation). Must persist across the two
  // processUserInputContext rebuilds inside submitMessage, but is cleared
  // at the start of each submitMessage to avoid unbounded growth across
  // many turns in SDK mode.
  private discoveredSkillNames = new Set<string>()
  private loadedNestedMemoryPaths = new Set<string>()

  constructor(config: QueryEngineConfig) {
    this.config = config
    this.mutableMessages = config.initialMessages ?? []
    this.abortController = config.abortController ?? createAbortController()
    this.permissionDenials = []
    this.readFileState = config.readFileCache
    this.totalUsage = EMPTY_USAGE
  }
```

Two lifetime carve-outs stand out immediately:
- **`discoveredSkillNames` is turn-scoped (`QueryEngine.ts:197`, `QueryEngine.ts:238`):** Cleared at each `submitMessage()` start to cap SDK memory (unlike `screens/REPL.tsx:1958-1963`). `loadedNestedMemoryPaths` (`QueryEngine.ts:198`) stays session-wide because `readFileState` is a bounded LRU that evicts nested `CLAUDE.md` paths.
- **`abortController` never resets (`QueryEngine.ts:187`, `QueryEngine.ts:203`, `QueryEngine.ts:1158-1160`):** Once `interrupt()` aborts an engine instance, it stays aborted across turns.

`submitMessage()` (`QueryEngine.ts:209-1156`) drives each turn in nine phases:

1. **Turn setup & denial capture (`QueryEngine.ts:213-271`):** Clears `discoveredSkillNames`, sets `cwd`, snapshots `persistSession = !isSessionPersistenceDisabled()` (`QueryEngine.ts:240`), and wraps `canUseTool` to record denials under `sdkCompatToolName(tool.name)` (`Agent` → `Task` for `#19647`, `utils/messages/systemInit.ts:19-25`).
2. **Prompt, coordinator & schema hooks (`QueryEngine.ts:273-333`):** Resolves model and thinking, calls `fetchSystemPromptParts()` (`utils/queryContext.ts:44-74`), and merges coordinator context under `feature('COORDINATOR_MODE')` (`QueryEngine.ts:112-117`, `QueryEngine.ts:302-308`, passing `getScratchpadDir()` behind GrowthBook `'tengu_scratch'` via `isScratchpadEnabled()`).

   When `customPrompt !== undefined && hasAutoMemPathOverride()` (`CLAUDE_COWORK_MEMORY_PATH_OVERRIDE` at `memdir/paths.ts:161-166`), it appends Cowork's memory prompt (`QueryEngine.ts:316-319`), brands `asSystemPrompt([...])`, and registers `Stop` schema enforcement when `jsonSchema` and `StructuredOutput` are present (`QueryEngine.ts:328-333`).
3. **Context #1 & orphaned permission (`QueryEngine.ts:335-408`):** Builds `processUserInputContext` with live `setMessages` (`QueryEngine.ts:344-346`) and same-ref `updateFileHistoryState` (`QueryEngine.ts:376-384`), then runs `handleOrphanedPermission()` once via `hasHandledOrphanedPermission`.
4. **User input & pre-query durability (`QueryEngine.ts:410-463`):** Calls `processUserInput({ ..., querySource: 'sdk' })`, pushes returned messages into `this.mutableMessages`, snapshots local `messages`, and persists *before* calling `query()`:

   ```ts
   // QueryEngine.ts:450-463
   if (persistSession && messagesFromUserInput.length > 0) {
     const transcriptPromise = recordTranscript(messages)
     if (isBareMode()) {
       void transcriptPromise
     } else {
       await transcriptPromise
       if (
         isEnvTruthy(process.env.CLAUDE_CODE_EAGER_FLUSH) ||
         isEnvTruthy(process.env.CLAUDE_CODE_IS_COWORK)
       ) {
         await flushSessionStorage()
       }
     }
   }
   ```

   Pre-query persistence plus eager flushing keeps Cowork `--resume` from failing with `"No conversation found"` on early Stop. Under `--bare` / `CLAUDE_CODE_SIMPLE` (`isBareMode()`, `utils/envUtils.ts:60-65`), scripted calls fire-and-forget, saving ~4–30 ms.
5. **Context #2 & `system/init` (`QueryEngine.ts:465-554`):** Selects `messagesToAck` via lazy `messageSelector().selectableUserMessagesFilter` (`QueryEngine.ts:87-89`, `QueryEngine.ts:471`), rebuilds `processUserInputContext` with no-op `setMessages`, loads cache-only skills/plugins, and yields `system/init` (`buildSystemInitMessage()`, `utils/messages/systemInit.ts:53-96`; `SDKSystemMessageSchema`, `entrypoints/sdk/coreSchemas.ts:1457-1494`).
6. **`!shouldQuery` fast path (`QueryEngine.ts:556-639`):** Local slash commands skip `query()`. `system/local_command` output becomes a synthetic `SDKAssistantMessage` (`utils/messages/mappers.ts:196-215`) because Android and `api-go` only parse `init` and `compact_boundary` system subtypes.
7. **Pre-loop snapshots & watermark (`QueryEngine.ts:641-673`):** Fires `void fileHistoryMakeSnapshot(...)` when `fileHistoryEnabled() && persistSession`, and captures reference-based `errorLogWatermark = getInMemoryErrors().at(-1)` (`QueryEngine.ts:669`).
8. **`query()` consumer loop (`QueryEngine.ts:675-1049`):** Iterates `for await (const message of query({...}))` and **discards `query()`'s `Terminal` return value**. Before recording `compact_boundary`, it flushes `this.mutableMessages.slice(0, tailIdx + 1)` up to `preservedSegment.tailUuid` (`QueryEngine.ts:701-715`). Core writes then split sync vs. async:

   ```ts
   // QueryEngine.ts:717-732
   if (persistSession) {
     // Fire-and-forget for assistant messages. claude.ts yields one
     // assistant message per content block, then mutates the last
     // one's message.usage/stop_reason on message_delta — relying on
     // the write queue's 100ms lazy jsonStringify. Awaiting here
     // blocks ask()'s generator, so message_delta can't run until
     // every block is consumed; the drain timer (started at block 1)
     // elapses first. Interactive CC doesn't hit this because
     // useLogMessages.ts fire-and-forgets. enqueueWrite is
     // order-preserving so fire-and-forget here is safe.
     if (message.type === 'assistant') {
       void recordTranscript(messages)
     } else {
       await recordTranscript(messages)
     }
   }
   ```

   In `switch (message.type)` (`QueryEngine.ts:757-969`), `tombstone` is skipped (`QueryEngine.ts:758-760`), `stream_event` accumulates `totalUsage` on `message_stop` (`QueryEngine.ts:810-816`), and `progress`/`attachment` call inline `void recordTranscript` (`QueryEngine.ts:773-781`, `QueryEngine.ts:831-835`) so unrecorded rows never stall prefix dedup.

   On `snipReplay` (`QueryEngine.ts:905-915`) and `compact_boundary` (`QueryEngine.ts:918-942`), `QueryEngine` splices pre-compaction messages out of `this.mutableMessages` in place for GC.
9. **Guardrails & `result` framing (`QueryEngine.ts:842-874`, `QueryEngine.ts:972-1156`):** Enforces `maxTurns` (`error_max_turns`), `maxBudgetUsd` (`getTotalCost()` → `error_max_budget_usd`), and `process.env.MAX_STRUCTURED_OUTPUT_RETRIES || '5'` (`error_max_structured_output_retries`).

   All six exit/pre-query sites eager-flush under `CLAUDE_CODE_EAGER_FLUSH || CLAUDE_CODE_IS_COWORK` (`QueryEngine.ts:457-461`, `QueryEngine.ts:611-615`, `QueryEngine.ts:845-849`, `QueryEngine.ts:975-979`, `QueryEngine.ts:1018-1022`, `QueryEngine.ts:1075-1079`). On failure, `error_during_execution` slices `getInMemoryErrors()` from `all.lastIndexOf(errorLogWatermark) + 1` (`QueryEngine.ts:1106-1115`), staying turn-scoped even when `.shift()` rotates the 100-entry ring buffer (`utils/log.ts:66-77`).

### Hidden Invariants & Architectural Reality Today

- **`ask()` and `HISTORY_SNIP` (`QueryEngine.ts:1186-1295`):** `export async function* ask(...)` creates a fresh `QueryEngine` per call, shares `mutableMessages`, clones `readFileCache` and writes it back in `finally` (`QueryEngine.ts:1292-1294`), and injects `snipReplay` behind `feature('HISTORY_SNIP')` (`QueryEngine.ts:122-127`, `QueryEngine.ts:1276-1284`) using snapshot-absent `services/compact/snipCompact.js` and `services/compact/snipProjection.js`.
- **Unfinished caller migration:** Despite `QueryEngine.ts:176-182`'s docstring, **`cli/print.ts` is the sole production caller** (`cli/print.ts:91`, `cli/print.ts:2147`), hoisting `mutableMessages`, `readFileState` + `pendingSeeds` (`cli/print.ts:1145-1167`, `cli/print.ts:2168-2181`), and a fresh `abortController` per turn (`cli/print.ts:2133`) around `ask()`. Interactive `screens/REPL.tsx` keeps its own refs (`screens/REPL.tsx:1958-1977`) and calls `query()` directly (`screens/REPL.tsx:146`, `screens/REPL.tsx:2793-2803`).

---

## 2. SDK Framing, Orphaned Permissions & Resume Cache Extraction (`utils/queryHelpers.ts`)

### The Problem

Translating internal messages for SDK clients and recovering restarted headless processes introduces four edge cases: subagent attribution, silent `end_turn` completions, out-of-band permission responses after reconnects, and an empty `FileStateCache` on restart.

### The Real Implementation (`utils/queryHelpers.ts`)

1. **`normalizeMessage()` (`utils/queryHelpers.ts:102-222`):** Converts internal `assistant`, `progress`, and `user` messages into `SDKMessage`s via `normalizeMessages()` and `isNotEmptyMessage()`. It unwraps `agent_progress`/`skill_progress` with `parent_tool_use_id: message.parentToolUseID` (`utils/queryHelpers.ts:121-156`) and merges `mcpMeta` into `tool_use_result`.

   For `bash_progress`/`powershell_progress` (`utils/queryHelpers.ts:157-201`), it emits `tool_progress` **only** when `CLAUDE_CODE_REMOTE` or `CLAUDE_CODE_CONTAINER_ID` is set, throttled by `TOOL_PROGRESS_THROTTLE_MS = 30000` (30 s) in a 100-entry `toolProgressLastSentTime` `Map` (`utils/queryHelpers.ts:98-100`). *(Stale comments: `utils/queryHelpers.ts:161` says `"one per minute"` and `utils/queryHelpers.ts:178` says `"LRU eviction"`, but `Map.set()` on an existing key preserves insertion order—making eviction FIFO at 30 s.)*

2. **`isResultSuccessful()` (`utils/queryHelpers.ts:56-94`):** Paired with `QueryEngine.ts:1051-1060`'s `#23537` fix (`messages.findLast(m => m.type === 'assistant' || m.type === 'user')` so trailing stop-hook progress cannot blank `-p`), this check accepts assistant `text`/`thinking`/`redacted_thinking` blocks, all-`tool_result` user messages, or the **zero-block `end_turn` carve-out** (`stopReason === 'end_turn'`, `utils/queryHelpers.ts:83-93`).

   On `task_notification` drain turns or post-`StructuredOutput` turns (`services/api/claude.ts:2346-2350`; comment at `utils/queryHelpers.ts:85` cites stale line 2026 of `services/api/claude.ts`), zero assistant blocks are legitimate; without this carve-out, `QueryEngine` emits `error_during_execution`.

3. **`handleOrphanedPermission()` (`utils/queryHelpers.ts:224-343`) & `PermissionPromptTool` (`utils/queryHelpers.ts:39-42`):** When a remote client sends a late permission response (`cli/print.ts:5241-5304`), `handleOrphanedPermission()` applies `updatedInput` on `'allow'` with a warn fallback (`utils/queryHelpers.ts:262-276`), guards `mutableMessages` before yielding, and replays `[finalToolUseBlock]` via `runTools()` (`utils/queryHelpers.ts:322-342`):

   ```ts
   // utils/queryHelpers.ts:299-319
   const alreadyPresent = mutableMessages.some(
     m =>
       m.type === 'assistant' &&
       Array.isArray(m.message.content) &&
       m.message.content.some(
         b => b.type === 'tool_use' && 'id' in b && b.id === toolUseID,
       ),
   )
   if (!alreadyPresent) {
     mutableMessages.push(assistantMessage)
     if (persistSession) {
       await recordTranscript(mutableMessages)
     }
   }

   const sdkAssistantMessage: SDKMessage = {
     ...assistantMessage,
     session_id: getSessionId(),
     parent_tool_use_id: null,
   } as SDKMessage
   yield sdkAssistantMessage
   ```

   Deduplicating by `tool_use.id`—not `assistantMessage.message.id`—avoids both traps: streaming splits `[text, tool_use]` under one `message.id` and recovery can drop `tool_use`. Checking `message.id` orphans `tool_result`; blind pushes hit HTTP 400 `"tool_use ids must be unique"` after `normalizeMessagesForAPI` merges assistants.

   Companion `PermissionPromptTool` (`utils/queryHelpers.ts:39-42`) wraps `utils/permissions/PermissionPromptToolResultSchema.ts:15-79` (`.catch(...)` → `undefined` for `#29440` at `utils/permissions/PermissionPromptToolResultSchema.ts:48-59`, vs. `decisionClassificationField`'s `.catch(undefined)` at `utils/permissions/PermissionPromptToolResultSchema.ts:37-42`; mobile `{}` `updatedInput` keeps original input at `utils/permissions/PermissionPromptToolResultSchema.ts:107-111`).

4. **Resume cache extractors (`utils/queryHelpers.ts:346-552`):**
   - `extractReadFilesFromMessages()` (`utils/queryHelpers.ts:346-501`, default `ASK_READ_FILE_STATE_CACHE_SIZE = 10`, overridden at `cli/print.ts:1154`, `screens/REPL.tsx:1972`) runs two passes for last-wins `FileStateCache` hydration.

     Pass 1 indexes non-ranged `Read`/`Write`/`Edit` calls; Pass 2 replays `tool_result`s, skips `FILE_UNCHANGED_STUB` (`utils/queryHelpers.ts:428`), strips `<system-reminder>` tags/line prefixes, and re-reads `Edit` targets from live disk via `readFileSyncWithMetadata` (`utils/queryHelpers.ts:477-494`).
   - `extractBashToolsFromMessages()` (`utils/queryHelpers.ts:507-552`) strips `VAR=val` and `'sudo'` (`STRIPPED_COMMANDS`/`extractCliName`) to rebuild used CLI binaries.

---

## 3. JSONL Transcript Persistence, the `parentUuid` DAG & Scale Guards (`utils/sessionStorage.ts`, `utils/sessionStoragePortable.ts`)

### The Problem

Transcripts must survive sudden kills without leaking empty `.jsonl` files on `--version` or `/exit`, avoid syscall thrashing during streaming, represent rewinds and compactions in an append-only log, and stay fast when sessions exceed 150 MB (`inc-3930`).

### The Write Path: Lazy `Project`, Batched Queues & Sidechain Isolation

Singleton `class Project` (`utils/sessionStorage.ts:532-1384`, returned by `getProject()` at `utils/sessionStorage.ts:443-467`) enforces five invariants:

- **Lazy materialization (`utils/sessionStorage.ts:549-552`, `utils/sessionStorage.ts:960-991`):** `sessionFile` starts `null`, buffering early rows in `pendingEntries`. The first `user`/`assistant` message runs `materializeSessionFile()`, checking `shouldSkipPersistence()` (`NODE_ENV === 'test' && !TEST_ENABLE_SESSION_PERSISTENCE`, `cleanupPeriodDays === 0`, `isSessionPersistenceDisabled()`, `CLAUDE_CODE_SKIP_PROMPT_HISTORY`), resolving `getOriginalCwd()` lazily (`utils/sessionStorage.ts:108-112`), and draining `pendingEntries`.
- **Dual async/sync queues (`utils/sessionStorage.ts:530`, `utils/sessionStorage.ts:567-568`, `utils/sessionStorage.ts:606-686`, `utils/sessionStorage.ts:2572-2729`):** Transcript rows batch via `FLUSH_INTERVAL_MS` (`100` ms; `REMOTE_FLUSH_INTERVAL_MS = 10` ms remotely) in `MAX_CHUNK_BYTES` (`100` MB) chunks (`0o600` files, `0o700` dirs). Metadata (`saveCustomTitle`, `saveTag`) writes synchronously via `appendEntryToFile()`.

  On exit, `registerCleanup` (`utils/sessionStorage.ts:449-462`) flushes and calls `reAppendSessionMetadata()` (`utils/sessionStorage.ts:721-839`), tail-reading 64 KiB (`readFileTailSync`) with col-0 `startsWith` so external SDK renames win inside the tail window.
- **In-place 64 KiB tombstoning & 50 MB caps (`inc-3930`):** `removeMessageByUuid()` (`utils/sessionStorage.ts:871-951`) searches the last 64 KiB for `"uuid":"<id>"` (avoiding `parentUuid` hits) and splices via `fh.truncate()`. Its slow-path full rewrite caps at `MAX_TOMBSTONE_REWRITE_BYTES` (`50` MB, `utils/sessionStorage.ts:123`), matching `MAX_TRANSCRIPT_READ_BYTES` (`utils/sessionStorage.ts:229`).
- **Main-file-authoritative `messageSet` (`inc-4718`, `utils/sessionStorage.ts:1224-1262`):** Agent sidechains write to `<sessionId>/subagents/agent-<agentId>.jsonl` and share inherited parent UUIDs. Deduping against main `messageSet` dropped fork context, while adding sidechain UUIDs or posting to Session Ingress (`ENABLE_SESSION_PERSISTENCE`, `utils/sessionStorage.ts:1327`) caused dangling links and 409 shutdowns—so `appendEntry()` bypasses dedup, `messageSet.add`, and `persistToRemote` for sidechains.
- **DAG links & post-spread session re-stamp (`utils/sessionStorage.ts:1031-1068`):** `tool_result`s override `parentUuid` with `sourceToolAssistantUUID`; `compact_boundary` sets `parentUuid: null` and preserves `logicalParentUuid`; only `isChainParticipant` (`m.type !== 'progress'`, `utils/sessionStorage.ts:154-156`) advances `parentUuid`. Session-stamp fields intentionally follow `...message`:

  ```ts
  // utils/sessionStorage.ts:1039-1064
          const transcriptMessage: TranscriptMessage = {
            parentUuid: isCompactBoundary ? null : effectiveParentUuid,
            logicalParentUuid: isCompactBoundary ? parentUuid : undefined,
            isSidechain,
            teamName: teamInfo?.teamName,
            agentName: teamInfo?.agentName,
            promptId:
              message.type === 'user' ? (getPromptId() ?? undefined) : undefined,
            agentId,
            ...message,
            // Session-stamp fields MUST come after the spread. On --fork-session
            // and --resume, messages arrive as SerializedMessage (carries source
            // sessionId/cwd/etc. because removeExtraFields only strips parentUuid
            // and isSidechain). If sessionId isn't re-stamped, FRESH.jsonl ends up
            // with messages stamped sessionId=A but content-replacement entries
            // stamped sessionId=FRESH (from insertContentReplacement), and
            // loadFullLog's sessionId-keyed contentReplacements lookup misses →
            // replacement records lost → FROZEN misclassification.
            userType: getUserType(),
            entrypoint: getEntrypoint(),
            cwd: getCwd(),
            sessionId,
            version: VERSION,
            gitBranch,
            slug,
          }
  ```

`recordTranscript()` (`utils/sessionStorage.ts:1408-1449`) runs `cleanMessagesForLogging()` (`utils/sessionStorage.ts:4450-4461`): `isLoggableMessage()` (`utils/sessionStorage.ts:4351-4367`) drops all `progress` unconditionally (`utils/sessionStorage.ts:4352`), and under `getUserType() !== 'ant'` (`process.env.USER_TYPE`, `utils/sessionStorage.ts:419-421`) drops `attachment`s except `hook_additional_context` when `CLAUDE_CODE_SAVE_HOOK_ADDITIONAL_CONTEXT` is truthy (`utils/sessionStorage.ts:4357-4365`).

That same `getUserType() !== 'ant'` gate calls `transformMessagesForExternalTranscript()` (`utils/sessionStorage.ts:4396-4448`, `utils/sessionStorage.ts:4455-4460`), stripping `REPL_TOOL_NAME` pairs and promoting `isVirtual`; tracking `startingParentUuid` **only over an unbroken prefix** (`!seenNewMessage`) prevents post-compact chain rewiring.

Separately, `EPHEMERAL_PROGRESS_TYPES` / `isEphemeralToolProgress()` (`utils/sessionStorage.ts:186-196`, gating `'sleep_progress'` on `feature('PROACTIVE') || feature('KAIROS')` at `utils/sessionStorage.ts:190-192`) drives UI replace-in-place in `screens/REPL.tsx:2608`, not `cleanMessagesForLogging()`.

### Read-Side Repair Pipeline & Three Scale Guards

On load, `loadTranscriptFile()` (`utils/sessionStorage.ts:3472-3813`) and `buildConversationChain()` (`utils/sessionStorage.ts:2069-2094`) run five deterministic repairs, followed by `checkResumeConsistency()` on resume (`utils/conversationRecovery.ts:553`):

| Stage | Exact Symbol & Citation | What It Repairs |
|---|---|---|
| 1 | `isLegacyProgressEntry()` (`utils/sessionStorage.ts:169-178`), `progressBridge` (`utils/sessionStorage.ts:3616-3645`) | Bridges pre-`#24099` legacy `progress` entries (`#14373`, `#23537`) to the nearest non-progress ancestor. |
| 2 | `applyPreservedSegmentRelinks` (`utils/sessionStorage.ts:1839-1956`) | Rewires compaction-preserved `head→anchor`, zeroes stale pre-compact `usage`, validates `tail→head` (`tengu_relink_walk_broken`), prunes pre-boundary noise. |
| 3 | `applySnipRemovals` (`utils/sessionStorage.ts:1982-2039`) | Structurally inspects `snipMetadata?.removedUuids` (no ant-only string leak), deletes snipped entries, path-compressed relinks surviving children. |
| 4 | Leaf pruning (`utils/sessionStorage.ts:3716-3790`) | Walks terminal nodes to nearest `user`/`assistant` with cycle guard; under GrowthBook `'tengu_pebble_leaf_prune'` (default `false`, `utils/sessionStorage.ts:3731`), prunes ancestors already having a `user`/`assistant` child. |
| 5 | `recoverOrphanedParallelToolResults` (`utils/sessionStorage.ts:2118-2206`) | Re-attaches sibling 1-block `AssistantMessage`s (same `message.id`) and their `tool_result`s orphaned by single-parent walks (`tengu_chain_parallel_tr_recovered`). |
| 6 | `checkResumeConsistency` (`utils/sessionStorage.ts:2224-2243`) | Checks latest `turn_duration` checkpoint's `messageCount` against reconstructed index (`tengu_resume_consistency_delta`, catching `#22453` truncation). |

Three scale guards paired with [`utils/sessionStoragePortable.ts`](../../utils/sessionStoragePortable.ts) (793 lines) bound latency and RSS:

1. **`> 5 MiB` fd-level pre-compact streaming (`utils/sessionStorage.ts:3536-3556`, `utils/sessionStoragePortable.ts:480`, `utils/sessionStoragePortable.ts:717-793`):** Above `SKIP_PRECOMPACT_THRESHOLD` (`5 * 1024 * 1024`), `readTranscriptForLoad()` streams 1 MB chunks, dropping stale `attribution-snapshot` lines and resetting at non-preserved `compact_boundary` lines (cutting a 151 MB log from ~316 MB to ~155 MB RSS, `utils/sessionStorage.ts:3525-3529`).

   `scanPreBoundaryMetadata()` (`utils/sessionStorage.ts:3157-3224`) recovers pre-boundary metadata via raw `Buffer.includes`.
2. **Byte-level dead-fork pre-filter (`walkChainBeforeParse()`, `utils/sessionStorage.ts:3306-3466`):** Above `5 MiB` (when `!opts?.keepAllLeaves && !hasPreservedSegment`), it indexes `{"parentUuid":` lines and `"uuid":"<36>","timestamp":"` (disambiguating nested hits via brace-depth-1 `pickDepthOneUuidCandidate()` at `utils/sessionStorage.ts:3275-3304`) to walk the live chain in `latin1` before `JSON.parse`:

   ```ts
   // utils/sessionStorage.ts:3419-3444
     const seen = new Set<number>()
     const chain = new Set<number>()
     let chainBytes = 0
     let slot: number | undefined = leafSlot
     while (slot !== undefined) {
       if (seen.has(slot)) break
       seen.add(slot)
       chain.add(msgIdx[slot]!)
       chainBytes += msgIdx[slot + 1]! - msgIdx[slot]!
       const parentStart = msgIdx[slot + 2]!
       if (parentStart < 0) break
       const parent = buf.toString('latin1', parentStart, parentStart + UUID_LEN)
       slot = uuidToSlot.get(parent)
     }

     // parseJSONL cost scales with bytes, not entry count. A session can have
     // thousands of dead entries by count but only single-digit-% of bytes if
     // the dead branches are short turns and the live chain holds the fat
     // assistant responses (measured: 107 MB session, 69% dead entries, 30%
     // dead bytes - index+concat overhead exceeded parse savings). Gate on
     // bytes: only stitch if we would drop at least half the buffer. Metadata
     // is tiny so len - chainBytes approximates dead bytes closely enough.
     // Near break-even the concat memcpy (copying chainBytes into a fresh
     // allocation) dominates, so a conservative 50% gate stays safely on the
     // winning side.
     if (len - chainBytes < len >> 1) return buf
   ```

   Setting `CLAUDE_CODE_DISABLE_PRECOMPACT_SKIP` (`utils/sessionStorage.ts:3536`, `utils/sessionStorage.ts:3575`) disables both the `> 5 MiB` pre-compact skip and `walkChainBeforeParse()`.
3. **Two-phase progressive listing (`utils/sessionStorage.ts:4739-5105`):** `getSessionFilesLite()` (`utils/sessionStorage.ts:4975-5016`) is **strictly `stat`-only** (zero file reads), returning `mtime`-sorted stubs immediately.

   Phase 2 (`enrichLogs()`, `utils/sessionStorage.ts:5077-5105`) accepts caller `count`—defaulting to `INITIAL_ENRICH_COUNT = 50` (`utils/sessionStorage.ts:4577`; callers `utils/sessionStorage.ts:3973`, `utils/sessionStorage.ts:4020`, `utils/sessionStorage.ts:4076`, `utils/sessionStorage.ts:4089`).

   It reuses one `LITE_READ_BUF_SIZE = 65536` (64 KiB, `utils/sessionStoragePortable.ts:17`) buffer via `readLiteMetadata()` (`utils/sessionStorage.ts:4739-4813`) → `readHeadAndTail()` (`utils/sessionStoragePortable.ts:215-242`) for 64 KiB head/tail reads. *(Stale `utils/sessionStorage.ts:2810` and `utils/sessionStorage.ts:5049` comments say `"16KB"`.)*

---

## 4. Crash Recovery, Resume & Session Forking (`utils/json.ts`, `utils/conversationRecovery.ts`, `utils/sessionRestore.ts`)

### The Problem

Hard kills damage two layers: truncated trailing JSONL lines, and turns ending in dangling `tool_use`, orphaned thinking, or unanswered prompts. Resume and `--fork-session` must repair both without corrupting parent state.

### Two-Level Crash Resilience (`utils/json.ts`, `utils/conversationRecovery.ts`)

1. **Syntactic partial-write recovery ([`utils/json.ts`](../../utils/json.ts), 277 lines):** `parseJSONL()` (`utils/json.ts:182-190`) runs native `Bun.JSONL.parseChunk` (`parseJSONLBun()`, `utils/json.ts:102-127`). On a mid-stream error (`result.error`), it keeps already-parsed `result.values`, skips past the next `\n` (`0x0a`), and resumes `parse(data, offset)`.

   Fallbacks `parseJSONLBuffer()` (`utils/json.ts:129-153`) and `parseJSONLString()` (`utils/json.ts:155-175`) strip UTF-8 BOMs and skip bad lines via per-line `try/catch`, while `readJSONLFile()` (`utils/json.ts:192-226`) bounds raw tail reads at `MAX_JSONL_READ_BYTES` (100 MB).
2. **Semantic interruption repair (`utils/conversationRecovery.ts:164-373`):** `deserializeMessagesWithInterruptDetection()` returns `{ messages, turnInterruptionState }` (`DeserializeResult` / `TurnInterruptionState`, `utils/conversationRecovery.ts:139-146`, `utils/conversationRecovery.ts:247`) across six stages:
   - Migrates legacy attachments (`migrateLegacyAttachmentTypes()`, `utils/conversationRecovery.ts:77-132`), strips unknown `permissionMode` strings, and filters unresolved `tool_use`s, orphaned thinking-only blocks, and whitespace-only assistant messages.
   - Runs `detectTurnInterruption()` (`utils/conversationRecovery.ts:272-333`), skipping trailing `system`, `progress`, and `isApiErrorMessage` assistants. For trailing `tool_result`s, `isTerminalToolResult()` (`utils/conversationRecovery.ts:348-373`) recognizes brief/Kairos terminal tools—present `tools/BriefTool/prompt.ts` (`feature('KAIROS') || feature('KAIROS_BRIEF')`, `utils/conversationRecovery.ts:55-66`) and absent `tools/SendUserFileTool/prompt.js` (`feature('KAIROS')`, `utils/conversationRecovery.ts:67-71`)—fixing `#20467`.
   - Turns `interrupted_turn` into `interrupted_prompt` by appending synthetic `isMeta: true` `'Continue from where you left off.'`, plus a `NO_RESPONSE_REQUESTED` assistant sentinel so history stays API-valid even without auto-continue.

### Resume Loading, Hydration & `--fork-session` (`utils/conversationRecovery.ts`, `utils/sessionRestore.ts`)

`loadConversationForResume()` (`utils/conversationRecovery.ts:456-597`) resolves `--continue` (skipping live `--bg`/daemon sessions via absent `utils/udsClient.js` behind `feature('BG_SESSIONS')`, `utils/conversationRecovery.ts:492-506`), `.jsonl` paths, UUIDs, or `LogOption`s.

It then runs `loadFullLog`, `copyPlanForResume`, `void copyFileHistoryForResume(log)` (`utils/conversationRecovery.ts:550`), `checkResumeConsistency()`, `restoreSkillStateFromMessages()` (`utils/conversationRecovery.ts:382-403`, replaying `invoked_skills` and suppressing duplicate `skill_listing`), `deserializeMessagesWithInterruptDetection()`, and `processSessionStartHooks('resume')`.

`restoreSessionStateFromLog()` (`utils/sessionRestore.ts:99-150`) hydrates `fileHistory` via `fileHistoryRestoreStateFromLog()` (`utils/sessionRestore.ts:104-108`), `attribution` (`feature('COMMIT_ATTRIBUTION')`), and legacy SDK `todos` (`!isTodoV2Enabled()`, `utils/tasks.ts:133-139`, bypassed by `CLAUDE_CODE_ENABLE_TASKS`).

Under `feature('CONTEXT_COLLAPSE')` (`utils/sessionRestore.ts:127-136`), it calls absent `services/contextCollapse/persist.js`'s `restoreFromEntries()` even on empty arrays so `/resume` clears stale collapse state.

`processResumedConversation()` (`utils/sessionRestore.ts:409-551`) runs coordinator sync (`feature('COORDINATOR_MODE')`), `restoreAgentFromSession()`, non-fork worktree `chdir` (`restoreWorktreeForResume()`, `utils/sessionRestore.ts:479`; `exitRestoredWorktree()` at `utils/sessionRestore.ts:380-400` runs only on mid-session `/resume`, `screens/REPL.tsx:1878`), a second `CONTEXT_COLLAPSE` restore (`utils/sessionRestore.ts:494-503`), and the in-place vs. `--fork-session` split:

```ts
// utils/sessionRestore.ts:436-463
  if (!opts.forkSession) {
    const sid = opts.sessionIdOverride ?? result.sessionId
    if (sid) {
      // When resuming from a different project directory (git worktrees,
      // cross-project), transcriptPath points to the actual file; its dirname
      // is the project dir. Otherwise the session lives in the current project.
      switchSession(
        asSessionId(sid),
        opts.transcriptPath ? dirname(opts.transcriptPath) : null,
      )
      // Rename asciicast recording to match the resumed session ID so
      // getSessionRecordingPaths() can discover it during /share
      await renameRecordingForSession()
      await resetSessionFilePointer()
      restoreCostStateForSession(sid)
    }
  } else if (result.contentReplacements?.length) {
    // --fork-session keeps the fresh startup session ID. useLogMessages will
    // copy source messages into the new JSONL via recordTranscript, but
    // content-replacement entries are a separate entry type only written by
    // recordContentReplacement (which query.ts calls for newlyReplaced, never
    // the pre-loaded records). Without this seed, `claude -r {newSessionId}`
    // finds source tool_use_ids in messages but no matching replacement records
    // → they're classified as FROZEN → full content sent (cache miss, permanent
    // overage). insertContentReplacement stamps sessionId = getSessionId() =
    // the fresh ID, so loadTranscriptFile's keyed lookup will match.
    await recordContentReplacement(result.contentReplacements)
  }
```

> [!IMPORTANT]
> **How `--fork-session` Works (No UUID Remapping):** `processResumedConversation()` keeps the fresh startup `sessionId` and does **not** remap message UUIDs. It seeds `recordContentReplacement()` against `FROZEN` cache misses and strips `worktreeSession: undefined` (`utils/sessionRestore.ts:465-472`) so fork `/exit` cannot delete the parent's worktree.
>
> It also skips `restoreWorktreeForResume()` and `adoptResumedSessionFile()` (`utils/sessionStorage.ts:1530-1534`), letting `recordTranscript()` → `insertMessageChain()` (`utils/sessionStorage.ts:993-1083`) re-stamp `sessionId` *after* `...message` (`utils/sessionStorage.ts:1048-1064`).

---

## 5. Rolling Back Conversation & Disk Together: `/rewind` (`utils/fileHistory.ts`)

### The Problem

Rewinding `messages` without disk rollback desyncs files from memory. Naive snapshotting blocks reducers with I/O, OOMs via `readFileSync`+`writeFileSync`, overwrites `v1` backups, and loses backups on session expiry.

### The Real Implementation (`utils/fileHistory.ts`)

[`utils/fileHistory.ts`](../../utils/fileHistory.ts) (1,115 lines; zero `feature()`, `USER_TYPE`, or GrowthBook gates) solves all five hazards:

1. **Dual interactive vs. SDK gate (`utils/fileHistory.ts:63-78`):** Interactive mode defaults **on** unless `fileCheckpointingEnabled === false` or `CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING` is truthy. SDK/non-interactive mode defaults **off**, requiring `CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING` truthy and `CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING` falsy.
2. **Three-phase async protocol (`fileHistoryTrackEdit()` at `utils/fileHistory.ts:86-193`, `fileHistoryMakeSnapshot()` at `utils/fileHistory.ts:198-342`):**
   - **Phase 1 (Same-ref capture):** Calls `updateFileHistoryState(state => { captured = state; return state })`, letting same-ref wrappers (`QueryEngine.ts:376-384`, `screens/REPL.tsx:2442-2454`) skip notifications and no-op stubs (`utils/forkedAgent.ts:432`) bail cleanly. In `fileHistoryTrackEdit()`, Phase 1 guards `mostRecent.trackedFileBackups[trackingPath]` (`utils/fileHistory.ts:99-118`) so repeat edits never corrupt `{hash}@v1`.
   - **Phase 2 (Async disk I/O):** Runs `stat()`, `checkOriginFileChanged()`, and `createBackup()` outside store updaters.
   - **Phase 3 (Fresh re-read commit):** Inherits files tracked during Phase 2's async window (`utils/fileHistory.ts:290-297`), enforces `MAX_SNAPSHOTS = 100` (`utils/fileHistory.ts:54`, `utils/fileHistory.ts:305-313`) with monotonic `snapshotSequence`, and persists via `recordFileHistorySnapshot()`.
3. **Path-hashed backups & stat-first creation sentinels (`utils/fileHistory.ts:725-798`):** `getBackupFileName()` computes `{sha256(filePath).slice(0, 16)}@v{version}` under `{configDir}/file-history/{sessionId}/`—hashing the **path**, not contents *(correcting imprecise `"content hash"` comments in `tools/FileEditTool/FileEditTool.ts:433` and `tools/FileWriteTool/FileWriteTool.ts:257`)*. `createBackup()` keeps source-missing distinct from dir-missing and avoids heap OOMs:

   ```ts
   // utils/fileHistory.ts:759-786
     // Stat first: if the source is missing, record a null backup and skip the
     // copy. Separates "source missing" from "backup dir missing" cleanly —
     // sharing a catch for both meant a file deleted between copyFile-success
     // and stat would leave an orphaned backup with a null state record.
     let srcStats: Stats
     try {
       srcStats = await stat(filePath)
     } catch (e: unknown) {
       if (isENOENT(e)) {
         return { backupFileName: null, version, backupTime: new Date() }
       }
       throw e
     }

     // copyFile preserves content and avoids reading the whole file into the JS
     // heap (which the previous readFileSync+writeFileSync pipeline did, OOMing
     // on large tracked files). Lazy mkdir: 99% of calls hit the fast path
     // (directory already exists); on ENOENT, mkdir then retry.
     try {
       await copyFile(filePath, backupPath)
     } catch (e: unknown) {
       if (!isENOENT(e)) throw e
       await mkdir(dirname(backupPath), { recursive: true })
       await copyFile(filePath, backupPath)
     }

     // Preserve file permissions on the backup.
     await chmod(backupPath, srcStats.mode)
   ```

4. **Dual-keyed DAG-branch replay (`utils/fileHistory.ts:172-175`, `utils/fileHistory.ts:319-322`, `utils/sessionStorage.ts:2248-2272`):** Turn-start `fileHistoryMakeSnapshot()` writes `entry.messageId = userMessage.uuid` with `isSnapshotUpdate: false`. Mid-turn `fileHistoryTrackEdit()` attaches `v1` to `mostRecentSnapshot` (keeping `snapshot.messageId = userMessage.uuid`) while keying the JSONL entry on the **assistant** `parentMessage.uuid` with `isSnapshotUpdate: true`.

   On load, `buildFileHistorySnapshotChain()` replays only entries along the active `parentUuid` branch, updating `snapshots[existingIndex]` in place so abandoned rewind branches never leak into active history.

   Under `fileHistoryEnabled()`, `fileHistoryRestoreStateFromLog()` (`utils/fileHistory.ts:888-917`; callers `utils/sessionRestore.ts:104-108`, `hooks/useFileHistorySnapshotInit.ts:16-24`) hydrates `FileHistoryState`: migrating legacy absolute paths via `maybeShortenFilePath()` (`utils/fileHistory.ts:867-876`), rebuilding `trackedFiles: Set<string>`, and setting `snapshotSequence: snapshots.length`.
5. **Pure-disk rewind + append-only conversation rewind (`utils/fileHistory.ts:347-397`, `utils/fileHistory.ts:537-672`, `utils/fileHistory.ts:847-862`):** `fileHistoryRewind()` never mutates `FileHistoryState` (allowing repeated forward/backward rewinds) and runs `applySnapshot()` across every path in `state.trackedFiles`.

   For targets predating a file's first edit, `getBackupFileNameFirstVersion()` checks `version === 1` (failing safe if `MAX_SNAPSHOTS = 100` evicted it). `null` calls `unlink()`; non-null calls `restoreBackup()` only when `checkOriginFileChanged()` / `compareStatsAndContent()` (`utils/fileHistory.ts:600-672`) detects existence, `mode`/`size`, `mtimeMs` fast-path, or UTF-8 content diffs.

   In parallel, interactive `/rewind` (`screens/REPL.tsx:3661-3707`) slices `messages` and triggers a **same-head shrink** in `useLogMessages` (`hooks/useLogMessages.ts:53-57`, `hooks/useLogMessages.ts:102-114`). JSONL is never truncated—the next prompt chains off the rewound leaf, leaving an abandoned fork that `walkChainBeforeParse()` skips.

   *(Forward seams: pre-edit `fileHistoryTrackEdit()` callers in `FileEditTool`, `FileWriteTool`, `NotebookEditTool`, and `BashTool`'s `applySedEdit()`—not general shell commands—belong to [Chapter 12](12-shell-execution-sandboxing-and-workspace-tools.md); `MessageSelector` `/rewind` belongs to UI chapters.)*

> [!WARNING]
> **Fork Backup Isolation & `switchSession` Quirk (`utils/fileHistory.ts:922-1046`):** Because `cleanupOldFileHistoryBackups()` (`utils/cleanup.ts:305-348`) deletes expired `{configDir}/file-history/{sessionId}/` directories wholesale, `copyFileHistoryForResume()` hard-links (`link`, fallback `copyFile`) backups into the new session directory so forks survive parent cleanup.
>
> Ordering quirk: `utils/conversationRecovery.ts:550` (before `utils/sessionRestore.ts:442`) and `screens/REPL.tsx:1802` (before `screens/REPL.tsx:1846`) invoke `copyFileHistoryForResume()` before `switchSession`, so its `previousSessionId === getSessionId()` short-circuit (`utils/fileHistory.ts:942-948`) only fires if the caller switched first.

---

## Putting Layer 2 Together

```mermaid
flowchart TD
  Caller["cli/print.ts -> ask() -> QueryEngine.submitMessage()"] --> Prep["processUserInput() + pre-query recordTranscript()"]
  Prep --> Snap["fileHistoryMakeSnapshot() (if fileHistoryEnabled)"]
  Snap --> Loop["Ch 07 query() single-turn AsyncGenerator"]
  Loop -->|"assistant / user / compact_boundary"| Persist["recordTranscript(): void assistant, await user/boundary"]
  Loop -->|"tool edits"| Track["fileHistoryTrackEdit() -> isSnapshotUpdate: true"]
  Loop -->|"assistant / progress / user"| Frame["normalizeMessage() -> SDKMessage stream"]
  Persist --> Storage["Project JSONL writeQueues (100 ms / 10 ms remote)"]
  Frame --> Guards["maxTurns / maxBudgetUsd / MAX_STRUCTURED_OUTPUT_RETRIES"]
  Guards --> Result["Eager flush (Cowork) + SDKResultMessage"]
  Storage -->|"restart / --resume / --fork-session"| Load["loadTranscriptFile() -> walkChainBeforeParse() -> parseJSONL()"]
  Load --> Recover["deserializeMessagesWithInterruptDetection() + processResumedConversation()"]
  Recover --> Caller
```

> [!NOTE]
> **Snapshot-Absent Modules Observed via Call Sites Only (Never Linked):** These imports are **absent from this checkout** and documented strictly from call sites and present schemas:
> - `types/message.js` (`QueryEngine.ts:42`, `utils/queryHelpers.ts:19`, `utils/sessionStorage.ts:57-64`, `utils/sessionRestore.ts:30`, `utils/conversationRecovery.ts:15-19`) and `types/messageQueueTypes.js` (`utils/sessionStorage.ts:65`).
> - `services/compact/snipCompact.js` & `services/compact/snipProjection.js` (`QueryEngine.ts:122-127`, `feature('HISTORY_SNIP')`) — observed via `snipReplay` (`QueryEngine.ts:1278-1282`).
> - `services/contextCollapse/persist.js` (`utils/sessionRestore.ts:127-136`, `utils/sessionRestore.ts:494-503`) & `services/contextCollapse/index.js` (`services/compact/postCompactCleanup.ts:42-50`, `screens/REPL.tsx:3677-3688`, `feature('CONTEXT_COLLAPSE')`) — paired with zero-caller `recordContextCollapseCommit()` / `recordContextCollapseSnapshot()` (`utils/sessionStorage.ts:1541-1581`).
> - `utils/udsClient.js` (`utils/conversationRecovery.ts:492-506`, `feature('BG_SESSIONS')`) & `utils/udsMessaging.js` (`utils/messages/systemInit.ts:88-93`, `feature('UDS_INBOX')`).
> - `tools/SendUserFileTool/prompt.js` (`utils/conversationRecovery.ts:67-71`, `feature('KAIROS')`), paired with present `tools/BriefTool/prompt.ts`.
> - `entrypoints/sdk/controlTypes.ts`, `entrypoints/sdk/runtimeTypes.ts`, `entrypoints/sdk/toolTypes.ts`, `entrypoints/sdk/sdkUtilityTypes.ts`, `entrypoints/sdk/coreTypes.generated.ts`, `entrypoints/sdk/settingsTypes.generated.ts` (re-exported by `entrypoints/agentSdkTypes.ts:19-31`, `entrypoints/sdk/coreTypes.ts:19-22`; live schemas in `entrypoints/sdk/coreSchemas.ts`, `entrypoints/sdk/controlSchemas.ts`), plus comment-only `useGitDiffStats` (`utils/fileHistory.ts:49`).

---

## How This Snaps Into the Next Layer

Chapter 08 closes **Layer 2 (The Agent Engine)**. [Chapter 09](09-five-layer-compaction-pipeline.md) opens **Layer 3 (Long-Horizon Context & Memory)** directly on top of Chapter 08's persistence hooks:

- `services/compact/compact.ts:598`, `services/compact/compact.ts:1014`, and `services/compact/sessionMemoryCompact.ts:447` emit `compact_boundary` entries (with `services/compact/compact.ts:711` and `services/compact/compact.ts:1057` calling `reAppendSessionMetadata()`) before `utils/sessionStorage.ts:1040-1041` severs `parentUuid` and saves `logicalParentUuid`.
- `query.ts:376-535` runs five pre-API stages: tool-result budget (`recordContentReplacement`, `query.ts:376-394`), snip (`feature('HISTORY_SNIP')`, `query.ts:401-410`), microcompact (`query.ts:413-426`; post-API `microcompact_boundary` via `feature('CACHED_MICROCOMPACT')`, `query.ts:870-892`), collapse (`feature('CONTEXT_COLLAPSE')` → snapshot-absent `contextCollapse.applyCollapsesIfNeeded()`, `query.ts:440-447`), and autocompact (`query.ts:454-535`).
- Zero-caller `recordContextCollapseCommit()`/`recordContextCollapseSnapshot()` (`utils/sessionStorage.ts:1541-1581`) define the `marble-origami-commit`/`marble-origami-snapshot` writers; `QueryEngine.ts:701-715` flushes `preservedSegment.tailUuid`, and `QueryEngine.ts:918-942` splices pre-boundary history for GC.
- `services/compact/postCompactCleanup.ts:76` calls `clearSessionMessagesCache()` (`utils/sessionStorage.ts:3854-3856`) to clear `getSessionMessages`'s UUID dedup cache.

---

## Reading Exercises & Code Checkpoints

1. **Trace conversation-lifetime state in `QueryEngine` vs. single-turn `query()`:**
   ```sh
   rg -n 'export (class QueryEngine|async function\* ask)|private (mutableMessages|readFileState|permissionDenials|totalUsage|hasHandledOrphanedPermission|discoveredSkillNames|loadedNestedMemoryPaths)|async \*submitMessage\(|for await \(const message of query\(' QueryEngine.ts
   ```
   Verify why `discoveredSkillNames` clears at `QueryEngine.ts:238` while `loadedNestedMemoryPaths` persists, and why `cli/print.ts:2133` creates a fresh `AbortController` before every `ask()` call.
2. **Locate JSONL scale guards and two-level crash-recovery entry points:**
   ```sh
   rg -n 'MAX_TRANSCRIPT_READ_BYTES|SKIP_PRECOMPACT_THRESHOLD|walkChainBeforeParse|CLAUDE_CODE_DISABLE_PRECOMPACT_SKIP|deserializeMessagesWithInterruptDetection|handleOrphanedPermission' utils/sessionStorage.ts utils/sessionStoragePortable.ts utils/conversationRecovery.ts utils/queryHelpers.ts
   ```
   Trace why `walkChainBeforeParse()` gates on 50% dropped bytes (`len - chainBytes < len >> 1`) instead of entry counts, and compare syntactic recovery in `utils/json.ts:102-127` with semantic repair in `utils/conversationRecovery.ts:164-252`.
3. **Audit file-checkpointing gates, pre-edit tracking sites, and `/rewind` callers:**
   ```sh
   rg -n 'fileHistory(TrackEdit|MakeSnapshot|Rewind)|CLAUDE_CODE_(DISABLE|ENABLE_SDK)_FILE_CHECKPOINTING' utils/fileHistory.ts utils/handlePromptSubmit.ts QueryEngine.ts tools/ screens/REPL.tsx cli/print.ts
   ```
   Confirm why SDK mode defaults checkpointing off while interactive mode defaults it on, and verify which tools invoke `fileHistoryTrackEdit()` (noting why general `BashTool` commands stay untracked outside `applySedEdit()`).
4. **Verify the Layer 2 → Layer 3 compaction persistence seam and snapshot-absent restore hook:**
   ```sh
   rg -n 'logicalParentUuid|applyPreservedSegmentRelinks|applySnipRemovals|clearSessionMessagesCache|contextCollapse/persist\.js' utils/sessionStorage.ts utils/sessionRestore.ts services/compact/postCompactCleanup.ts
   ```
   Follow a `compact_boundary` from `utils/sessionStorage.ts:1040-1041` through `applyPreservedSegmentRelinks()` (`utils/sessionStorage.ts:1839-1956`) and `clearSessionMessagesCache()` (`services/compact/postCompactCleanup.ts:76`) to prepare for [Chapter 09](09-five-layer-compaction-pipeline.md).


---

<!-- chapters/09-five-layer-compaction-pipeline.md — https://reverseengineeringclaudecode.com/chapters/09-five-layer-compaction-pipeline -->

# Chapter 09 — The Five-Layer Compaction Pipeline

> **Layer:** Layer 3 (Long-Horizon Context & Memory)
> **Prerequisites:** [Chapter 03](03-command-and-message-contracts.md) (`normalizeMessagesForAPI`), [Chapter 04](04-prompt-engineering-and-cache-boundaries.md) (prompt cache), [Chapter 05](05-talking-to-the-model.md) (`addCacheBreakpoints`, `utils/betas.ts`), [Chapter 06](06-executing-tools.md) (`applyToolResultBudget`), [Chapter 07](07-the-heartbeat-query-loop.md) (`query.ts`, `QueryDeps`), [Chapter 08](08-session-envelope-query-engine-and-transcripts.md) (`QueryEngine.ts`, `utils/sessionStorage.ts`)
> **Primary Source Files:**
> - [`query.ts`](../../query.ts) — five-stage pre-API pipeline, blocking-limit guard, deferred microcompact boundary, overflow recovery, `taskBudgetRemaining` (1,729 lines)
> - [`services/compact/microCompact.ts`](../../services/compact/microCompact.ts) — cold-cache clearing, warm-cache `CACHED_MICROCOMPACT` dispatch, main-thread isolation (530 lines)
> - [`services/compact/apiMicrocompact.ts`](../../services/compact/apiMicrocompact.ts) — server-side `context_management` edits (`clear_thinking_20251015`, ant-only `clear_tool_uses_20250919`) (153 lines)
> - [`services/compact/autoCompact.ts`](../../services/compact/autoCompact.ts) — window math, thresholds, exclusivity guards, SessionMemory dispatch, 3-failure breaker (351 lines)
> - [`services/compact/compact.ts`](../../services/compact/compact.ts) — full/partial summarization, cache-sharing fork, PTL retries, `compact_boundary`, budgeted restoration (1,705 lines)
> - [`services/compact/sessionMemoryCompact.ts`](../../services/compact/sessionMemoryCompact.ts) — zero-LLM SessionMemory fast path, boundary-floored tail expansion, invariant repair (630 lines)
> - [`services/compact/prompt.ts`](../../services/compact/prompt.ts) — no-tools preamble/trailer, 9-section templates, `<analysis>` stripping, continuation framing (374 lines)
> - [`services/compact/postCompactCleanup.ts`](../../services/compact/postCompactCleanup.ts) — `isMainThreadCompact`-guarded 10-step cache invalidation (77 lines)
> - Sibling helpers: [`services/compact/timeBasedMCConfig.ts`](../../services/compact/timeBasedMCConfig.ts) (43 lines), [`services/compact/grouping.ts`](../../services/compact/grouping.ts) (63 lines), [`services/compact/compactWarningState.ts`](../../services/compact/compactWarningState.ts) (18 lines), [`services/compact/compactWarningHook.ts`](../../services/compact/compactWarningHook.ts) (16 lines)
> - `services/contextCollapse/` (absent from this snapshot — observed via call sites only; likewise absent: `services/compact/snipCompact.js`, `services/compact/snipProjection.js`, `services/compact/cachedMicrocompact.js`, `services/compact/reactiveCompact.js`, `constants/querySource.js`, `proactive/index.js`, `services/sessionTranscript/sessionTranscript.js`, `utils/attributionHooks.js`, and `types/message.js`)

---

## Why This Layer Exists

By the end of Layer 2 ([Chapter 07](07-the-heartbeat-query-loop.md) and [Chapter 08](08-session-envelope-query-engine-and-transcripts.md)), Claude Code runs multi-step turns and persists JSONL transcripts until a session hits the context ceiling. Naive truncation fails in five ways, which Layer 3 solves via a five-stage pre-API cascade plus two-tier post-API overflow recovery:

1. **Prompt-cache demolition:** Mutating earlier messages busts the prefix cache ([Chapter 04](04-prompt-engineering-and-cache-boundaries.md), [Chapter 05](05-talking-to-the-model.md)), turning cheap reads into full-prefix writes.
2. **API-contract violations:** Mid-turn cuts sever `tool_use`/`tool_result` pairs ([Chapter 03](03-command-and-message-contracts.md)), split streamed `thinking` blocks sharing a `message.id`, or leave an assistant-first payload.
3. **Append-only transcript corruption:** `utils/sessionStorage.ts` never rewrites logged JSONL lines; keeping recent messages across a boundary without relink metadata breaks `--resume` chains and leaves stale `~190K` usage.
4. **Death spirals & cross-thread corruption:** Retrying doomed compactions burns hundreds of thousands of API calls/day, and in-process subagents (`agent:*`) share module-level caches with the main REPL thread.
5. **Task-budget blindness:** Server-side `output_config.task_budget` counts down from visible history; once compaction shrinks history, the server under-counts spend unless `query.ts` subtracts the erased window manually.

---

## 1. The Five-Stage Pre-API Pipeline & Reactive Overflow Recovery

### The Problem

No single compression tactic fits every turn. Large tool outputs spill to disk first; cold-cache idle sessions clear old tool bodies for free; warm sessions trim without busting prefix caches; span collapse preempts full summaries; and HTTP 413 (`prompt_too_long`) or media rejections need post-API recovery.

### The Real Implementation

Each `queryLoop()` iteration builds a post-boundary view (`query.ts:365`) via `getMessagesAfterCompactBoundary()` (`utils/messages.ts:4643-4656`, calling absent `services/compact/snipProjection.js`'s `projectSnippedView()` under `feature('HISTORY_SNIP')`). It then runs five ordered stages before `deps.callModel()` (`query/deps.ts:21-40` binds `microcompact: microcompactMessages` and `autocompact: autoCompactIfNeeded`):

- **Stage 1 — Tool-result budget (`query.ts:376-394`):** Runs `applyToolResultBudget()` ([Chapter 06](06-executing-tools.md), `utils/toolResultStorage.ts:924-936`), persisting replacements via `recordContentReplacement()` only for `'agent:*'` and `'repl_main_thread*'` sources (prefix-matched via `.startsWith()`, `query.ts:376-378`) and skipping tools with `!Number.isFinite(t.maxResultSizeChars)`.
- **Stage 2 — History snip (`query.ts:400-410`):** Behind `feature('HISTORY_SNIP')`, calls absent `services/compact/snipCompact.js`'s `snipCompactIfNeeded()`, captures `snipTokensFreed`, and yields any `boundaryMessage` (replayed on `mutableMessages` at `QueryEngine.ts:905-915` / `QueryEngine.ts:1276-1284` and relinked on resume at `utils/sessionStorage.ts:1982-2039`).
- **Stage 3 — Microcompact (`query.ts:413-426`, `query.ts:870-892`):** Runs `deps.microcompact()`. Under `feature('CACHED_MICROCOMPACT')`, holds `pendingCacheEdits` until post-API usage arrives so `createMicrocompactBoundaryMessage()` records server-deleted tokens. Server-side `apiMicrocompact.ts` runs orthogonally in `services/api/claude.ts:1633-1637`.

```ts
// query.ts:400-426
let snipTokensFreed = 0
if (feature('HISTORY_SNIP')) {
  queryCheckpoint('query_snip_start')
  const snipResult = snipModule!.snipCompactIfNeeded(messagesForQuery)
  messagesForQuery = snipResult.messages
  snipTokensFreed = snipResult.tokensFreed
  if (snipResult.boundaryMessage) {
    yield snipResult.boundaryMessage
  }
  queryCheckpoint('query_snip_end')
}

// Apply microcompact before autocompact
queryCheckpoint('query_microcompact_start')
const microcompactResult = await deps.microcompact(
  messagesForQuery,
  toolUseContext,
  querySource,
)
messagesForQuery = microcompactResult.messages
// For cached microcompact (cache editing), defer boundary message until after
// the API response so we can use actual cache_deleted_input_tokens.
// Gated behind feature() so the string is eliminated from external builds.
const pendingCacheEdits = feature('CACHED_MICROCOMPACT')
  ? microcompactResult.compactionInfo?.pendingCacheEdits
  : undefined
queryCheckpoint('query_microcompact_end')
```

- **Stage 4 — Context collapse (`query.ts:440-447`):** Behind `feature('CONTEXT_COLLAPSE')`, calls absent `services/contextCollapse/index.js`'s `applyCollapsesIfNeeded()`. Nothing is yielded: collapse projects a read-time view backed by `marble-origami-commit`/`marble-origami-snapshot` JSONL entries (`utils/sessionStorage.ts:1541-1581`, restored via absent `services/contextCollapse/persist.js` at `utils/sessionRestore.ts:127-136`).
- **Stage 5 — Proactive autocompact (`query.ts:453-543`):** Runs `deps.autocompact(..., tracking, snipTokensFreed)`. On hit, logs `tengu_auto_compact_succeeded`, updates `taskBudgetRemaining` (`query.ts:508-515`), resets `tracking` with `consecutiveFailures: 0` (`query.ts:521-526`), yields `buildPostCompactMessages()`, and swaps `messagesForQuery`. On failure, propagates `consecutiveFailures` (`query.ts:536-543`).
- **Blocking-limit guard & two-tier overflow recovery (`query.ts:615-648`, `query.ts:799-825`, `query.ts:1070-1183`):** Exits with `{ reason: 'blocking_limit' }` (`query.ts:628-648`) unless compaction succeeded, `querySource` is `'compact'`/`'session_memory'`, or reactive compact or context collapse (`collapseOwnsIt`, `query.ts:615-620`) owns real 413 recovery. While streaming, `query.ts:799-825` withholds recoverable 413 and media-size errors:
  1. For `isWithheld413`, `query.ts:1089-1117` calls `contextCollapse.recoverFromOverflow()` once (`state.transition?.reason !== 'collapse_drain_retry'`), retrying with `{ reason: 'collapse_drain_retry', committed }` if `drained.committed > 0`.
  2. For unrecovered `isWithheld413` or `isWithheldMedia` (media skips collapse drain because collapse never strips images, `query.ts:1074-1076`), `query.ts:1119-1166` calls absent `services/compact/reactiveCompact.js`'s `tryReactiveCompact()`, updates `taskBudgetRemaining` (`query.ts:1138-1146`), yields `buildPostCompactMessages()`, sets `hasAttemptedReactiveCompact: true`, and retries with `{ reason: 'reactive_compact_retry' }`.

| Stage | Call Site in `query.ts` | Gate | Snapshot Status & Observed Interface |
|---|---|---|---|
| 1. Tool-result budget | `query.ts:379-394` | `contentReplacementState` present | **Present** (`utils/toolResultStorage.ts:924-936`, Ch 06) |
| 2. History snip | `query.ts:401-410` | `feature('HISTORY_SNIP')` | **Absent** (`services/compact/snipCompact.js`, `snipProjection.js` — `snipCompactIfNeeded`, `tokensFreed`, `boundaryMessage`, `projectSnippedView`) |
| 3. Microcompact | `query.ts:414-425`, `query.ts:870-892` | `tengu_slate_heron` / `feature('CACHED_MICROCOMPACT')` | **Hybrid** (`microCompact.ts` & `apiMicrocompact.ts` present; `services/compact/cachedMicrocompact.js` absent) |
| 4. Context collapse | `query.ts:440-447`, `query.ts:1089-1117` | `feature('CONTEXT_COLLAPSE')` | **Absent** (`services/contextCollapse/index.js`, `operations.js`, `persist.js` — `applyCollapsesIfNeeded`, `isContextCollapseEnabled`, `isWithheldPromptTooLong`, `recoverFromOverflow`, `resetContextCollapse`, `getStats`) |
| 5. Autocompact & reactive | `query.ts:454-543`, `query.ts:1119-1183` | `DISABLE_COMPACT` / `DISABLE_AUTO_COMPACT` / `feature('REACTIVE_COMPACT')` | **Hybrid** (`autoCompact.ts`, `compact.ts`, `sessionMemoryCompact.ts` present; `services/compact/reactiveCompact.js` absent) |

### Hidden Invariants & Failure Modes

- **Stage 1 precedes Stage 3 (`query.ts:369-372`):** Cached microcompact keys solely on `tool_use_id` without inspecting block content, so Stage 1's `<persisted-output>` spills compose ahead of Stage 3 with zero cache-key churn.
- **Stale API usage after snip (`query.ts:396-399`, `query.ts:637-640`, `services/compact/autoCompact.ts:225`):** The protected tail assistant survives snipping unchanged, so `tokenCountWithEstimation()` misses snipped tokens. Subtracting `snipTokensFreed` in `shouldAutoCompact()` and the blocking-limit guard prevents false triggers.
- **`mediaRecoveryEnabled` hoisting scar (`query.ts:621-627`, `query.ts:814-819`, `query.ts:1082-1084`):** Hoisting `reactiveCompact?.isReactiveCompactEnabled() ?? false` before streaming ensures withholding and recovery agree; otherwise a `CACHED_MAY_BE_STALE` refresh mid-stream could withhold and drop a media error.
- **Stop-hook death-spiral guard (`query.ts:1168-1183`, `query.ts:1292-1297`):** Unrecovered overflow yields `lastMessage`, runs `executeStopFailureHooks`, and exits (`'prompt_too_long'` or `'image_error'`) *without* stop hooks (which inject tokens per cycle). `stop_hook_blocking` also preserves `hasAttemptedReactiveCompact`.

> [!NOTE]
> **Snapshot-Absence Discipline:** `services/contextCollapse/`, `services/compact/snipCompact.js`, `services/compact/snipProjection.js`, `services/compact/cachedMicrocompact.js`, and `services/compact/reactiveCompact.js` are absent here. All symbols above are call-site only: `getStats().stagedSpans` (`components/TokenWarning.tsx:40-42`) and `recoverFromOverflow()`'s `{ committed }` (`query.ts:1098`); no `isStaged` symbol exists.
>
> Likewise, `utils/sessionStorage.ts` special-cases `compact_boundary` (`isCompactBoundaryMessage`), **not** `microcompact_boundary`, which persists as a standard system entry (`utils/messages.ts:4557-4583`) and is suppressed from UI rendering (returning `null`) at `components/Message.tsx:246-248`.

---

## 2. Microcompaction: Cold-Cache Clearing, Warm-Cache Edits, and Server-Side Policies

### The Problem

Tool outputs from `Read`, `Bash`, `PowerShell`, `Grep`, `Glob`, `WebSearch`, `WebFetch`, `Edit`, and `Write` (`COMPACTABLE_TOOLS`, `services/compact/microCompact.ts:41-50`) drive most token growth. Naive local clearing mutates earlier user messages and forces full-prefix cache writes, so Claude Code splits microcompaction into three cache-aware paths.

### The Real Implementation

`microcompactMessages()` (`services/compact/microCompact.ts:253-293`) resets UI warning suppression via `clearCompactWarningSuppression()` (`services/compact/compactWarningState.ts:16-18`) and dispatches through two client paths before falling back to a no-op:

```ts
// services/compact/microCompact.ts:267-292
const timeBasedResult = maybeTimeBasedMicrocompact(messages, querySource)
if (timeBasedResult) {
  return timeBasedResult
}

// Only run cached MC for the main thread to prevent forked agents
// (session_memory, prompt_suggestion, etc.) from registering their
// tool_results in the global cachedMCState, which would cause the main
// thread to try deleting tools that don't exist in its own conversation.
if (feature('CACHED_MICROCOMPACT')) {
  const mod = await getCachedMCModule()
  const model = toolUseContext?.options.mainLoopModel ?? getMainLoopModel()
  if (
    mod.isCachedMicrocompactEnabled() &&
    mod.isModelSupportedForCacheEditing(model) &&
    isMainThreadSource(querySource)
  ) {
    return await cachedMicrocompactPath(messages, querySource)
  }
}

// Legacy microcompact path removed — tengu_cache_plum_violet is always true.
// For contexts where cached microcompact is not available (external builds,
// non-ant users, unsupported models, sub-agents), no compaction happens here;
// autocompact handles context pressure instead.
return { messages }
```

- **1. Cold-cache time-based clearing (`services/compact/microCompact.ts:422-530`, `services/compact/timeBasedMCConfig.ts:18-43`):** `evaluateTimeBasedTrigger()` reads GrowthBook `'tengu_slate_heron'` (defaults `{ enabled: false, gapThresholdMinutes: 60, keepRecent: 5 }`) and requires a non-`undefined` main-thread `querySource` so read-only callers (`/context`, `/compact`, `analyzeContext`) never clear history.
  - Once `(Date.now() - new Date(lastAssistant.timestamp).getTime()) / 60_000 >= config.gapThresholdMinutes` (`services/compact/microCompact.ts:438-442`), the 1h cache is cold; older `COMPACTABLE_TOOLS` results become `TIME_BASED_MC_CLEARED_MESSAGE` (`'[Old tool result content cleared]'`). Clamping `keepRecent = Math.max(1, config.keepRecent)` (`services/compact/microCompact.ts:458-462`) avoids `slice(-0)` before `suppressCompactWarning()`, `resetMicrocompactState()`, and `notifyCacheDeletion(querySource)` (`feature('PROMPT_CACHE_BREAK_DETECTION')`).
- **2. Warm-cache `CACHED_MICROCOMPACT` (`services/compact/microCompact.ts:305-399`, `query.ts:870-892`):** Behind `feature('CACHED_MICROCOMPACT')`, `cachedMicrocompactPath()` calls absent `services/compact/cachedMicrocompact.js` (`registerToolResult`, `registerToolMessage`, `getToolResultsToDelete`, `createCacheEditsBlock`), queues `pendingCacheEdits`, calls `suppressCompactWarning()`/`notifyCacheDeletion()`, and returns `messages` **untouched** with `baselineCacheDeletedTokens` (`usage.cache_deleted_input_tokens`).
  - `services/api/claude.ts:1531-1532` consumes `pendingCacheEdits` and fetches pinned edits before param construction (preventing retry double-consumption). `addCacheBreakpoints()` (`services/api/claude.ts:3108-3208`) re-inserts pinned `cache_edits` at each `userMessageIndex`, pins new edits (`pinCacheEdits()`), and tags `tool_result` blocks (`cache_reference: block.tool_use_id`). Post-response, `services/api/claude.ts:2834-2836` calls `markToolsSentToAPIState()`, and `query.ts:870-892` subtracts `baselineCacheDeletedTokens` for `createMicrocompactBoundaryMessage()`.
- **3. Orthogonal server-side `context_management` (`services/compact/apiMicrocompact.ts:64-153`):** Called solely by `services/api/claude.ts:1633-1637` and sent only when `useBetas` and `CONTEXT_MANAGEMENT_BETA_HEADER` (`'context-management-2025-06-27'`, `constants/betas.ts:7`) are active (`services/api/claude.ts:1718-1722`; enabled at `utils/betas.ts:301-312` by first-party betas plus ant-only `USE_API_CONTEXT_MANAGEMENT` requiring `USER_TYPE === 'ant'`, or thinking preservation):

```ts
// services/compact/apiMicrocompact.ts:82-102
if (hasThinking && !isRedactThinkingActive) {
  strategies.push({
    type: 'clear_thinking_20251015',
    keep: clearAllThinking ? { type: 'thinking_turns', value: 1 } : 'all',
  })
}

// Tool clearing strategies are ant-only
if (process.env.USER_TYPE !== 'ant') {
  return strategies.length > 0 ? { edits: strategies } : undefined
}

const useClearToolResults = isEnvTruthy(
  process.env.USE_API_CLEAR_TOOL_RESULTS,
)
const useClearToolUses = isEnvTruthy(process.env.USE_API_CLEAR_TOOL_USES)

// If no tool clearing strategy is enabled, return early
if (!useClearToolResults && !useClearToolUses) {
  return strategies.length > 0 ? { edits: strategies } : undefined
}
```

- **All users (`hasThinking && !isRedactThinkingActive`):** `clear_thinking_20251015` sends `keep: 'all'` normally and switches to `{ type: 'thinking_turns', value: 1 }` when `thinkingClearLatched` latches after >1h idle (`services/api/claude.ts:1446-1456`)—the API requires `value >= 1`, and omitting the edit defaults back to `'all'`.
- **Ant-only (`process.env.USER_TYPE === 'ant'`):** `USE_API_CLEAR_TOOL_RESULTS` sends `clear_tool_uses_20250919` with `clear_tool_inputs: TOOLS_CLEARABLE_RESULTS` (7 tools, `services/compact/apiMicrocompact.ts:19-26`), while `USE_API_CLEAR_TOOL_USES` sets `exclude_tools: TOOLS_CLEARABLE_USES` (`Edit`, `Write`, `NotebookEdit`, `services/compact/apiMicrocompact.ts:28-32`). Both trigger at `API_MAX_INPUT_TOKENS` (default `180_000`) with `clear_at_least = trigger - target` (`API_TARGET_INPUT_TOKENS`, default `40_000`).

### Hidden Invariants & Failure Modes

- **Two circular-dependency scars:** `TIME_BASED_MC_CLEARED_MESSAGE` is inlined (`services/compact/microCompact.ts:32-36`) rather than imported from `utils/toolResultStorage.ts:34` to break a 5-file cycle; time-based clearing calls `notifyCacheDeletion` over `notifyCompaction` (`services/compact/microCompact.ts:520-527`) to avoid tripping circular-deps lint.
- **Cold clear wipes warm state (`services/compact/microCompact.ts:512-517`):** `resetMicrocompactState()` stops cached MC on the next turn from sending `cache_edits` for already-cleared tool IDs.
- **React-free warning store (`services/compact/compactWarningState.ts:8-18`, `services/compact/compactWarningHook.ts:11-16`):** Isolating `useCompactWarningSuppression()` (read by `components/TokenWarning.tsx:107-110`) keeps React off print-mode startup.
- **Latent `querySource` mismatch (`services/compact/microCompact.ts:249-251` vs `services/api/claude.ts:1437`, `services/api/claude.ts:1678`, `services/api/claude.ts:1682`):** `isMainThreadSource()` prefix-matches `repl_main_thread*`, but `claude.ts` checks `=== 'repl_main_thread'`—so custom output styles queue and consume `pendingCacheEdits` without injecting them.

---

## 3. Threshold Math, Exclusivity Guards & the Three-Failure Circuit Breaker

### The Problem

Compaction runs inside the same context window as ordinary turns: firing too late makes the summarizer 413, while firing too early wastes headroom and races Stage 4 context collapse. Worse, retrying doomed compactions on an over-limit session creates an unbounded API burn.

### The Real Implementation

`getEffectiveContextWindowSize(model)` (`services/compact/autoCompact.ts:28-49`) reserves `Math.min(getMaxOutputTokensForModel(model), MAX_OUTPUT_TOKENS_FOR_SUMMARY)` (`20_000`, sized above p99.99 summary output of `17,387` tokens) from `getContextWindowForModel(model, getSdkBetas())` (optionally clamped by `CLAUDE_CODE_AUTO_COMPACT_WINDOW`):

```ts
// services/compact/autoCompact.ts:62-70
export const AUTOCOMPACT_BUFFER_TOKENS = 13_000
export const WARNING_THRESHOLD_BUFFER_TOKENS = 20_000
export const ERROR_THRESHOLD_BUFFER_TOKENS = 20_000
export const MANUAL_COMPACT_BUFFER_TOKENS = 3_000

// Stop trying autocompact after this many consecutive failures.
// BQ 2026-03-10: 1,279 sessions had 50+ consecutive failures (up to 3,272)
// in a single session, wasting ~250K API calls/day globally.
const MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES = 3
```

- **Thresholds (`services/compact/autoCompact.ts:72-145`):** `getAutoCompactThreshold(model)` returns `effectiveContextWindow - 13_000` (optionally tightened via `Math.min` by `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE`). `calculateTokenWarningState()` places `warningThreshold`/`errorThreshold` at `threshold - 20_000` (`autoCompactThreshold` if enabled, else `effectiveContextWindow`) and `defaultBlockingLimit` at `effectiveContextWindow - 3_000` (`CLAUDE_CODE_BLOCKING_LIMIT_OVERRIDE`).
- `isAutoCompactEnabled()` (`services/compact/autoCompact.ts:147-158`) checks `DISABLE_COMPACT`, `DISABLE_AUTO_COMPACT`, and `getGlobalConfig().autoCompactEnabled`.
- `shouldAutoCompact()` (`services/compact/autoCompact.ts:160-239`) runs six ordered gates before testing `tokenCountWithEstimation(messages) - snipTokensFreed`:
  1. **Fork recursion (`services/compact/autoCompact.ts:171-173`):** Blocks `'session_memory'` and `'compact'`.
  2. **Collapse agent (`services/compact/autoCompact.ts:179-183`):** Behind `feature('CONTEXT_COLLAPSE')`, blocks `'marble_origami'` so the codename DCEs from external builds and the ctx-agent cannot wipe collapse state.
  3. **Toggle (`services/compact/autoCompact.ts:185-187`):** Returns `false` if `!isAutoCompactEnabled()`.
  4. **Reactive-only (`services/compact/autoCompact.ts:195-199`):** Behind `feature('REACTIVE_COMPACT')`, GrowthBook `'tengu_cobalt_raccoon'` suppresses proactive autocompact so reactive compact catches real 413s.
  5. **Collapse ownership (`services/compact/autoCompact.ts:215-223`):** Behind `feature('CONTEXT_COLLAPSE')`, inline-requires absent `services/contextCollapse/index.js` (breaking an init cycle with `getEffectiveContextWindowSize`) and suppresses proactive autocompact when `isContextCollapseEnabled()` is true so ~93% autocompact never races collapse's 90%–95% window.
  6. **Threshold (`services/compact/autoCompact.ts:225-238`):** Checks `calculateTokenWarningState(tokenCountWithEstimation(messages) - snipTokensFreed, model).isAboveAutoCompactThreshold`.

`autoCompactIfNeeded()` (`services/compact/autoCompact.ts:241-351`) checks `DISABLE_COMPACT`, bails if `tracking?.consecutiveFailures >= 3` (`services/compact/autoCompact.ts:260-265`), runs `shouldAutoCompact()`, tries `trySessionMemoryCompaction()` (`services/compact/autoCompact.ts:288-310`), and otherwise invokes `compactConversation()`:

```ts
// services/compact/autoCompact.ts:328-350
  return {
    wasCompacted: true,
    compactionResult,
    // Reset failure count on success
    consecutiveFailures: 0,
  }
} catch (error) {
  if (!hasExactErrorMessage(error, ERROR_MESSAGE_USER_ABORT)) {
    logError(error)
  }
  // Increment consecutive failure count for circuit breaker.
  // The caller threads this through autoCompactTracking so the
  // next query loop iteration can skip futile retry attempts.
  const prevFailures = tracking?.consecutiveFailures ?? 0
  const nextFailures = prevFailures + 1
  if (nextFailures >= MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES) {
    logForDebugging(
      `autocompact: circuit breaker tripped after ${nextFailures} consecutive failures — skipping future attempts this session`,
      { level: 'warn' },
    )
  }
  return { wasCompacted: false, consecutiveFailures: nextFailures }
}
```

`query.ts:536-543` threads `consecutiveFailures` back into `tracking`, `query.ts:521-526` resets `consecutiveFailures: 0` on success, and `query.ts:1523-1533` increments `tracking.turnCounter++` (`tengu_post_autocompact_turn`) on later tool turns.

### Hidden Invariants & Failure Modes

- **Why exclusivity lives in `shouldAutoCompact()` (`services/compact/autoCompact.ts:206-209`):** `query.ts:633` and reactive compact call `isAutoCompactEnabled()` directly, so gating proactive triggers inside `shouldAutoCompact()` keeps reactive 413 fallback and `/compact` working under context collapse.
- **User-abort nuance (`services/compact/autoCompact.ts:335-349`):** `ERROR_MESSAGE_USER_ABORT` suppresses `logError(error)`, **yet still increments `consecutiveFailures`**. By contrast, `trySessionMemoryCompaction()` returning `null` falls through to `compactConversation()` without touching the breaker.

---

## 4. Full & Partial LLM Summarization, `compact_boundary`, and Budgeted Restoration

### The Problem

Sending compaction with a custom system prompt and stripped tools causes a ~98% cache miss—an internal January 2026 experiment measured ~0.76% of fleet `cache_creation` (~38B tokens/day), concentrated in ephemeral environments and 3P providers (`services/compact/compact.ts:431-434`). Meanwhile, compaction can hit `prompt_too_long`, adaptive-thinking models may attempt tool calls, and clearing `readFileState` wipes the working set without bounded restoration.

### The Real Implementation

**Prompt-cache-sharing fork vs. streaming fallback (`services/compact/compact.ts:1136-1396`).** Behind GrowthBook kill-switch `'tengu_compact_cache_prefix'` (default `true`, `services/compact/compact.ts:1155-1158`), `streamCompactSummary()` reuses the parent's prompt cache via `runForkedAgent()` (Chapter 18 seam), running a 30s WebSocket keep-alive (`sendSessionActivitySignal` + `setSDKStatus('compacting')`) whenever `isSessionActivityTrackingActive()` (`services/compact/compact.ts:1167-1176`):

```ts
// services/compact/compact.ts:1181-1200
// DO NOT set maxOutputTokens here. The fork piggybacks on the main thread's
// prompt cache by sending identical cache-key params (system, tools, model,
// messages prefix, thinking config). Setting maxOutputTokens would clamp
// budget_tokens via Math.min(budget, maxOutputTokens-1) in claude.ts,
// creating a thinking config mismatch that invalidates the cache.
// The streaming fallback path (below) can safely set maxOutputTokensOverride
// since it doesn't share cache with the main thread.
const result = await runForkedAgent({
  promptMessages: [summaryRequest],
  cacheSafeParams,
  canUseTool: createCompactCanUseTool(),
  querySource: 'compact',
  forkLabel: 'compact',
  maxTurns: 1,
  skipCacheWrite: true,
  // Pass the compact context's abortController so user Esc aborts the
  // fork — same signal the streaming fallback uses at
  // `signal: context.abortController.signal` below.
  overrides: { abortController: context.abortController },
})
```

- `createCompactCanUseTool()` (`services/compact/compact.ts:1125-1134`) denies all tools, and `skipCacheWrite: true` avoids caching the one-shot prompt. On fallback (`services/compact/compact.ts:1250-1392`), `queryModelWithStreaming()` strips top-level/nested `image`/`document` blocks (`stripImagesFromMessages()`, `services/compact/compact.ts:145-200`) and `skill_discovery`/`skill_listing` attachments (`stripReinjectedAttachments()`, `feature('EXPERIMENTAL_SKILL_SEARCH')`, `services/compact/compact.ts:211-223`).
- The fallback disables thinking, caps `maxOutputTokensOverride` at `Math.min(20_000, getMaxOutputTokensForModel(model))`, and retries up to `MAX_COMPACT_STREAMING_RETRIES = 2` under GrowthBook `'tengu_compact_streaming_retry'` (default `false`).

- **Prompt framing (`services/compact/prompt.ts`):** Because the cache-sharing fork keeps tool schemas, Sonnet 4.6+ adaptive thinking called tools at `2.79%` (vs `0.01%` on 4.5) when forbidden only at the bottom (`services/compact/prompt.ts:12-18`). `getCompactPrompt()` (`services/compact/prompt.ts:293-303`) and `getPartialCompactPrompt()` (`services/compact/prompt.ts:274-291`, `'from'` vs `'up_to'`) wrap their 9-section templates in `NO_TOOLS_PREAMBLE` and `NO_TOOLS_TRAILER`.
- **`<analysis>` stripping & continuation:** `formatCompactSummary()` (`services/compact/prompt.ts:311-335`) strips `<analysis>...</analysis>` and formats `<summary>...</summary>` as `Summary:\n...`. `getCompactUserSummaryMessage()` (`services/compact/prompt.ts:337-374`) adds transcript path, optional `"Recent messages are preserved verbatim."`, resume framing, and—behind `(feature('PROACTIVE') || feature('KAIROS')) && proactiveModule?.isProactiveActive()` (absent `proactive/index.js`)—autonomous-loop instructions.
- **PTL head-truncation retries (`services/compact/compact.ts:449-491`, `services/compact/compact.ts:861-899`):** Full and partial compact retry up to `MAX_PTL_RETRIES = 3` on `PROMPT_TOO_LONG_ERROR_MESSAGE`. `truncateHeadForPTLRetry()` (`services/compact/compact.ts:243-291`) strips prior `PTL_RETRY_MARKER` (avoiding retry-2+ stalls) and groups rounds via `groupMessagesByApiRound()` (`services/compact/grouping.ts:22-63`).
  - Splitting on new assistant `message.id` handles single-prompt sessions without dangling `tool_use` locks; `services/compact/grouping.ts` breaks a `compact.ts ↔ compactMessages.ts` cycle (`CC-1180`, racing `ws`; `compactMessages.ts` is absent from this snapshot, referenced only in comments at `services/compact/grouping.ts:18` and `services/compact/compact.ts:239`).
- **Pure helper vs. caller loops:** Returning `Message[] | null`, `truncateHeadForPTLRetry()` drops oldest groups covering `getPromptTooLongTokenGap()` or a `20%` fallback (clamped to `groups.length - 1`) and prepends `PTL_RETRY_MARKER` if dropping group 0 leaves an assistant-first slice. Caller loops then reassign **both** `messagesToSummarize` (`apiMessages` in partial compact) and `retryCacheSafeParams.forkContextMessages` (`services/compact/compact.ts:484-490`, `services/compact/compact.ts:894-898`).

**`compact_boundary`, `preservedSegment` & budgeted restoration (`services/compact/compact.ts:330-367`, `services/compact/compact.ts:518-624`, `services/compact/compact.ts:781-1096`).**
- `buildPostCompactMessages()` (`services/compact/compact.ts:330-338`) fixes one order across all paths: `[boundaryMarker, ...summaryMessages, ...(messagesToKeep ?? []), ...attachments, ...hookResults]`.
- `createCompactBoundaryMessage()` records `logicalParentUuid` (JSONL sets `parentUuid: null` at `utils/sessionStorage.ts:1026-1041`) and sorted `preCompactDiscoveredTools` (`services/compact/compact.ts:606-611`, `services/compact/compact.ts:1023-1028`) so deferred tool schemas survive summarization.
- `partialCompactConversation()` (`services/compact/compact.ts:772-1106`) stamps `{ headUuid, anchorUuid, tailUuid }` via `annotateBoundaryWithPreservedSegment()` (`services/compact/compact.ts:349-367`, `services/compact/compact.ts:1077-1081`, `services/compact/compact.ts:1083-1087`):
  - `'from'` keeps the prefix (`0..pivotIndex`, `services/compact/compact.ts:800`), summarizes the suffix using `allMessages` for prefix cache warmth (`services/compact/compact.ts:852-858`), and sets `anchorUuid = boundaryMarker.uuid` (`services/compact/compact.ts:1081`).
  - `'up_to'` summarizes the prefix (`messagesToSummarize`), keeps the suffix (`pivotIndex..end`, stripping stale `compact_boundary`/`isCompactSummary` entries so `findLastCompactBoundaryIndex` cannot hide the new summary, `services/compact/compact.ts:785-800`), and sets `anchorUuid = summaryMessages.at(-1)?.uuid ?? boundaryMarker.uuid` (`services/compact/compact.ts:1080`, matching SessionMemory compact at `services/compact/sessionMemoryCompact.ts:488-492`).
- On `--resume`, `applyPreservedSegmentRelinks()` (`utils/sessionStorage.ts:1839-1956`) validates `tail → head`, patches `head.parentUuid = anchorUuid` (`utils/sessionStorage.ts:1908-1911`), **splices `anchor`'s other children onto `tailUuid`** (`utils/sessionStorage.ts:1915-1919`), **zeroes stale assistant `usage`** (`utils/sessionStorage.ts:1923-1939`), and prunes non-preserved pre-boundary entries.
- Full and partial compact clear `context.readFileState` and `context.loadedNestedMemoryPaths?.clear()` (`services/compact/compact.ts:518-522`, `services/compact/compact.ts:919-921`), preserve `sentSkillNames` (~4K tok saved), and re-inject bounded context:
  - **Files (`createPostCompactFileAttachments`, `services/compact/compact.ts:1415-1464`):** Max `5` files (`POST_COMPACT_MAX_FILES_TO_RESTORE`), `5_000` tok/file (`POST_COMPACT_MAX_TOKENS_PER_FILE`), `50_000` total (`POST_COMPACT_TOKEN_BUDGET`), excluding plan/memory paths (`shouldExcludeFromPostCompactRestore`, `services/compact/compact.ts:1674-1705`) and preserved reads (`collectReadToolFilePaths`, `services/compact/compact.ts:1610-1655`).
  - **Working state & deltas (`services/compact/compact.ts:532-585`, `services/compact/compact.ts:1470-1599`):** Unretrieved `local_agent` tasks (`task_status`), `plan_file_reference`, `plan_mode` (`reminderType: 'full'`), agent-scoped `invoked_skills` head-truncated at `5_000` tok/skill (`POST_COMPACT_MAX_TOKENS_PER_SKILL`) up to `25_000` tok (`POST_COMPACT_SKILLS_TOKEN_BUDGET`), plus deferred-tool, agent-listing, and MCP-instruction deltas.
  - **Hooks, metadata & `KAIROS` (`services/compact/compact.ts:413-424`, `services/compact/compact.ts:592-594`, `services/compact/compact.ts:698-729`):** Runs `executePreCompactHooks`, `processSessionStartHooks('compact')`, and `executePostCompactHooks` (Ch 13 seam); calls `notifyCompaction` (`feature('PROMPT_CACHE_BREAK_DETECTION')`), `markPostCompaction()`, `reAppendSessionMetadata()` (16KB `--resume` tail-window scar), and—under `feature('KAIROS')`—absent `services/sessionTranscript/sessionTranscript.js`'s `writeSessionTranscriptSegment()`.

### Hidden Invariants & Failure Modes

- **Abort-as-summary guard (`services/compact/compact.ts:1205-1230`):** `query()` turns `APIUserAbortError` on `Esc` into `"Request was aborted."` (no `"API Error"` prefix). Checking `!assistantMsg.isApiErrorMessage` stops an aborted fork from becoming the summary.
- **`FILE_UNCHANGED_STUB` awareness (`services/compact/compact.ts:1606-1655`):** `collectReadToolFilePaths()` ignores preserved `Read` calls whose `tool_result` starts with `FILE_UNCHANGED_STUB` because that stub references a compacted-away read that must be re-injected.
- **Telemetry misnomer & deferral (`services/compact/compact.ts:626-642`, `services/compact/compact.ts:682-694`):** `postCompactTokenCount` logs the compact call's usage (`≈ preCompactTokenCount`) for legacy continuity while `truePostCompactTokenCount` estimates payload size; `analyzeContext(messages)` (~11ms on 4.5K-message sessions) runs after the API `await`.

---

## 5. The Zero-LLM Fast Path: SessionMemory Compaction

### The Problem

Full LLM compaction pays a summarization round-trip and replaces the active tail with prose. When Session Memory ([Chapter 10](10-memory-systems-claudemd-auto-memory-and-dream.md)) already maintains a markdown scratchpad on disk, Claude Code compacts instantaneously with zero LLM calls and keeps a verbatim tail.

### The Real Implementation

`shouldUseSessionMemoryCompaction()` (`services/compact/sessionMemoryCompact.ts:403-432`) checks `ENABLE_CLAUDE_CODE_SM_COMPACT` (wins), `DISABLE_CLAUDE_CODE_SM_COMPACT`, then GrowthBook `tengu_session_memory && tengu_sm_compact`. `USER_TYPE === 'ant'` gates `tengu_sm_compact_flag_check` (`services/compact/sessionMemoryCompact.ts:423-429`) and caught-error debug logs (`services/compact/sessionMemoryCompact.ts:625-627`). No `isSessionMemoryEnabled` exists (`services/SessionMemory/sessionMemory.ts:80` defines unexported `isSessionMemoryGateEnabled`).

When `trySessionMemoryCompaction()` (`services/compact/sessionMemoryCompact.ts:514-630`) runs from `autoCompactIfNeeded()` (`services/compact/autoCompact.ts:288-310`) or `/compact` without `customInstructions` (`commands/compact/compact.ts:57-83`):

1. **Config & sync (`services/compact/sessionMemoryCompact.ts:524-543`):** Loads `'tengu_sm_compact_config'` once (`getDynamicConfig_BLOCKS_ON_INIT`) over `DEFAULT_SM_COMPACT_CONFIG = { minTokens: 10_000, minTextBlockMessages: 5, maxTokens: 40_000 }` (`services/compact/sessionMemoryCompact.ts:47-61`, `services/compact/sessionMemoryCompact.ts:102-130`). Awaits `waitForSessionMemoryExtraction()` (15s cap / 60s stale bailout, `services/SessionMemory/sessionMemoryUtils.ts:89-105`), returning `null` if empty (`isSessionMemoryEmpty`).
2. **Watermark & tail sizing (`services/compact/sessionMemoryCompact.ts:324-397`, `services/compact/sessionMemoryCompact.ts:548-574`):** Sets `startIndex = lastSummarizedIndex + 1` (or `null` if a stored UUID is missing). On resumed sessions lacking a watermark, `lastSummarizedIndex` falls back to `messages.length - 1` (`services/compact/sessionMemoryCompact.ts:564`), so `startIndex = messages.length` (0 kept initially) before `calculateMessagesToKeepIndex()` expands backward to meet `minTokens`/`minTextBlockMessages`, floored at the last `compact_boundary`:

```ts
// services/compact/sessionMemoryCompact.ts:370-396
const idx = messages.findLastIndex(m => isCompactBoundaryMessage(m))
const floor = idx === -1 ? 0 : idx + 1
for (let i = startIndex - 1; i >= floor; i--) {
  const msg = messages[i]!
  const msgTokens = estimateMessageTokens([msg])
  totalTokens += msgTokens
  if (hasTextBlocks(msg)) {
    textBlockMessageCount++
  }
  startIndex = i

  // Stop if we hit the max cap
  if (totalTokens >= config.maxTokens) {
    break
  }

  // Stop if we meet both minimums
  if (
    totalTokens >= config.minTokens &&
    textBlockMessageCount >= config.minTextBlockMessages
  ) {
    break
  }
}

// Adjust for tool pairs
return adjustIndexToPreserveAPIInvariants(messages, startIndex)
```

3. **Two-pass invariant repair (`services/compact/sessionMemoryCompact.ts:232-314`):** Step 1 scans `[startIndex..end]` for `tool_result` IDs lacking a kept `tool_use` and expands backward (`services/compact/sessionMemoryCompact.ts:242-286`). Step 2 collects kept assistant `message.id`s and walks back to `0` to re-attach split streaming chunks (`services/compact/sessionMemoryCompact.ts:288-313`), preserving `thinking` blocks for `normalizeMessagesForAPI()`.
4. **Assembly & threshold guard (`services/compact/sessionMemoryCompact.ts:437-503`, `services/compact/sessionMemoryCompact.ts:579-620`):** Strips old `compact_boundary` markers, runs `processSessionStartHooks('compact')`, caps each `# ` section at `8_000` chars (`truncateSessionMemoryForCompact`, `services/SessionMemory/prompts.ts:256-324`), and stamps `preservedSegment`. If `postCompactTokenCount >= autoCompactThreshold` (`services/compact/sessionMemoryCompact.ts:605-614`), returns `null` (`tengu_sm_compact_threshold_exceeded`) so LLM compact runs instead.

### Hidden Invariants & Failure Modes

- **Boundary-floor & old-boundary strip (`services/compact/sessionMemoryCompact.ts:364-371`, `services/compact/sessionMemoryCompact.ts:575-581`):** Walking past a prior `compact_boundary` crosses the on-disk `preservedSegment` discontinuity and breaks `applyPreservedSegmentRelinks()`; filtering old boundaries from `messagesToKeep` stops `QueryEngine.ts:918-942` from firing a second prune that drops the new summary.
- **BQ 2026-03-01 cache-break scar (`services/compact/autoCompact.ts:293-310`):** Because `trySessionMemoryCompaction()` skips `notifyCompaction()` internally, `autoCompactIfNeeded()` must call `setLastSummarizedMessageId(undefined)`, `runPostCompactCleanup(querySource)`, `notifyCompaction` (`feature('PROMPT_CACHE_BREAK_DETECTION')`), and `markPostCompaction()` on hit—omitting `notifyCompaction` previously made **20% of `tengu_prompt_cache_break` events** false positives.

---

## 6. Post-Compact Cleanup & Manual `taskBudgetRemaining` Accounting

### The Problem

Crossing a compaction boundary exposes two system-wide hazards: (1) ten module-level caches must reset without letting an in-process subagent (`agent:*`) clobber main-thread singletons; (2) server-side `output_config.task_budget` (`beta: task-budgets-2026-03-13`, `constants/betas.ts:16`, `services/api/claude.ts:479-501`, plumbed via `QueryParams.taskBudget` at `query.ts:193-197`) counts down from visible history and forgets tokens summarized away unless `query.ts` passes `remaining`.

### The Real Implementation

**Centralized, isolated cleanup (`services/compact/postCompactCleanup.ts:31-77`).** `runPostCompactCleanup(querySource)` is called by `autoCompactIfNeeded()` (`services/compact/autoCompact.ts:297`, `services/compact/autoCompact.ts:326`), manual `/compact` (`commands/compact/compact.ts:64`, `commands/compact/compact.ts:118`, `commands/compact/compact.ts:201`), partial compact (`screens/REPL.tsx:4972`), and `/clear` (`commands/clear/caches.ts:74`)—never directly by `query.ts`. It gates main-thread stores behind `isMainThreadCompact`:

```ts
// services/compact/postCompactCleanup.ts:36-61
const isMainThreadCompact =
  querySource === undefined ||
  querySource.startsWith('repl_main_thread') ||
  querySource === 'sdk'

resetMicrocompactState()
if (feature('CONTEXT_COLLAPSE')) {
  if (isMainThreadCompact) {
    /* eslint-disable @typescript-eslint/no-require-imports */
    ;(
      require('../contextCollapse/index.js') as typeof import('../contextCollapse/index.js')
    ).resetContextCollapse()
    /* eslint-enable @typescript-eslint/no-require-imports */
  }
}
if (isMainThreadCompact) {
  // getUserContext is a memoized outer layer wrapping getClaudeMds() →
  // getMemoryFiles(). If only the inner getMemoryFiles cache is cleared,
  // the next turn hits the getUserContext cache and never reaches
  // getMemoryFiles(), so the armed InstructionsLoaded hook never fires.
  // Manual /compact already clears this explicitly at its call sites;
  // auto-compact and reactive-compact did not — this centralizes the
  // clear so all compaction paths behave consistently.
  getUserContext.cache.clear?.()
  resetGetMemoryFilesCache('compact')
}
```

Unconditional steps then clear system-prompt sections (`constants/systemPromptSections.ts:65`), classifier approvals (`utils/classifierApprovals.ts:84`), speculative bash checks (`tools/BashTool/bashPermissions.ts:1543`), beta tracing (`utils/telemetry/betaSessionTracing.ts:65`), commit-attribution caches behind `feature('COMMIT_ATTRIBUTION')` (absent `utils/attributionHooks.js`'s `sweepFileContentCache()`), and the session-messages cache (`utils/sessionStorage.ts:3854`).

**Manual `taskBudgetRemaining` subtraction (`query.ts:282-291`, `utils/tokens.ts:79-112`).** `queryLoop()` keeps `taskBudgetRemaining` loop-local (`undefined` initially, avoiding all seven `continue` sites on `State`) and omits `remaining` before the first compact (`query.ts:699-706`) so the server runs its native countdown. Immediately *before* swapping `messagesForQuery` on **both** proactive (`query.ts:504-515`) and reactive (`query.ts:1138-1146`) paths, `queryLoop()` subtracts the pre-compact window:

```ts
// query.ts:504-515
// task_budget: capture pre-compact final context window before
// messagesForQuery is replaced with postCompactMessages below.
// iterations[-1] is the authoritative final window (post server tool
// loops); see #304930.
if (params.taskBudget) {
  const preCompactContext =
    finalContextTokensFromLastResponse(messagesForQuery)
  taskBudgetRemaining = Math.max(
    0,
    (taskBudgetRemaining ?? params.taskBudget.total) - preCompactContext,
  )
}
```

`finalContextTokensFromLastResponse()` (`utils/tokens.ts:79-112`) reads `usage.iterations.at(-1)` (`last.input_tokens + last.output_tokens`), falling back to `usage.input_tokens + usage.output_tokens` when absent. Server tool loops inflate cumulative billing tokens across iterations, whereas `iterations[-1]` is the authoritative window erased (excluding cache tokens per `#304930`; `utils/tokens.ts:103-106` notes a fallback parity question). Repeated compactions decrement cumulatively, clamping at `0`.

### Hidden Invariants & Failure Modes

- **Two-layer `CLAUDE.md` cache masking (`services/compact/postCompactCleanup.ts:51-61`):** Clearing only `resetGetMemoryFilesCache('compact')` leaves memoized `getUserContext` (`context.ts:155`) hot so `getMemoryFiles()` never runs and `InstructionsLoaded` never fires.
- **Intentional non-clears & `/clear` override (`services/compact/postCompactCleanup.ts:17-20`, `services/compact/postCompactCleanup.ts:65-69`, `commands/clear/caches.ts:74-84`):** Invoked skills survive repeated compactions, and `resetSentSkillNames()` is skipped (~4K tok `cache_creation` saved). `/clear` runs `runPostCompactCleanup()`, then calls `resetSentSkillNames()` and `resetGetMemoryFilesCache('session_start')`.
- **Context-scoped vs. global state:** `toolUseContext.loadedNestedMemoryPaths` (`Tool.ts:222`) is per-context, so it clears in `services/compact/compact.ts:522` and `services/compact/compact.ts:921` rather than `services/compact/postCompactCleanup.ts`.

> [!IMPORTANT]
> **Two invariants tie Layer 3 together:** (1) `taskBudgetRemaining` subtraction MUST run *before* `messagesForQuery = postCompactMessages` on proactive (`query.ts:508-515`) and reactive (`query.ts:1138-1146`) paths while pre-compact `usage` is readable; (2) `isMainThreadCompact` (`services/compact/postCompactCleanup.ts:36-39`) MUST gate `resetContextCollapse()`, `getUserContext.cache.clear()`, and `resetGetMemoryFilesCache('compact')` so subagents never corrupt main-thread state.

---

## Putting the Layer Together

```text
queryLoop() pre-API cascade & post-API overflow recovery (query.ts)
  │
  ▼ Stage 0: getMessagesAfterCompactBoundary()      [query.ts:365]
  │          (HISTORY_SNIP -> snipProjection [absent])
  ▼ Stage 1: applyToolResultBudget()                [query.ts:379-394]
  ▼ Stage 2: snipCompactIfNeeded() [absent]         [query.ts:401-410]
  │          └── captures snipTokensFreed ───────────────────────┐
  ▼ Stage 3: deps.microcompact()                    [query.ts:414-425]
  │          ├─ cold (>60m): timeBasedMC (tengu_slate_heron)     │
  │          └─ warm: CACHED_MICROCOMPACT [absent] -> edits      │
  ▼ Stage 4: applyCollapsesIfNeeded() [absent]      [query.ts:440-447]
  ▼ Stage 5: deps.autocompact(..., snipTokensFreed) [query.ts:454-543] ◄─┘
  │          ├─ hit: taskBudgetRemaining -= preCompactContext
  │          │       yield buildPostCompactMessages() + swap view
  │          └─ fail: propagate consecutiveFailures (trips at 3)
  ▼ Blocking Limit Guard (skipped if collapse/reactive owns 413)
  ▼ deps.callModel() (+ taskBudget.remaining if defined)
  │          ├─ wire: apiMicrocompact beta [services/api/claude.ts:1633-1637]
  │          ├─ CACHED_MICROCOMPACT: deferred microcompact_boundary
  │          └─ withheld 413 / media error?
  │             ├─ 1. contextCollapse.recoverFromOverflow() [absent]
  │             │     -> collapse_drain_retry (single-shot)
  │             └─ 2. reactiveCompact.tryReactiveCompact() [absent]
  │                   -> taskBudgetRemaining -= preCompactContext
  │                   -> reactive_compact_retry | exit (no stop hooks)
```

```mermaid
flowchart TD
  Entry["autoCompactIfNeeded()"] --> Breaker{"DISABLE_COMPACT or consecutiveFailures >= 3?"}
  Breaker -->|"yes"| Skip["Return wasCompacted: false"]
  Breaker -->|"no"| Gate["shouldAutoCompact() (recursion, collapse, reactive, snip-adjusted)"]
  Gate -->|"false"| Skip
  Gate -->|"true"| SM{"trySessionMemoryCompaction()"}
  SM -->|"non-null"| SMPost["Clear watermark + notifyCompaction() + markPostCompaction()"]
  SM -->|"null fallback"| LLM["compactConversation() (cache fork -> streaming fallback + PTL retry)"]
  LLM -->|"throws"| Inc["Increment consecutiveFailures (trips breaker at 3)"]
  LLM -->|"succeeds"| LLMPost["Clear watermark + consecutiveFailures: 0"]
  SMPost --> ResetMC["runPostCompactCleanup(): step 1 resetMicrocompactState()"]
  LLMPost --> ResetMC
  ResetMC --> Cleanup{"isMainThreadCompact?"}
  Cleanup -->|"true (REPL / SDK)"| Global["Steps 2-4: resetContextCollapse + getUserContext.cache + resetGetMemoryFilesCache('compact')"]
  Global --> Rest["Steps 5-10 (always): sections, approvals, speculative, tracing, attribution, session cache"]
  Cleanup -->|"false (subagent)"| Rest
  Rest --> Build["query.ts: subtract taskBudgetRemaining, reset consecutiveFailures: 0, buildPostCompactMessages() -> yield & swap"]
  Build --> Persist["QueryEngine / REPL -> utils/sessionStorage.ts: compact_boundary + preservedSegment"]
```

---

## How This Snaps Into the Next Layer

Every compression path here depends on—and resets—the memory subsystems dissected in [Chapter 10](10-memory-systems-claudemd-auto-memory-and-dream.md):

1. **Session Memory (`services/SessionMemory/`):** `trySessionMemoryCompaction()` (`services/compact/sessionMemoryCompact.ts:514-630`) consumes the scratchpad built by `services/SessionMemory/sessionMemory.ts` (`extractSessionMemory`, `updateLastSummarizedMessageIdIfSafe`), syncs via `services/SessionMemory/sessionMemoryUtils.ts` (`waitForSessionMemoryExtraction`, `getSessionMemoryContent`, `getLastSummarizedMessageId`), and truncates sections via `services/SessionMemory/prompts.ts` (`isSessionMemoryEmpty`, `truncateSessionMemoryForCompact`).
2. **Eager `CLAUDE.md` reload (`utils/claudemd.ts`):** `services/compact/postCompactCleanup.ts:59-60` clears `getUserContext.cache` and calls `resetGetMemoryFilesCache('compact')` (`utils/claudemd.ts:1124-1130`) so Chapter 10 reloads instruction files and fires `InstructionsLoaded` with `load_reason: 'compact'`.
3. **Nested memory re-injection (`utils/attachments.ts`):** `services/compact/compact.ts:522` and `services/compact/compact.ts:921` clear `context.loadedNestedMemoryPaths` (read at `utils/attachments.ts:1719-1732`) so subdirectory `CLAUDE.md` files re-inject post-compact.
4. **Forward seams beyond Layer 3:** Compaction hooks (`executePreCompactHooks`, `processSessionStartHooks('compact')`, `executePostCompactHooks`) connect to **Chapter 13 (The Hook System)**; the cache-sharing fork (`runForkedAgent`, `CacheSafeParams` in `utils/forkedAgent.ts`) connects to **Chapter 18 (Subagents & Forked Agents)**.

---

## Reading Exercises & Code Checkpoints

1. **Trace all five pre-API stages, reactive overflow recovery, and all four snapshot-absent modules:**
   ```sh
   rg -n "applyToolResultBudget|snipCompact|deps\.microcompact|cachedMicrocompact|contextCollapse/index|applyCollapsesIfNeeded|deps\.autocompact|recoverFromOverflow|reactiveCompact\.js|tryReactiveCompact" query.ts services/compact/microCompact.ts
   ```
   Verify order in `query.ts:379-468` and compare the four `feature(...)` imports (`snipCompact.js`, `cachedMicrocompact.js`, `contextCollapse/index.js`, `reactiveCompact.js`) against overflow handlers at `query.ts:1085-1183`. Why does `contextCollapse` run *before* `deps.autocompact` and drain *before* `tryReactiveCompact`?
2. **Audit threshold math and the `MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES` circuit breaker:**
   ```sh
   rg -n "MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES|AUTOCOMPACT_BUFFER_TOKENS|MAX_OUTPUT_TOKENS_FOR_SUMMARY|consecutiveFailures" services/compact/autoCompact.ts query.ts
   ```
   Trace `consecutiveFailures` incrementing on failed `compactConversation()` (`services/compact/autoCompact.ts:341-349`), propagating at `query.ts:536-543`, tripping at `3` (`services/compact/autoCompact.ts:260-265`), and resetting to `0` (`services/compact/autoCompact.ts:332`, `query.ts:525`). Why does `trySessionMemoryCompaction()` returning `null` *not* increment it?
3. **Follow `taskBudgetRemaining` subtraction across both compaction paths:**
   ```sh
   rg -n "taskBudgetRemaining|finalContextTokensFromLastResponse" query.ts utils/tokens.ts
   ```
   Inspect `query.ts:282-291`, `query.ts:508-515`, `query.ts:699-706`, `query.ts:1138-1146`, and `utils/tokens.ts:68-112`. Why does `taskBudgetRemaining` stay `undefined` before the first compact, why must subtraction precede swapping `messagesForQuery`, and why read `usage.iterations[-1]` over `tokenCountFromLastAPIResponse()`?
4. **Verify subagent cleanup isolation (`isMainThreadCompact`) and Chapter 09 → Chapter 10 seams:**
   ```sh
   rg -n "isMainThreadCompact|runPostCompactCleanup|trySessionMemoryCompaction|resetGetMemoryFilesCache|loadedNestedMemoryPaths" services/compact/postCompactCleanup.ts services/compact/sessionMemoryCompact.ts services/compact/autoCompact.ts services/compact/compact.ts utils/claudemd.ts utils/attachments.ts
   ```
   Check which three actions in `services/compact/postCompactCleanup.ts:36-61` are skipped for subagents (`agent:*`), why `getUserContext.cache.clear?.()` accompanies `resetGetMemoryFilesCache('compact')`, and why `loadedNestedMemoryPaths?.clear()` lives in `services/compact/compact.ts` rather than `services/compact/postCompactCleanup.ts`.


---

<!-- chapters/10-memory-systems-claudemd-auto-memory-and-dream.md — https://reverseengineeringclaudecode.com/chapters/10-memory-systems-claudemd-auto-memory-and-dream -->

# Chapter 10 — Memory Systems: `CLAUDE.md`, Auto-Memory, Session Memory, and Auto-Dream

> **Layer:** Layer 3 (Long-Horizon Context & Memory)
> **Prerequisites:** [Chapter 01](01-atoms-types-stores-and-primitives.md), [Chapter 02](02-the-tool-contract.md), [Chapter 04](04-prompt-engineering-and-cache-boundaries.md), [Chapter 07](07-the-heartbeat-query-loop.md), [Chapter 08](08-session-envelope-query-engine-and-transcripts.md), [Chapter 09](09-five-layer-compaction-pipeline.md)
> **Primary Source Files:**
> - [`utils/claudemd.ts`](../../utils/claudemd.ts) — `CLAUDE.md` discovery, HTML stripping, `@include`, `.claude/rules/`, caches (1,479 lines)
> - [`utils/attachments.ts`](../../utils/attachments.ts), [`query.ts`](../../query.ts), [`bootstrap/state.ts`](../../bootstrap/state.ts) — nested memory injection, `loadedNestedMemoryPaths`, `using`-scoped `startRelevantMemoryPrefetch()`, and `cachedClaudeMdContent`
> - [`memdir/memdir.ts`](../../memdir/memdir.ts), [`memdir/memoryTypes.ts`](../../memdir/memoryTypes.ts), [`memdir/memoryScan.ts`](../../memdir/memoryScan.ts), [`memdir/findRelevantMemories.ts`](../../memdir/findRelevantMemories.ts) — `MEMORY.md` truncation, 4-type taxonomy, frontmatter scan, and Sonnet relevance selector
> - [`memdir/paths.ts`](../../memdir/paths.ts), [`memdir/memoryAge.ts`](../../memdir/memoryAge.ts), [`memdir/teamMemPaths.ts`](../../memdir/teamMemPaths.ts), [`memdir/teamMemPrompts.ts`](../../memdir/teamMemPrompts.ts) — enablement & path trust, staleness caveats, symlink containment, and team prompts
> - [`services/SessionMemory/sessionMemory.ts`](../../services/SessionMemory/sessionMemory.ts), [`services/SessionMemory/sessionMemoryUtils.ts`](../../services/SessionMemory/sessionMemoryUtils.ts), [`services/SessionMemory/prompts.ts`](../../services/SessionMemory/prompts.ts) — post-sampling scratchpad feeding [Chapter 09](09-five-layer-compaction-pipeline.md)
> - [`services/extractMemories/`](../../services/extractMemories/): [`services/extractMemories/extractMemories.ts`](../../services/extractMemories/extractMemories.ts), [`services/extractMemories/prompts.ts`](../../services/extractMemories/prompts.ts) — turn-end topic extraction, coalescing, and `createAutoMemCanUseTool()`
> - [`services/autoDream/autoDream.ts`](../../services/autoDream/autoDream.ts), [`services/autoDream/config.ts`](../../services/autoDream/config.ts), [`services/autoDream/consolidationLock.ts`](../../services/autoDream/consolidationLock.ts), [`services/autoDream/consolidationPrompt.ts`](../../services/autoDream/consolidationPrompt.ts) — 3-gate consolidation, PID+mtime lock, and leaf config
> - [`services/teamMemorySync/`](../../services/teamMemorySync/): [`services/teamMemorySync/index.ts`](../../services/teamMemorySync/index.ts), [`services/teamMemorySync/secretScanner.ts`](../../services/teamMemorySync/secretScanner.ts), [`services/teamMemorySync/teamMemSecretGuard.ts`](../../services/teamMemorySync/teamMemSecretGuard.ts), [`services/teamMemorySync/types.ts`](../../services/teamMemorySync/types.ts), [`services/teamMemorySync/watcher.ts`](../../services/teamMemorySync/watcher.ts) — OAuth delta sync, gitleaks scanning, and circuit-broken watcher
> - [`utils/forkedAgent.ts`](../../utils/forkedAgent.ts) (Ch 18 seam) and [`tasks/DreamTask/DreamTask.ts`](../../tasks/DreamTask/DreamTask.ts) (Ch 17 seam)
> - *(Snapshot absences — call sites only, never linked: `memdir/memoryShapeTelemetry.js`, `types/message.js`, `constants/querySource.js`)*

---

## Why This Layer Exists

[Chapter 09](09-five-layer-compaction-pipeline.md) showed how Claude Code forgets turns to fit a finite window. Memory solves the symmetric problem across five horizons: `CLAUDE.md`/`.claude/rules/`, persistent `memdir/` with optional relevance prefetch, live `SessionMemory` (`summary.md`), turn-end `extractMemories` plus `autoDream` consolidation, and OAuth `teamMemorySync`.

Every tier upholds three invariants: preserve the prompt cache ([Chapter 04](04-prompt-engineering-and-cache-boundaries.md)), keep latency off the critical path, and prevent arbitrary writes or credential leaks.

---

## 1. Hierarchical `CLAUDE.md`, Conditional Rules, and Nested Injection (`utils/claudemd.ts`, `utils/attachments.ts`)

### The Problem

[Chapter 04](04-prompt-engineering-and-cache-boundaries.md) covered `getUserContext()` (`context.ts:155-189`), honoring `CLAUDE_CODE_DISABLE_CLAUDE_MDS` and `--bare` before `getMemoryFiles()` → `filterInjectedMemoryFiles()` → `getClaudeMds()`. Beneath it sit six challenges: priority scopes, nested worktrees, HTML comments, recursive `@include`s, path-scoped rules, and [Chapter 01](01-atoms-types-stores-and-primitives.md)'s 100-entry LRU `FileStateCache` evicting injected `CLAUDE.md` files.

### The Mechanism: Reverse-Priority Walk, Single-Pass Lexing, and 4-Phase Nested Injection

`getMemoryFiles()` (`utils/claudemd.ts:790-1075`) memoizes an async walker loading scopes in **reverse priority** so local rules sit closest to model attention (docblock at `utils/claudemd.ts:9-10`):

1. **Managed (`utils/claudemd.ts:804-823`):** Always loaded (ungated by `isSettingSourceEnabled`). Reads platform `<managedDir>/CLAUDE.md` (`utils/settings/managedPath.ts:8-25`) and unconditional `.claude/rules/*.md`.
2. **User (`utils/claudemd.ts:826-847`):** Gated on `userSettings`. Loads `~/.claude/CLAUDE.md` and unconditional `~/.claude/rules/*.md` (`conditionalRule: false`, `utils/claudemd.ts:844`) with `includeExternal = true` (trusted outside `originalCwd`).
3. **Root-to-CWD Project & Local (`utils/claudemd.ts:850-934`):** Walks upward from `getOriginalCwd()` stopping before root (`!== parse(currentDir).root`), reverses root → CWD, and loads `CLAUDE.md`, `.claude/CLAUDE.md`, unconditional `.claude/rules/*.md` (`projectSettings`), and `CLAUDE.local.md` (`localSettings`).
4. **Opt-in `--add-dir` (`utils/claudemd.ts:940-977`):** Gated on `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD`; bypasses `projectSettings` (explicit user intent; SDK defaults `settingSources` to `[]`).
5. **`AutoMem` & `TeamMem` entrypoints (`utils/claudemd.ts:980-1007`):** When `isAutoMemoryEnabled()` (and under `feature('TEAMMEM')`, `isTeamMemoryEnabled()`), reads `MEMORY.md` and `team/MEMORY.md` via direct `safelyReadMemoryFileAsync()`—skipping `@include` and `claudeMdExcludes`.

Dedup never inspects `stat.ino`. `processMemoryFile()` (`utils/claudemd.ts:618-685`) tracks `processedPaths: Set<string>` via `normalizePathForComparison()` (`utils/file.ts:565-577`) plus `safeResolvePath()`'s symlink target (`utils/fsOperations.ts:138-178`, blocking UNC paths and FIFOs/sockets before `realpathSync`). `processMdRules()` (`utils/claudemd.ts:697-788`) adds `visitedDirs` to break directory-symlink cycles.

`parseMemoryFileContent()` (`utils/claudemd.ts:343-400`) rejects binary files outside `TEXT_FILE_EXTENSIONS` (`utils/claudemd.ts:96-227`) and parses YAML `paths:` via `parseFrontmatterPaths()` (`utils/claudemd.ts:254-279`, using `quoteProblematicValues()` at `utils/frontmatterParser.ts:85-121` and brace-aware `splitPathInFrontmatter()` at `utils/frontmatterParser.ts:189-232`). It lexes once for `stripHtmlCommentsFromTokens()` (`utils/claudemd.ts:303-334`) and `extractIncludePathsFromTokens()` (`utils/claudemd.ts:451-535`):

```ts
// utils/claudemd.ts:356-388
const { content: withoutFrontmatter, paths } =
  parseFrontmatterPaths(rawContent)

// Lex once so strip and @include-extract share the same tokens. gfm:false
// is required by extract (so ~/path doesn't tokenize as strikethrough) and
// doesn't affect strip (html blocks are a CommonMark rule).
const hasComment = withoutFrontmatter.includes('<!--')
const tokens =
  hasComment || includeBasePath !== undefined
    ? new Lexer({ gfm: false }).lex(withoutFrontmatter)
    : undefined

// Only rebuild via tokens when a comment actually needs stripping —
// marked normalises \r\n during lex, so round-tripping a CRLF file
// through token.raw would spuriously flip contentDiffersFromDisk.
const strippedContent =
  hasComment && tokens
    ? stripHtmlCommentsFromTokens(tokens).content
    : withoutFrontmatter

const includePaths =
  tokens && includeBasePath !== undefined
    ? extractIncludePathsFromTokens(tokens, includeBasePath)
    : []

// Truncate MEMORY.md entrypoints to the line AND byte caps
let finalContent = strippedContent
if (type === 'AutoMem' || type === 'TeamMem') {
  finalContent = truncateEntrypointContent(strippedContent).content
}

// Covers frontmatter strip, HTML comment strip, and MEMORY.md truncation
const contentDiffersFromDisk = finalContent !== rawContent
```

`stripHtmlCommentsFromTokens()` strips closed block `html` tokens (`<!--`..`-->`), preserving code blocks, inline comments, unclosed typos, and trailing type-2 text. `@include` caps depth at `MAX_INCLUDE_DEPTH = 5` (`utils/claudemd.ts:537`) and flags non-`User` includes outside CWD via `getExternalClaudeMdIncludes()` (`utils/claudemd.ts:1404-1414`). Three filters shape injection:

- **`isClaudeMdExcluded()` (`utils/claudemd.ts:547-612`):** Matches `settings.claudeMdExcludes` via `picomatch` on `User`/`Project`/`Local` only, resolving prefixes through `realpathSync` (`resolveExcludePatterns()`) for macOS `/tmp`.
- **`filterInjectedMemoryFiles()` (`utils/claudemd.ts:1142-1151`):** Strips `AutoMem`/`TeamMem` under GrowthBook `tengu_moth_copse`.
- **`getClaudeMds()` (`utils/claudemd.ts:1153-1195`):** Omits `Project`/`Local` under GrowthBook `tengu_paper_halyard`, wraps `TeamMem` in `<team-memory-content source="shared">` (`feature('TEAMMEM')`), and leaves `CLAUDE.md` untruncated (`MAX_MEMORY_CHARACTER_COUNT = 40000` at `utils/claudemd.ts:92`, `getLargeMemoryFiles()` at `utils/claudemd.ts:1132-1134` advisory).

For lazy discovery, `FileReadTool` appends read paths to `nestedMemoryAttachmentTriggers` (`tools/FileReadTool/FileReadTool.ts:848`, `tools/FileReadTool/FileReadTool.ts:870`, `tools/FileReadTool/FileReadTool.ts:1038`). `getAttachments()` awaits `@`-mentions first (`utils/attachments.ts:819`) before draining triggers (`utils/attachments.ts:872`, skipped under `CLAUDE_CODE_DISABLE_ATTACHMENTS`/`CLAUDE_CODE_SIMPLE`, `utils/attachments.ts:753-754`), and `getOpenedFileFromIDE()` calls discovery directly (`utils/attachments.ts:1878`).

`getNestedMemoryAttachmentsForFile()` (`utils/attachments.ts:1792-1862`) checks `pathInAllowedWorkingPath()`, then runs four phases: (1) Managed/User conditional rules (`utils/claudemd.ts:1205-1238`), (2) `getDirectoriesToProcess()` (`utils/attachments.ts:1656-1689`: `nestedDirs` CWD→target, `cwdLevelDirs` root→CWD). Phases (3) nested dirs (`utils/claudemd.ts:1249-1318`) and (4) ancestor rules (`utils/claudemd.ts:1329-1397`, `ignore()`) both honor GrowthBook `tengu_paper_halyard` (`utils/attachments.ts:1823-1826`, `utils/attachments.ts:1834`, `utils/attachments.ts:1851`).

`memoryFilesToAttachments()` (`utils/attachments.ts:1710-1775`) decouples session-wide deduplication from edit-safety caching:

```ts
// utils/attachments.ts:1718-1750
for (const memoryFile of memoryFiles) {
  // Dedup: loadedNestedMemoryPaths is a non-evicting Set; readFileState
  // is a 100-entry LRU that drops entries in busy sessions, so relying
  // on it alone re-injects the same CLAUDE.md on every eviction cycle.
  if (toolUseContext.loadedNestedMemoryPaths?.has(memoryFile.path)) {
    continue
  }
  if (!toolUseContext.readFileState.has(memoryFile.path)) {
    attachments.push({
      type: 'nested_memory',
      path: memoryFile.path,
      content: memoryFile,
      displayPath: relative(getCwd(), memoryFile.path),
    })
    toolUseContext.loadedNestedMemoryPaths?.add(memoryFile.path)

    // Mark as loaded in readFileState — this provides cross-function and
    // cross-turn dedup via the .has() check above.
    //
    // When the injected content doesn't match disk (stripped HTML comments,
    // stripped frontmatter, truncated MEMORY.md), cache the RAW disk bytes
    // with `isPartialView: true`. Edit/Write see the flag and require a real
    // Read first; getChangedFiles sees real content + undefined offset/limit
    // so mid-session change detection still works.
    toolUseContext.readFileState.set(memoryFile.path, {
      content: memoryFile.contentDiffersFromDisk
        ? (memoryFile.rawContent ?? memoryFile.content)
        : memoryFile.content,
      timestamp: Date.now(),
      offset: undefined,
      limit: undefined,
      isPartialView: memoryFile.contentDiffersFromDisk,
    })
```

### Hidden Invariants & Production Scars

- **Non-evicting `Set` vs. 100-entry LRU:** `FileStateCache` caps at `100` entries / `25 MB` (`utils/fileStateCache.ts:18-22`). Storing paths in `loadedNestedMemoryPaths` (`Tool.ts:222`, owned by `QueryEngine.ts:198` and `screens/REPL.tsx:1967`) stops eviction re-injection; compaction (`services/compact/compact.ts:522`, `services/compact/compact.ts:921`) and `/clear` (`commands/clear/conversation.ts:132`) clear it.
- **Silent vs. hook-arming cache resets:** Worktrees, settings sync, and `/memory` call silent `clearMemoryFileCaches()` (`utils/claudemd.ts:1119-1122`). Reloads call `resetGetMemoryFilesCache('compact')` (`utils/claudemd.ts:1124-1130`), arming `shouldFireHook = true` alongside `getUserContext.cache.clear?.()` in [Chapter 09](09-five-layer-compaction-pipeline.md)'s `services/compact/postCompactCleanup.ts:59-60`.
- **Nested git worktree dedup (`#29599`, `utils/claudemd.ts:859-934`):** Inside `.claude/worktrees/<name>/`, `skipProject` skips checked-in `Project` files above the worktree while keeping gitignored `CLAUDE.local.md` from main.
- **`unconditionalProcessedPaths` clone scar (`utils/claudemd.ts:1288-1315`):** `processMdRules()` marks every visited `.md` in `processedPaths` before filtering `conditionalRule`; cloning `processedPaths` for the unconditional pass avoids silencing sibling conditional rules.
- **Stale docblock ordering scar (`utils/claudemd.ts:23`, `utils/claudemd.ts:616` vs. `utils/claudemd.ts:663-682`):** Both docblocks claim `@include`d children precede their parent, yet code pushes the parent first (`result.push(memoryFile)`) and appends children after.

---

## 2. Persistent Auto-Memory & Team Memory Layout (`memdir/`)

### The Problem

Writable cross-session memory raises four hazards: hostile repos redirecting writes to `~/.ssh`, unbounded `MEMORY.md` indexes bloating turn-1 context, models saving derivable code or stale `file:line` claims, and symlink traversal in shared team memory.

### The Mechanism: Path Trust, Dual Caps, 4-Type Taxonomy, and Two-Pass Containment

[`memdir/paths.ts`](../../memdir/paths.ts) resolves enablement via 5-level `isAutoMemoryEnabled()` (`memdir/paths.ts:30-55`): (1) tri-state `CLAUDE_CODE_DISABLE_AUTO_MEMORY` (truthy off, defined-falsy forces on); (2) `CLAUDE_CODE_SIMPLE` (`--bare` off); (3) `CLAUDE_CODE_REMOTE` off unless `CLAUDE_CODE_REMOTE_MEMORY_DIR` is set; (4) `settings.autoMemoryEnabled`; (5) default `true`.

`getAutoMemPath()` (`memdir/paths.ts:223-235`) memoizes per `getProjectRoot()` (skipping four `parseSettingsFile` calls per render) and shares one dir across worktrees via `findCanonicalGitRoot()` (`memdir/paths.ts:203-205`, `#24382`). `getAutoMemPathSetting()` (`memdir/paths.ts:179-186`) reads `autoMemoryDirectory` from policy, flag, local, and user settings—**excluding `projectSettings`**. `validateMemoryPath()` (`memdir/paths.ts:109-150`) rejects relative paths, bare `~`/`~/`, drive roots, UNC prefixes, and null bytes.

> [!WARNING]
> **Path Trust Boundary (Ch 10 → Ch 11):** Because `~/.claude/` sits inside `DANGEROUS_DIRECTORIES`, `utils/permissions/filesystem.ts:1572-1581` grants a silent pre-safety write carve-out when `!hasAutoMemPathOverride() && isAutoMemPath(normalizedPath)`. Excluding `projectSettings` blocks hostile repos from redirecting writes to `~/.ssh`; `CLAUDE_COWORK_MEMORY_PATH_OVERRIDE` (`memdir/paths.ts:161-166`) sets `hasAutoMemPathOverride()` (`memdir/paths.ts:194-196`) `true`, withholding silent writes from SDK mounts.

Both `utils/claudemd.ts:384` and subagent `buildMemoryPrompt()` (`memdir/memdir.ts:272-316`) bound `MEMORY.md` via `truncateEntrypointContent()` (`memdir/memdir.ts:57-103`) at `MAX_ENTRYPOINT_LINES = 200` and `MAX_ENTRYPOINT_BYTES = 25_000` (`memdir/memdir.ts:35-38`). It checks `wasByteTruncated` on original `trimmed.length` (UTF-16 units, unlike `services/teamMemorySync/index.ts:435`'s `Buffer.byteLength`) and slices at `lastIndexOf('\n', MAX_ENTRYPOINT_BYTES)` so links never split mid-line.

`loadMemoryPrompt()` (`memdir/memdir.ts:419-507`) feeds [Chapter 04](04-prompt-engineering-and-cache-boundaries.md)'s `systemPromptSection('memory', ...)` (`constants/prompts.ts:495`). In Team and Individual modes (not `KAIROS`), it calls `ensureMemoryDirExists()` (`memdir/memdir.ts:129-147`) so `DIR_EXISTS_GUIDANCE` / `DIRS_EXIST_GUIDANCE` (`memdir/memdir.ts:116-119`) avoids `ls`/`mkdir -p` turns, threading `CLAUDE_COWORK_MEMORY_EXTRA_GUIDELINES` (`memdir/memdir.ts:441-446`) into both builders. Mode precedence:

1. **`feature('KAIROS') && autoEnabled && getKairosActive()` (`memdir/memdir.ts:432-438`):** `buildAssistantDailyLogPrompt()` (`memdir/memdir.ts:327-370`) overrides team memory, skips `ensureMemoryDirExists()` (instructing first-write creation at `memdir/memdir.ts:348`), and emits literal `<autoMemPath>/logs/YYYY/MM/YYYY-MM-DD.md` to survive midnight rollover.
2. **`feature('TEAMMEM') && isTeamMemoryEnabled()` (`memdir/memdir.ts:448-473`):** Requires auto-memory + GrowthBook `tengu_herring_clock` (`memdir/teamMemPaths.ts:73-78`), calls `ensureMemoryDirExists(teamDir)` (`memdir/memdir.ts:459`, creating `autoDir` via recursive `mkdir`), and returns `buildCombinedMemoryPrompt()` (`memdir/teamMemPrompts.ts:22-100`).
3. **Individual auto-memory (`memdir/memdir.ts:475-490`):** Calls `ensureMemoryDirExists(autoDir)` (`memdir/memdir.ts:479`) and returns `buildMemoryLines()` (`memdir/memdir.ts:199-266`).

All three builders append GrowthBook `tengu_coral_fern` search guidance via `buildSearchingPastContextSection()` (`memdir/memdir.ts:375-407`, called at `memdir/memdir.ts:366`, `memdir/teamMemPrompts.ts:96`, `memdir/memdir.ts:263`).

[`memdir/memoryTypes.ts`](../../memdir/memoryTypes.ts) defines the closed 4-type taxonomy (`'user' | 'feedback' | 'project' | 'reference'`, `memdir/memoryTypes.ts:14-21`) and `WHAT_NOT_TO_SAVE_SECTION` (`memdir/memoryTypes.ts:183-195`).

[`memdir/memoryAge.ts`](../../memdir/memoryAge.ts) formats `"today"`/`"yesterday"`/`"N days ago"` via `memoryAge()` (`memdir/memoryAge.ts:15-20`); `memoryFreshnessText()` (`memdir/memoryAge.ts:33-42`) emits `"This memory is N days old..."` caveats for files `> 1` day old, wrapped in `<system-reminder>` by `memoryFreshnessNote()` (`memdir/memoryAge.ts:49-53`, `tools/FileReadTool/FileReadTool.ts:747-753`).

For `<autoMemPath>/team/`, [`memdir/teamMemPaths.ts`](../../memdir/teamMemPaths.ts) enforces PSR M22186/M22187 via `sanitizePathKey()` (`memdir/teamMemPaths.ts:22-64`), blocking null bytes, URL-encoded traversals, NFKC fullwidth `．．／`, backslashes, and leading `/`. `validateTeamMemWritePath()` (`memdir/teamMemPaths.ts:228-256`) and `validateTeamMemKey()` (`memdir/teamMemPaths.ts:265-284`) pair trailing-sep containment with `realpathDeepestExisting()` (`memdir/teamMemPaths.ts:109-171`), trapping dangling symlinks, `ELOOP`, and `EACCES`/`EIO`.

### Hidden Invariants & Production Scars

- **197 KB `MEMORY.md` p100 scar (`memdir/memdir.ts:36-38`):** Long single-line paragraphs hit 197 KB under 200 lines, forcing the dual cap and original-length check.
- **Eval-validated wording (`memdir/memoryTypes.ts:192-194`, `memdir/memoryTypes.ts:204-222`, `memdir/memoryTypes.ts:224-256`):** Tightening save exclusions jumped 0/2 → 3/3; `#22856` added the ignore-memory rule (`memdir/memoryTypes.ts:220`); renaming `"Trusting what you recall"` to `"## Before recommending from memory"` (same body) jumped 0/3 → 3/3 (0/3 gap on slash commands like `/fork`).

---

## 3. Latency-Hidden Relevant Memory Prefetch with `using` (`memdir/memoryScan.ts`, `memdir/findRelevantMemories.ts`, `utils/attachments.ts`, `query.ts`)

### The Problem

Eager `MEMORY.md` injection crowds context as topic files grow, yet synchronous relevance selection adds ~500–1,500 ms to time-to-first-token.

### The Mechanism: Four-Subsystem `tengu_moth_copse` Switch & Disposable Zero-Wait Prefetch

One GrowthBook flag, `tengu_moth_copse` (default `false`), switches four subsystems: `filterInjectedMemoryFiles()` (`utils/claudemd.ts:1142-1151`) strips `AutoMem`/`TeamMem` `MEMORY.md`, both `memdir/memdir.ts:422-425` (inside `loadMemoryPrompt()`) and `services/extractMemories/extractMemories.ts:366-369` set `skipIndex = true`, and `startRelevantMemoryPrefetch()` (`utils/attachments.ts:2361-2424`) activates in `queryLoop`.

`findRelevantMemories()` (`memdir/findRelevantMemories.ts:39-75`) calls `scanMemoryFiles()` (`memdir/memoryScan.ts:35-77`, split for circular import `#25372`), scanning up to `200` newest `.md` files (30 header lines + `mtimeMs` in one `readFileInRange()` call). Pre-filtering `!alreadySurfaced`, `selectRelevantMemories()` (`memdir/findRelevantMemories.ts:77-141`) builds `formatMemoryManifest()` (`memdir/memoryScan.ts:84-94`) and runs Sonnet `sideQuery` (`max_tokens: 256`, `json_schema`, up to 5 files, `recentTools` suppression at `utils/attachments.ts:2465-2503`).

> [!NOTE]
> **Snapshot Absence (`memdir/memoryShapeTelemetry.js`):** Under `feature('MEMORY_SHAPE_TELEMETRY')`, `memdir/findRelevantMemories.ts:66-72` requires `./memoryShapeTelemetry.js` and calls `logMemoryRecallShape(memories, selected)` even when empty; `utils/sessionFileAccessHooks.ts:38-40` and `utils/sessionFileAccessHooks.ts:210-224` call `logMemoryWriteShape()`. Absent from this snapshot (call sites only).

To hide `sideQuery` latency behind streaming and tools, `query.ts:297-304` binds `using pendingMemoryPrefetch = startRelevantMemoryPrefetch(state.messages, state.toolUseContext)` once per turn before `while (true)`. Four cheap guards—`isAutoMemoryEnabled()` + `tengu_moth_copse`, non-meta prompt, `>= 2` words, and `collectSurfacedMemories(messages).totalBytes < 60 * 1024` (`utils/attachments.ts:2383-2386`, `RELEVANT_MEMORIES_CONFIG.MAX_SESSION_BYTES` at `utils/attachments.ts:279-289`)—return `undefined` (`using` no-op); otherwise it returns a handle:

```ts
// utils/attachments.ts:2390-2423
const controller = createChildAbortController(toolUseContext.abortController)
const firedAt = Date.now()
const promise = getRelevantMemoryAttachments(
  input,
  toolUseContext.options.agentDefinitions.activeAgents,
  toolUseContext.readFileState,
  collectRecentSuccessfulTools(messages, lastUserMessage),
  controller.signal,
  surfaced.paths,
).catch(e => {
  if (!isAbortError(e)) {
    logError(e)
  }
  return []
})

const handle: MemoryPrefetch = {
  promise,
  settledAt: null,
  consumedOnIteration: -1,
  [Symbol.dispose]() {
    controller.abort()
    logEvent('tengu_memdir_prefetch_collected', {
      hidden_by_first_iteration:
        handle.settledAt !== null && handle.consumedOnIteration === 0,
      consumed_on_iteration: handle.consumedOnIteration,
      latency_ms: (handle.settledAt ?? Date.now()) - firedAt,
    })
  },
}
void promise.finally(() => {
  handle.settledAt = Date.now()
})
return handle
```

At `queryLoop`'s post-tools stage (`query.ts:1592-1614`), collection **never waits**: it polls `settledAt !== null && consumedOnIteration === -1`, skipping if still running. When ready, `filterDuplicateMemoryAttachments()` (`utils/attachments.ts:2520-2541`) filters survivors, yields `<system-reminder>` attachments (`utils/messages.ts:3708-3722`), and sets `consumedOnIteration = turnCount - 1`.

### Hidden Invariants & Production Scars

- **Deterministic disposal across 12 `queryLoop` exits:** TC39 `using` ensures `[Symbol.dispose]()` runs on all 12 `return { reason: ... }` exits (`query.ts:646` through `query.ts:1711`), throws, and `.return()`, cancelling orphaned side-queries and emitting `tengu_memdir_prefetch_collected`. `createChildAbortController()` (`utils/abortController.ts:68-99`) propagates Escape downward, isolates child abort, and cleans up via `WeakRef`.
- **Precomputed `memoryHeader` cache-bust scar (`utils/attachments.ts:505-514`, `utils/attachments.ts:2327-2332`):** Formatting `"saved N days ago"` at render time (`utils/messages.ts:3715`) flips across midnight and busts cache; freezing `header` at creation stays byte-stable.
- **Mark-after-filter scar (`utils/attachments.ts:2506-2541`):** Writing paths to `readFileState` during `readMemoriesForSurfacing()` (`utils/attachments.ts:2279-2321`, capped at `200` lines / `4096` bytes at `utils/attachments.ts:269-277`) made `filterDuplicateMemoryAttachments()` drop 100% of prefetched memories. Writing survivors *after* filtering breaks the cycle.
- **Self-healing 60 KB budget (`utils/attachments.ts:2251-2266`):** Scanning `messages` in `collectSurfacedMemories()` instead of a mutable counter lets [Chapter 09](09-five-layer-compaction-pipeline.md) compaction restore the budget automatically.

---

## 4. Cache-Sharing Background Agents: `SessionMemory` and `extractMemories` (`services/SessionMemory/`, `services/extractMemories/`, `utils/forkedAgent.ts`)

### The Problem

Background memory agents must read live history without cold `cache_creation` penalties or uncontrolled repo edits.

### The Mechanism: `runForkedAgent()` Prefix Reuse, Mid-Turn Scratchpads, and Turn-End Extraction

`SessionMemory`, `extractMemories`, and `autoDream` run via [`utils/forkedAgent.ts`](../../utils/forkedAgent.ts) (**forward seam to Chapter 18**). `runForkedAgent()` (`utils/forkedAgent.ts:489-626`) takes `createCacheSafeParams(context)` (`utils/forkedAgent.ts:131-141`) to preserve exact `systemPrompt`, `userContext`, `systemContext`, `toolUseContext`, and `forkContextMessages`.

`createSubagentContext()` (`utils/forkedAgent.ts:345-462`) clones `readFileState` and `contentReplacementState`, starts fresh `loadedNestedMemoryPaths` (`utils/forkedAgent.ts:383`), and stubs `setAppState` while keeping `setAppStateForTasks`. *(Both `constants/querySource.js` at `utils/forkedAgent.ts:14` and `types/message.js` at `utils/forkedAgent.ts:26` are absent from this snapshot; call sites only.)*

#### A. Live Session Scratchpad (`services/SessionMemory/`)

`initSessionMemory()` (`services/SessionMemory/sessionMemory.ts:357-375`) runs inside `!isBareMode()` (`setup.ts:293`, calling `initSessionMemory()` at `setup.ts:294`), exits on remote mode (`services/SessionMemory/sessionMemory.ts:358`), logs `tengu_session_memory_init` under `USER_TYPE === 'ant'` (`services/SessionMemory/sessionMemory.ts:363-367`), exits if `!isAutoCompactEnabled()` (`services/SessionMemory/sessionMemory.ts:369-371`), and calls `registerPostSamplingHook()` (`utils/hooks/postSamplingHooks.ts:31-33`, fired at `query.ts:1000-1009`).

- **FIFO queue & thresholds:** `sequential()` (`utils/sequential.ts:19-56`) serializes ticks. After `querySource === 'repl_main_thread'` and lazy GrowthBook `tengu_session_memory` / `tengu_sm_config` (`> 0` overrides), `shouldExtractMemory()` (`services/SessionMemory/sessionMemory.ts:134-181`) triggers at `>= 10000` init tokens, then `+5000` tokens with `>= 3` tool calls or a tool-free break.
- **Atomic init & Edit-only sandbox:** `setupSessionMemoryFile()` (`services/SessionMemory/sessionMemory.ts:183-233`) creates `summary.md` via `flag: 'wx'` (`O_CREAT|O_EXCL`, `0o600`), seeds the 10-section template (`services/SessionMemory/prompts.ts:11-41`), and deletes `memoryPath` from `readFileState` before `FileReadTool.call` to prevent a `file_unchanged` stub. `createMemoryFileCanUseTool(memoryPath)` (`services/SessionMemory/sessionMemory.ts:460-482`) permits **only** `FILE_EDIT_TOOL_NAME` on exact `memoryPath`.
- **Safe cursor:** `updateLastSummarizedMessageIdIfSafe()` (`services/SessionMemory/sessionMemory.ts:488-495`) advances `lastSummarizedMessageId` only when `!hasToolCallsInLastAssistantTurn(messages)` so [Chapter 09](09-five-layer-compaction-pipeline.md)'s `trySessionMemoryCompaction()` (`services/compact/sessionMemoryCompact.ts:514-630`, calling `calculateMessagesToKeepIndex()` at `services/compact/sessionMemoryCompact.ts:571-574`) never splits a tool pair.
- **Leaf utils:** [`services/SessionMemory/sessionMemoryUtils.ts`](../../services/SessionMemory/sessionMemoryUtils.ts) isolates `waitForSessionMemoryExtraction()` (`15s` wait / `60s` stale) from `runAgent`, while [`services/SessionMemory/prompts.ts`](../../services/SessionMemory/prompts.ts) exports `isSessionMemoryEmpty()` and `truncateSessionMemoryForCompact()` (`services/SessionMemory/prompts.ts:256-324`).

#### B. Turn-End Topic Extraction (`services/extractMemories/`)

Because Bun's `feature()` tree-shakes direct `if` checks only (docblock at `memdir/paths.ts:65-67`), `feature('EXTRACT_MEMORIES')` sits at three caller boundaries—never inside `services/extractMemories/extractMemories.ts`: `utils/backgroundHousekeeping.ts:34-36`, `query/stopHooks.ts:141-153`, and `cli/print.ts:967-969`.

At turn end, `query/stopHooks.ts:136` checks `!isBareMode()`, and `query/stopHooks.ts:141-153` checks `!agentId` plus `isExtractModeActive()` (`memdir/paths.ts:69-77`, GrowthBook `tengu_passport_quail` + non-interactive GrowthBook `tengu_slate_thimble`); headless exit calls `drainPendingExtraction()` (`services/extractMemories/extractMemories.ts:611-615`) via its 60s `.unref()` `drainer` closure (`services/extractMemories/extractMemories.ts:579-586`).

`runExtraction()` (`services/extractMemories/extractMemories.ts:329-523`) skips via `hasMemoryWritesSince()` (`services/extractMemories/extractMemories.ts:121-148`) after main-agent writes, throttles via GrowthBook `tengu_bramble_lintel` (`services/extractMemories/extractMemories.ts:377-386`), and coalesces overlapping turns into one trailing `pendingContext` pass (`services/extractMemories/extractMemories.ts:503-522`, `services/extractMemories/extractMemories.ts:557-564`).

The fork runs with `skipTranscript: true`, `maxTurns: 5`, 2-turn batching (`services/extractMemories/prompts.ts:29-154`), compaction-safe cursor fallback (`services/extractMemories/extractMemories.ts:103-108`), and `createAutoMemCanUseTool()` (`services/extractMemories/extractMemories.ts:171-222`):

```ts
// services/extractMemories/extractMemories.ts:171-222
export function createAutoMemCanUseTool(memoryDir: string): CanUseToolFn {
  return async (tool: Tool, input: Record<string, unknown>) => {
    // Allow REPL — when REPL mode is enabled (ant-default), primitive tools
    // are hidden from the tool list so the forked agent calls REPL instead.
    // REPL's VM context re-invokes this canUseTool for each inner primitive
    // (toolWrappers.ts createToolWrapper), so the Read/Bash/Edit/Write checks
    // below still gate the actual file and shell operations. Giving the fork a
    // different tool list would break prompt cache sharing (tools are part of
    // the cache key — see CacheSafeParams in forkedAgent.ts).
    if (tool.name === REPL_TOOL_NAME) {
      return { behavior: 'allow' as const, updatedInput: input }
    }
    // ...
    if (tool.name === BASH_TOOL_NAME) {
      const parsed = tool.inputSchema.safeParse(input)
      if (parsed.success && tool.isReadOnly(parsed.data)) {
        return { behavior: 'allow' as const, updatedInput: input }
      }
      // ...
    }

    if (
      (tool.name === FILE_EDIT_TOOL_NAME ||
        tool.name === FILE_WRITE_TOOL_NAME) &&
      'file_path' in input
    ) {
      const filePath = input.file_path
      if (typeof filePath === 'string' && isAutoMemPath(filePath)) {
        return { behavior: 'allow' as const, updatedInput: input }
      }
    }
    // ...
  }
}
```

### Hidden Invariants & Production Scars

> [!IMPORTANT]
> **The `REPL_TOOL_NAME` Cache-Key Scar (`services/extractMemories/extractMemories.ts:173-182`):** Because `tools[]` hashes first in the prompt cache ([Chapter 04](04-prompt-engineering-and-cache-boundaries.md)), forks cannot strip tools without busting cache. Claude Code sends the full tool pool (allowing `REPL_TOOL_NAME` in `ant`-default REPL mode) and enforces least privilege in `canUseTool` as REPL wraps inner `Read`, read-only `Bash`, `Edit`, and `Write`.

- **Missing `try/finally` scar in `extractSessionMemory`:** Manual `/summary` (`services/SessionMemory/sessionMemory.ts:450-452`) calls `markExtractionCompleted()` in `finally`, whereas background `extractSessionMemory` runs unguarded (`services/SessionMemory/sessionMemory.ts:272-350`), calling `markExtractionCompleted()` at `services/SessionMemory/sessionMemory.ts:349`—relying on `EXTRACTION_STALE_THRESHOLD_MS = 60000` (`services/SessionMemory/sessionMemoryUtils.ts:13`, `services/SessionMemory/sessionMemoryUtils.ts:93`) on throws.

---

## 5. Cross-Session Consolidation: `autoDream`'s Three-Gate Lock (`services/autoDream/`, `tasks/DreamTask/DreamTask.ts`)

### The Problem

Per-turn notes accumulate contradictions, relative dates, and index bloat. Consolidating every turn wastes tokens; unlocked consolidation lets concurrent terminals corrupt rewrites.

### The Mechanism: Cheapest-First Funnel, PID+mtime Lock, and Symmetric Rollback

Initialized at `utils/backgroundHousekeeping.ts:37` and fired at `query/stopHooks.ts:154-156` (inside `!isBareMode()`, `query/stopHooks.ts:136`, excluding subagents), `isGateOpen()` (`services/autoDream/autoDream.ts:95-100`) checks `!getKairosActive()`, `!getIsRemoteMode()`, `isAutoMemoryEnabled()`, and `isAutoDreamEnabled()`.

`isAutoDreamEnabled()` lives in 21-line [`services/autoDream/config.ts`](../../services/autoDream/config.ts) (`services/autoDream/config.ts:13-21`), where `settings.autoDreamEnabled` overrides GrowthBook `tengu_onyx_plover.enabled`. *(`isForced()` at `services/autoDream/autoDream.ts:105-107` returns `false`.)*

`runAutoDream()` (`services/autoDream/autoDream.ts:125-272`) bounds per-turn cost to at most two cached GrowthBook reads when `settings.autoDreamEnabled` is unset (`getConfig()` at `services/autoDream/autoDream.ts:126` and `isAutoDreamEnabled()` via `isGateOpen()` at `services/autoDream/autoDream.ts:128`) plus one `stat` via a **cheapest-first three-gate funnel** (`services/autoDream/autoDream.ts:126-190`, `DEFAULTS = { minHours: 24, minSessions: 5 }` at `services/autoDream/autoDream.ts:63-66`):

1. **Time gate (1 `stat`):** `readLastConsolidatedAt()` (`services/autoDream/consolidationLock.ts:29-36`) reads `.consolidate-lock`'s `mtime` (`0` if missing); returns unless `hoursSince >= cfg.minHours`.
2. **Scan throttle + Session gate:** Enforces a 10-minute `SESSION_SCAN_INTERVAL_MS` cooldown (`services/autoDream/autoDream.ts:56`, `services/autoDream/autoDream.ts:144-151`) before `listSessionsTouchedSince(lastAt)` (`services/autoDream/consolidationLock.ts:118-124`, using `mtime` since `ext4` `birthtime` is `0` and excluding `agent-*.jsonl`); `runAutoDream()` then excludes `getSessionId()` (`services/autoDream/autoDream.ts:164-165`) and requires `>= cfg.minSessions`.
3. **Cross-process lock:** `tryAcquireConsolidationLock()` (`services/autoDream/consolidationLock.ts:46-84`) writes the holder PID into `.consolidate-lock`, whose `mtime` doubles as `lastConsolidatedAt`:

```ts
// services/autoDream/consolidationLock.ts:60-84
  if (mtimeMs !== undefined && Date.now() - mtimeMs < HOLDER_STALE_MS) {
    if (holderPid !== undefined && isProcessRunning(holderPid)) {
      logForDebugging(
        `[autoDream] lock held by live PID ${holderPid} (mtime ${Math.round((Date.now() - mtimeMs) / 1000)}s ago)`,
      )
      return null
    }
    // Dead PID or unparseable body — reclaim.
  }

  // Memory dir may not exist yet.
  await mkdir(getAutoMemPath(), { recursive: true })
  await writeFile(path, String(process.pid))

  // Two reclaimers both write → last wins the PID. Loser bails on re-read.
  let verify: string
  try {
    verify = await readFile(path, 'utf8')
  } catch {
    return null
  }
  if (parseInt(verify.trim(), 10) !== process.pid) return null

  return mtimeMs ?? 0
}
```

Once locked, `runAutoDream()` calls `registerDreamTask()` in [`tasks/DreamTask/DreamTask.ts`](../../tasks/DreamTask/DreamTask.ts) (**Ch 17 seam**, `setAppStateForTasks ?? setAppState`, `services/autoDream/autoDream.ts:200-208`). It builds the 4-phase prompt (`services/autoDream/consolidationPrompt.ts:10-65`: Orient → Gather signal → Consolidate → Prune and index) and calls `runForkedAgent()` (`services/autoDream/autoDream.ts:224-233`) with `createAutoMemCanUseTool()`, `skipTranscript: true`, and `makeDreamProgressWatcher()` (`services/autoDream/autoDream.ts:281-313`).

### Hidden Invariants & Production Scars

- **1-hour PID-reuse guard & rollback rewind (`services/autoDream/consolidationLock.ts:19`, `services/autoDream/consolidationLock.ts:91-108`):** `HOLDER_STALE_MS = 60 * 60 * 1000` stops recycled PIDs from deadlocking consolidation. On failure, `rollbackConsolidationLock(priorMtime)` unlinks if `priorMtime === 0` or runs `writeFile(path, '')` *before* `utimes()` so our live PID clears the lock.
- **No double-rollback on user kill (`services/autoDream/autoDream.ts:258-271`, `tasks/DreamTask/DreamTask.ts:136-156`):** `DreamTask.kill` aborts `abortController` and calls `rollbackConsolidationLock(priorMtime)`; `if (abortController.signal.aborted) return` prevents double-rollback or overwriting `'killed'`.
- **21-line leaf config (`services/autoDream/config.ts:1-21`):** Lets UI components query `isAutoDreamEnabled()` without importing `runForkedAgent` or `DreamTask`.

---

## 6. Team Memory Sync, Secret Scanning, and File Watcher (`services/teamMemorySync/`)

### The Problem

Syncing `<autoMemPath>/team/` across collaborators adds three hazards: concurrent edits must not lose local work or hit HTTP 413s, leaked credentials reach the whole org, and naive watchers exhaust fds or spin on permanent auth errors.

### The Mechanism: Asymmetric Delta Sync, Dual-Layer Secret Scanning, and Pull-Before-Watch

[`services/teamMemorySync/index.ts`](../../services/teamMemorySync/index.ts) requires first-party OAuth (`isUsingOAuth()`, `services/teamMemorySync/index.ts:151-161`), builds URLs in `getTeamMemorySyncEndpoint()` (`services/teamMemorySync/index.ts:163-167`: `TEAM_MEMORY_SYNC_URL` or `getOauthConfig().BASE_API_URL`), and uses lazy Zod schemas in [`services/teamMemorySync/types.ts`](../../services/teamMemorySync/types.ts).

`SyncState` (`services/teamMemorySync/index.ts:100-119`) tracks `{ lastKnownChecksum, serverChecksums, serverMaxEntries }` (stale "watcher suppression" docblock at `services/teamMemorySync/index.ts:22`). Sync splits conflict policy between pull and push:

- **Server-wins parallel pull (`pullTeamMemory()`, `services/teamMemorySync/index.ts:770-867`):** Sends `If-None-Match` with exponential backoff in `fetchTeamMemory()` (`services/teamMemorySync/index.ts:387-410`, `MAX_RETRIES = 3`). `writeRemoteEntriesToLocal()` (`services/teamMemorySync/index.ts:689-755`) validates keys (`validateTeamMemKey()`), caps at `250_000` bytes, skips unchanged files, and writes in parallel (fixing ~22s p99 pulls). `pullTeamMemory()` calls `clearMemoryFileCaches()` (`services/teamMemorySync/index.ts:851-855`) when `filesWritten > 0`.
- **Local-wins delta push (`pushTeamMemory()` at `services/teamMemorySync/index.ts:889-1146`):** Read-only on disk. Packs `sha256:` deltas into sorted `200_000`-byte `PUT` batches via `batchDeltaByBytes()` (`services/teamMemorySync/index.ts:426-460`, avoiding gateway HTML 413s), advancing `serverChecksums` and `lastKnownChecksum` after each `200`.
- **412 hash probes & dynamic 413 caps:** On `412`, `fetchTeamMemoryHashes()` (`GET ...&view=hashes`, `services/teamMemorySync/index.ts:315-385`) refreshes hashes without bodies (`MAX_CONFLICT_RETRIES = 2`). On structured `413` (`TeamMemoryTooManyEntriesSchema`, `services/teamMemorySync/index.ts:533-542`), `pushTeamMemory()` caches `state.serverMaxEntries` (`services/teamMemorySync/index.ts:1053-1059`) so `readLocalTeamMemory()` truncates sorted keys deterministically (`services/teamMemorySync/index.ts:654-671`).

Credential defense (PSR M22174) uses 36 gitleaks regexes in [`services/teamMemorySync/secretScanner.ts`](../../services/teamMemorySync/secretScanner.ts) (`ANT_KEY_PFX = ['sk', 'ant', 'api'].join('-')`, `services/teamMemorySync/secretScanner.ts:46`; `SECRET_RULES`, `services/teamMemorySync/secretScanner.ts:48-224`) at two gates:

1. **Upstream fail-closed write guard:** `checkTeamMemSecrets()` ([`services/teamMemorySync/teamMemSecretGuard.ts`](../../services/teamMemorySync/teamMemSecretGuard.ts), `services/teamMemorySync/teamMemSecretGuard.ts:15-44`, `feature('TEAMMEM')`) runs in `validateInput` on `content` (`tools/FileWriteTool/FileWriteTool.ts:157-160`) and `new_string` only (`tools/FileEditTool/FileEditTool.ts:144-147`)—**not** inside `createAutoMemCanUseTool()`—blocking writes pre-disk.
2. **Push-time safety net:** `readLocalTeamMemory()` (`services/teamMemorySync/index.ts:567-673`) runs full-file `scanForSecrets()` (`services/teamMemorySync/index.ts:599-615`), catching Bash, external, and split-edit credentials and returning `skippedSecrets` while pushing clean files. `pushTeamMemory()` logs rule IDs only via `tengu_team_mem_secret_skipped` (`services/teamMemorySync/index.ts:935-944`).

[`services/teamMemorySync/watcher.ts`](../../services/teamMemorySync/watcher.ts) (started inside `!isBareMode()`, `setup.ts:336`, behind `feature('TEAMMEM')`, `setup.ts:365-369`) avoids pull-echo structurally: `startTeamMemoryWatcher()` (`services/teamMemorySync/watcher.ts:252-305`) finishes `pullTeamMemory()` *before* `startFileWatcher()`, watching `404` repos via `fs.watch({ recursive: true })` (O(1) FSEvents vs. 500+ kqueue fds in `chokidar` 4+).

Writes coalesce behind a 2-second `DEBOUNCE_MS` timer (`services/teamMemorySync/watcher.ts:35`), backed by `PostToolUse` `notifyTeamMemoryWrite()` (`utils/sessionFileAccessHooks.ts:201`, `utils/sessionFileAccessHooks.ts:205`) and final flush in `stopTeamMemoryWatcher()` (`services/teamMemorySync/watcher.ts:327-352`).

### Hidden Invariants & Production Scars

- **167K-event `no_oauth` storm & unlink-cleared circuit breaker:** Exponential backoff lives in `fetchTeamMemory()`, not `watcher.ts`. Instead, `watcher.ts` latches `pushSuppressedReason` on permanent failure, clearing it only on unlink (`stat()` → `ENOENT`, `services/teamMemorySync/watcher.ts:187-205`) or restart:

```ts
// services/teamMemorySync/watcher.ts:45-73
// Set after a push fails for a reason that can't self-heal on retry.
// Prevents watch events from other sessions' writes to the shared team
// dir driving an infinite retry loop (BQ Mar 14-16: one no_oauth device
// emitted 167K push events over 2.5 days). Cleared on unlink — file deletion
// is a recovery action for the too-many-entries case, and for no_oauth the
// suppression persisting until session restart is correct.
let pushSuppressedReason: string | null = null

/**
 * Permanent = retry without user action will fail the same way.
 * - no_oauth / no_repo: pre-request client checks, no status code
 * - 4xx except 409/429: client error (404 missing repo, 413 too many
 *   entries, 403 permission). 409 is a transient conflict — server state
 *   changed under us, a fresh push after next pull can succeed. 429 is a
 *   rate limit — watcher-driven backoff is fine.
 */
export function isPermanentFailure(r: TeamMemorySyncPushResult): boolean {
  if (r.errorType === 'no_oauth' || r.errorType === 'no_repo') return true
  if (
    r.httpStatus !== undefined &&
    r.httpStatus >= 400 &&
    r.httpStatus < 500 &&
    r.httpStatus !== 409 &&
    r.httpStatus !== 429
  ) {
    return true
  }
  return false
}
```

---

## Putting Layer 3 Together

```text
Memory Subsystem Horizon, Trigger & Write Boundary Matrix
+-----------------+---------------+----------------------+-------------------+
| Subsystem       | Trigger Seam  | Gate / Throttle      | Write Sandbox     |
+-----------------+---------------+----------------------+-------------------+
| CLAUDE.md/rules | Turn 1 + Read | Always on; Set dedup | RO; isPartialView |
| Memory Prefetch | query() using | tengu_moth_copse     | RO sideQuery <=5  |
| SessionMemory   | Post-sampling | tengu_session_memory | Edit summary.md   |
| extractMemories | Stop hook     | EXTRACT_MEMORIES     | RO/Bash + AutoMem |
| autoDream       | Stop hook     | 24h/5ses + PID lock  | RO/Bash + AutoMem |
| teamMemorySync  | Setup + watch | TEAMMEM + OAuth; 2s  | team/ + 36 rules  |
+-----------------+---------------+----------------------+-------------------+
```

```mermaid
flowchart TD
    CMD["utils/claudemd.ts: hierarchical discovery & @include"]
    ATT["utils/attachments.ts: loadedNestedMemoryPaths & prefetch"]
    Q["query.ts: using pendingMemoryPrefetch & post-sampling"]
    STOP["query/stopHooks.ts: handleStopHooks()"]
    SM["services/SessionMemory/: summary.md scratchpad"]
    EXT["services/extractMemories/: turn-end topic extraction"]
    DRM["services/autoDream/: 3-gate lock & consolidation"]
    FORK["utils/forkedAgent.ts: runForkedAgent() + CacheSafeParams"]
    SUM["session-memory/summary.md (Ch 09)"]
    GUARD["FileWriteTool & FileEditTool: checkTeamMemSecrets()"]
    MEM["memdir/: private memory/ & memory/team/"]
    SYNC["services/teamMemorySync/: watcher & OAuth delta sync"]
    PERM["Ch 11: utils/permissions/ carve-outs & classifier"]

    CMD -->|"getUserContext() (Ch 04)"| Q
    CMD -->|"nested rules"| ATT
    MEM -->|"scanMemoryFiles()"| ATT
    ATT -->|"non-blocking poll"| Q
    Q -->|"executePostSamplingHooks()"| SM
    Q -->|"end of turn"| STOP
    STOP -->|"EXTRACT_MEMORIES"| EXT
    STOP -->|"tengu_onyx_plover"| DRM
    SM -->|"createMemoryFileCanUseTool()"| FORK
    EXT -->|"createAutoMemCanUseTool()"| FORK
    DRM -->|"createAutoMemCanUseTool()"| FORK
    FORK -->|"SessionMemory: Edit only"| SUM
    FORK -->|"extractMemories / autoDream"| GUARD
    GUARD --> MEM
    MEM <--> SYNC
    CMD -.->|"cachedClaudeMdContent"| PERM
    MEM -.->|"isAutoMemPath()"| PERM
```

---

## How This Snaps Into the Next Layer

Every memory write boundary and policy signal plugs into **Layer 4** in [Chapter 11](11-the-permission-engine.md):

- **Forked-agent callbacks:** `createMemoryFileCanUseTool()` (`services/SessionMemory/sessionMemory.ts:460-482`) and `createAutoMemCanUseTool()` (`services/extractMemories/extractMemories.ts:171-222`) implement `CanUseToolFn` without mutating cached tool schemas.
- **Filesystem helpers & carve-outs:** [`utils/permissions/filesystem.ts`](../../utils/permissions/filesystem.ts) owns `getSessionMemoryDir()` / `isSessionMemoryPath()` (`utils/permissions/filesystem.ts:261-278`), the `!hasAutoMemPathOverride() && isAutoMemPath(normalizedPath)` write carve-out (`utils/permissions/filesystem.ts:1572-1581`) withholding silent writes from `CLAUDE_COWORK_MEMORY_PATH_OVERRIDE`, and read carve-outs (`utils/permissions/filesystem.ts:1620-1629`, `utils/permissions/filesystem.ts:1716-1725`).
- **Auto-mode classifier seam:** `cachedClaudeMdContent` (`bootstrap/state.ts:121-123`, `bootstrap/state.ts:1207-1213`) breaks the `claudemd → filesystem → permissions → yoloClassifier` cycle so `buildClaudeMdMessage()` (`utils/permissions/yoloClassifier.ts:460-477`) feeds `CLAUDE.md` into `classifyYoloAction()` (`utils/permissions/permissions.ts:102-105`, `utils/permissions/permissions.ts:693-699`).
- **Layer 6 forward seams:** `tasks/DreamTask/DreamTask.ts` plugs into **Chapter 17**'s background task runtime, and `utils/forkedAgent.ts` opens **Chapter 18**'s subagent runtime.

---

## Reading Exercises & Code Checkpoints

1. **Trace `loadedNestedMemoryPaths` across attachments, compaction, and forks:**
   Run `rg -n "loadedNestedMemoryPaths" utils/attachments.ts services/compact/compact.ts utils/forkedAgent.ts` and verify why a non-evicting `Set` pairs with LRU `readFileState` and clears on compaction.
2. **Trace `tengu_moth_copse` across all four memory subsystems:**
   Run `rg -n "startRelevantMemoryPrefetch|tengu_moth_copse" query.ts utils/attachments.ts utils/claudemd.ts memdir/memdir.ts services/extractMemories/extractMemories.ts` to confirm how one flag swaps static `MEMORY.md` for `using` prefetch and `skipIndex = true`.
3. **Audit background sandboxes and upstream secret scanning:**
   Run `rg -n "createMemoryFileCanUseTool|createAutoMemCanUseTool|checkTeamMemSecrets|isAutoMemPath" services/SessionMemory/sessionMemory.ts services/extractMemories/extractMemories.ts services/autoDream/autoDream.ts services/teamMemorySync/teamMemSecretGuard.ts tools/FileWriteTool/FileWriteTool.ts tools/FileEditTool/FileEditTool.ts utils/permissions/filesystem.ts` and confirm why `checkTeamMemSecrets` runs in `validateInput`.
4. **Verify `autoDream`'s 3-gate lock, symmetric rollback, and leaf config:**
   Run `rg -n "isAutoDreamEnabled|tryAcquireConsolidationLock|rollbackConsolidationLock|registerDreamTask|tengu_onyx_plover" services/autoDream/ tasks/DreamTask/DreamTask.ts` and trace both rollbacks (`services/autoDream/autoDream.ts:270`, `tasks/DreamTask/DreamTask.ts:154`) plus `abortController.signal.aborted`.


---

<!-- chapters/11-the-permission-engine.md — https://reverseengineeringclaudecode.com/chapters/11-the-permission-engine -->

# Chapter 11 — The Permission Engine: Modes, Rules, Classifiers, and Persistence

> **Layer:** Layer 4 (Safety, Policy, Sandbox & Lifecycle Hooks)
> **Prerequisites:** [Chapter 01](01-atoms-types-stores-and-primitives.md), [Chapter 02](02-the-tool-contract.md), [Chapter 06](06-executing-tools.md), [Chapter 08](08-session-envelope-query-engine-and-transcripts.md), [Chapter 10](10-memory-systems-claudemd-auto-memory-and-dream.md)
> **Primary Source Files:**
> - [`types/permissions.ts`](../../types/permissions.ts) — mode unions, 8 `PermissionRuleSource`s, `PermissionUpdate`, `PermissionResult`, and `YoloClassifierResult` contracts (441 lines; present in this snapshot)
> - [`utils/permissions/PermissionMode.ts`](../../utils/permissions/PermissionMode.ts) — Zod mode schemas, UI metadata, `toExternalPermissionMode`, and `permissionModeFromString` (141 lines)
> - [`utils/permissions/permissions.ts`](../../utils/permissions/permissions.ts) — two-layer evaluator (`hasPermissionsToUseToolInner`, `hasPermissionsToUseTool`), `checkRuleBasedPermissions`, headless hooks, and `syncPermissionRulesFromDisk` (1,486 lines)
> - [`utils/permissions/permissionSetup.ts`](../../utils/permissions/permissionSetup.ts) — dangerous-permission stripping/restoration, `transitionPermissionMode`, plan/auto coordination, CLI init, and killswitches (1,532 lines)
> - [`utils/permissions/permissionsLoader.ts`](../../utils/permissions/permissionsLoader.ts) & [`utils/permissions/PermissionUpdate.ts`](../../utils/permissions/PermissionUpdate.ts) — disk loader (`allowManagedPermissionRulesOnly`, lenient edit-only JSON), reducer, and 3-source persistence (296 & 389 lines)
> - [`utils/permissions/filesystem.ts`](../../utils/permissions/filesystem.ts) & [`utils/permissions/pathValidation.ts`](../../utils/permissions/pathValidation.ts) — symlink containment, gitignore prefix lattice, protected paths, internal carve-outs, and shell TOCTOU guards (1,777 & 485 lines)
> - [`utils/permissions/shellRuleMatching.ts`](../../utils/permissions/shellRuleMatching.ts) — `ShellPermissionRule` parser (`prefix`/`wildcard`/`exact`) and regex `matchWildcardPattern` (228 lines)
> - [`utils/permissions/yoloClassifier.ts`](../../utils/permissions/yoloClassifier.ts) & [`utils/permissions/classifierDecision.ts`](../../utils/permissions/classifierDecision.ts) — sanitized transcript builder, two-stage XML / `classify_result` classifier, and `isAutoModeAllowlistedTool` (1,495 & 98 lines)
> - [`utils/permissions/denialTracking.ts`](../../utils/permissions/denialTracking.ts) — immutable `DENIAL_LIMITS` (`maxConsecutive: 3`, `maxTotal: 20`) circuit breaker and `shouldFallbackToPrompting` (45 lines)
> - [`hooks/useCanUseTool.tsx`](../../hooks/useCanUseTool.tsx), [`hooks/toolPermission/PermissionContext.ts`](../../hooks/toolPermission/PermissionContext.ts) & [`hooks/toolPermission/handlers/interactiveHandler.ts`](../../hooks/toolPermission/handlers/interactiveHandler.ts) — compiled `CanUseToolFn` waterfall, two-phase `claim()` lock, and 5-racer modal (204, 388 & 536 lines)

---

## Why This Layer Exists

Layers 1–3 wired every caller into permissions: `Tool.checkPermissions()` ([Chapter 02](02-the-tool-contract.md)), `runToolUse()` via `resolveHookPermissionDecision()` (`services/tools/toolExecution.ts:921-929`, [Chapter 06](06-executing-tools.md)), and `QueryEngine.ts:244-271` tracking SDK `permissionDenials` ([Chapter 08](08-session-envelope-query-engine-and-transcripts.md)).

Memory agents ([Chapter 10](10-memory-systems-claudemd-auto-memory-and-dream.md)) supply scoped `CanUseToolFn` wrappers (`createMemoryFileCanUseTool` at `services/SessionMemory/sessionMemory.ts:460-482`, `createAutoMemCanUseTool` at `services/extractMemories/extractMemories.ts:171-222`) while stashing `CLAUDE.md` in `bootstrap/state.ts` (`context.ts:176`).

Giving an LLM shell and filesystem write access demands three guarantees before any tool executes:

1. **Non-bypassable precedence:** Enterprise policy, CLI flags, settings, hooks, modes, and config guards must compose without letting a hook, a broad allow rule, or `bypassPermissions` defeat a deny rule or `.claude/settings.json` edit.
2. **Adversarial path & shell defenses:** Symlink chains, dangling links, case-insensitive filesystems, Windows NTFS short names, UNC paths, and shell expansions (`$VAR`, `~root`) all open parser-vs-OS TOCTOU gaps.
3. **Autonomous safety under untrusted context:** An `auto`-mode classifier must judge risk without prompt injection from `tool_result` outputs or assistant prose, fail closed on outages, and fall back to human prompts before spinning forever.

---

## 1. Permission Contracts, Modes, and the Eight Rule Sources

### The Problem

Permissions sit in a high-fan-in import diamond spanning `Tool.ts`, `utils/claudemd.ts`, hooks, and UI. Rules come from eight origins, while modes must span external SDKs, a feature-gated classifier (`auto`), and an internal subagent mode (`bubble`) users must never pass on the CLI.

### The Mechanism: Leaf Contracts, Mode Projections, and the Source Lattice

Unlike absent `types/message.ts`, `types/permissions.ts` **is present** (441 lines) to break circular imports (`types/permissions.ts:1-7`). Watch one divergence: `types/permissions.ts:427-441` omits `isAutoModeAvailable?: boolean`, whereas runtime evaluators (`utils/permissions/permissions.ts:8`) import the authoritative `DeepImmutable<ToolPermissionContext>` from `Tool.ts:123-138` (`isAutoModeAvailable` at `Tool.ts:130`).

`types/permissions.ts:16-38` defines three concentric mode sets—5 external modes, 6 user-addressable runtime modes (`feature('TRANSCRIPT_CLASSIFIER')`), and 7 type literals including internal `'bubble'`:

```ts
// types/permissions.ts:16-38
export const EXTERNAL_PERMISSION_MODES = [
  'acceptEdits',
  'bypassPermissions',
  'default',
  'dontAsk',
  'plan',
] as const

export type ExternalPermissionMode = (typeof EXTERNAL_PERMISSION_MODES)[number]

// Exhaustive mode union for typechecking. The user-addressable runtime set
// is INTERNAL_PERMISSION_MODES below.
export type InternalPermissionMode = ExternalPermissionMode | 'auto' | 'bubble'
export type PermissionMode = InternalPermissionMode

// Runtime validation set: modes that are user-addressable (settings.json
// defaultMode, --permission-mode CLI flag, conversation recovery).
export const INTERNAL_PERMISSION_MODES = [
  ...EXTERNAL_PERMISSION_MODES,
  ...(feature('TRANSCRIPT_CLASSIFIER') ? (['auto'] as const) : ([] as const)),
] as const satisfies readonly PermissionMode[]

export const PERMISSION_MODES = INTERNAL_PERMISSION_MODES
```

- **Internal `'bubble'` mode:** Excluded from `INTERNAL_PERMISSION_MODES` and assigned only to `FORK_AGENT` (`tools/AgentTool/forkSubagent.ts:67`). When explicit `canShowPermissionPrompts` is undefined (`tools/AgentTool/runAgent.ts:440-463`), `'bubble'` keeps local `shouldAvoidPrompts` `false` so async fork children skip setting `shouldAvoidPermissionPrompts: true` (without overwriting an inherited `true`), bubbling prompts to the parent while setting `awaitAutomatedChecksBeforeDialog = true` when async.
- **Parent-mode floor:** Agent definitions cannot override parent `bypassPermissions`, `acceptEdits`, or `feature('TRANSCRIPT_CLASSIFIER')` `auto` (`tools/AgentTool/runAgent.ts:421-434`).
- **Mode projections (`utils/permissions/PermissionMode.ts:42-121`):** `PERMISSION_MODE_CONFIG` maps modes to UI metadata and an `external` fallback (`auto` gated on `feature('TRANSCRIPT_CLASSIFIER')`). `toExternalPermissionMode` projects `'auto'` and `'bubble'` to `'default'` at SDK edges; `permissionModeFromString` defaults unknown strings to `'default'`.
- **Shift+Tab carousel (`utils/permissions/getNextPermissionMode.ts:17-101`):** Cycles `default -> acceptEdits -> plan -> [bypassPermissions] -> [auto] -> default` (`USER_TYPE === 'ant'` skips `acceptEdits`/`plan` from `default`; `dontAsk`/`auto` return to `'default'`). Under `feature('TRANSCRIPT_CLASSIFIER')`, `canCycleToAuto` checks both cached `isAutoModeAvailable` and live `isAutoModeGateEnabled()` so `cyclePermissionMode` never throws mid-session.

All rules in `alwaysAllowRules`, `alwaysDenyRules`, and `alwaysAskRules` are keyed by `PermissionRuleSource` (`types/permissions.ts:54-62`), ordered by `PERMISSION_RULE_SOURCES` (`utils/permissions/permissions.ts:109-114`):

| # | `PermissionRuleSource` | Origin | Editable? | Update Dest? | Shared? |
|---:|---|---|---|---|---|
| 1 | `userSettings` | `~/.claude/settings.json` | Yes | Yes | Personal |
| 2 | `projectSettings` | `<repo>/.claude/settings.json` | Yes | Yes | **Shared** |
| 3 | `localSettings` | `<repo>/.claude/settings.local.json` | Yes | Yes | Personal |
| 4 | `flagSettings` | `--settings` CLI path/JSON | No | No | Personal |
| 5 | `policySettings` | Enterprise managed policy | No | No | **Shared** |
| 6 | `cliArg` | `--allowed-tools` / `--disallowed-tools` / `--tools` | No | Yes | Personal |
| 7 | `command` | Skill / command frontmatter `allowed-tools` | No | No | **Shared** |
| 8 | `session` | Ephemeral in-session approvals | No | Yes | Personal |

Three utilities parse, load, and audit rules across these sources:

- **Parser & aliases (`utils/permissions/permissionRuleParser.ts:10-198`):** `permissionRuleValueFromString` splits `Tool(ruleContent)` via backslash-parity paren scanning, collapses `Bash()`/`Bash(*)` to blanket `{ toolName: 'Bash' }`, and normalizes `LEGACY_TOOL_NAME_ALIASES` (`Task -> Agent`, `KillShell -> TaskStop`, `AgentOutputTool`/`BashOutputTool -> TaskOutput`, plus `Brief` under `feature('KAIROS') || feature('KAIROS_BRIEF')`).
- **Managed lockdown (`utils/permissions/permissionsLoader.ts:31-242`):** When `policySettings.allowManagedPermissionRulesOnly === true`, `loadAllPermissionRulesFromDisk()` ignores all other sources, `shouldShowAlwaysAllowOptions()` hides permanent allow prompts, and `addPermissionRulesToSettings()` refuses writes.
- **Shadowed-rule audit:** `detectUnreachableRules` (`utils/permissions/shadowedRuleDetection.ts:193-234`) flags content-specific `allow` rules masked by tool-wide `deny`/`ask` rules; `isAllowRuleShadowedByAskRule` (`utils/permissions/shadowedRuleDetection.ts:111-147`) exempts sandboxed `Bash` only for personal `ask` sources (`!isSharedSettingSource`, `utils/permissions/shadowedRuleDetection.ts:61-67`), since teammates sharing `projectSettings`/`policySettings` may run unsandboxed.

### Hidden Invariants & Production Scars

- **Lenient edit-only JSON fallback (`utils/permissions/permissionsLoader.ts:61-83`, `utils/permissions/permissionsLoader.ts:253-256`):** If `settings.json` fails strict Zod validation (e.g., malformed `hooks`), writing `{ permissions: {} }` would wipe existing settings. `getSettingsForSourceLenient_FOR_EDITING_ONLY_NOT_FOR_READING` parses raw JSON without Zod so edits preserve untouched keys.
- **Legacy ant-only drift (`utils/permissions/PermissionMode.ts:97-105`):** `isExternalPermissionMode` returns `true` unconditionally when `process.env.USER_TYPE !== 'ant'`, though `types/permissions.ts:35` gates `'auto'` on `feature('TRANSCRIPT_CLASSIFIER')` in external builds. SDK edges rely on `toExternalPermissionMode`.
- **Within-bucket vs. cross-bucket order (`utils/permissions/permissions.ts:275-302`, `utils/permissions/permissions.ts:362-390`):** Cross-behavior precedence (`deny > ask > allow`) is fixed by pipeline order. Inside one bucket, tool-wide matchers use `.find()` (earliest source wins), while `getRuleByContentsForToolName` fills a `Map` `1 -> 8` (later source overwrites identical `ruleContent`).

---

## 2. Two-Layer Evaluation Precedence, Stripping, Transitions, and Persistence

### The Problem

A flat evaluator with scattered early returns lets one new `'ask'` branch silently bypass `dontAsk`, `auto`-mode classification, or headless hooks. Likewise, letting a `PreToolUse` hook skip deny/ask rules—or leaving `Bash(python:*)` active inside `auto` mode—breaks defense in depth.

### The Mechanism: Inner Precedence, Outer Transforms, and Reversible Stripping

`utils/permissions/permissions.ts` splits evaluation into an inner evaluator, a hook mirror, and an outer mode wrapper:

1. **Inner evaluator — `hasPermissionsToUseToolInner` (`utils/permissions/permissions.ts:1158-1319`):**
   - **Steps 0–1b (`utils/permissions/permissions.ts:1163-1206`):** Throws `AbortError` if aborted; checks blanket `deny` (canonical `getToolNameForPermissionCheck` blocking `CLAUDE_AGENT_SDK_MCP_NO_PREFIX` collisions plus `mcp__server` wildcards, `utils/permissions/permissions.ts:238-269`); checks blanket `ask` (except sandboxed auto-allow `Bash`, which falls through to `1c`).
   - **Steps 1c–1g (`utils/permissions/permissions.ts:1210-1260`):** Parses input and awaits `tool.checkPermissions` (re-throwing aborts; falling through as `passthrough` on other errors); returns immediately on tool `'deny'` (`1d`), `requiresUserInteraction?.()` `'ask'` (`1e`), content-specific `ask` rules (`1f`), and `safetyCheck` asks (`1g`).
   - **Steps 2a–3 (`utils/permissions/permissions.ts:1264-1318`):** Re-reads fresh `context.getAppState()` for `bypassPermissions` (or `plan` with `isBypassPermissionsModeAvailable`), checks blanket `allow` (`toolAlwaysAllowedRule`, `2b`), then promotes `passthrough` to `'ask'` via `createPermissionRequestMessage`.

Steps `1a`–`1g` are **bypass-immune**—even `bypassPermissions` cannot cross the `1g -> 2a` wall:

```ts
// utils/permissions/permissions.ts:1252-1281
// 1g. Safety checks (e.g. .git/, .claude/, .vscode/, shell configs) are
// bypass-immune — they must prompt even in bypassPermissions mode.
// checkPathSafetyForAutoEdit returns {type:'safetyCheck'} for these paths.
if (
  toolPermissionResult?.behavior === 'ask' &&
  toolPermissionResult.decisionReason?.type === 'safetyCheck'
) {
  return toolPermissionResult
}

// 2a. Check if mode allows the tool to run
// IMPORTANT: Call getAppState() to get the latest value
appState = context.getAppState()
// Check if permissions should be bypassed:
// - Direct bypassPermissions mode
// - Plan mode when the user originally started with bypass mode (isBypassPermissionsModeAvailable)
const shouldBypassPermissions =
  appState.toolPermissionContext.mode === 'bypassPermissions' ||
  (appState.toolPermissionContext.mode === 'plan' &&
    appState.toolPermissionContext.isBypassPermissionsModeAvailable)
if (shouldBypassPermissions) {
  return {
    behavior: 'allow',
    updatedInput: getUpdatedInputOrFallback(toolPermissionResult, input),
    decisionReason: {
      type: 'mode',
      mode: appState.toolPermissionContext.mode,
    },
  }
}
```

2. **Hook parity mirror — `checkRuleBasedPermissions` (`utils/permissions/permissions.ts:1071-1156`):** Mirrors **only steps `1a`, `1b`, `1c`, `1d`, `1f`, and `1g`**. Called solely by `resolveHookPermissionDecision` (`services/tools/toolHooks.ts:373-377`), it enforces the `inc-4788 analog` invariant (`services/tools/toolHooks.ts:324-325`): a `PreToolUse` hook's `'allow'` never overrides deny/ask rules or `safetyCheck`s.
3. **Outer wrapper — `hasPermissionsToUseTool` (`utils/permissions/permissions.ts:473-956`):** Ensures inner early returns cannot escape mode transforms (`utils/permissions/permissions.ts:504`). On inner `'allow'` in `auto` mode, it resets consecutive denials (`utils/permissions/permissions.ts:486-501`). On inner `'ask'`:
   - **`dontAsk` (`utils/permissions/permissions.ts:508-517`):** Converts `'ask'` to `'deny'`.
   - **`auto` / `plan`-with-auto (`utils/permissions/permissions.ts:520-927`, `feature('TRANSCRIPT_CLASSIFIER')`):** Runs **before** `shouldAvoidPermissionPrompts` for headless coverage: non-`classifierApprovable` `safetyCheck`, `requiresUserInteraction()`, PowerShell guard unless `feature('POWERSHELL_AUTO_MODE')`, and `acceptEdits` fast-path (excluding `Agent`/`REPL`, `utils/permissions/permissions.ts:596-603`).
     - Remaining actions check `isAutoModeAllowlistedTool`, then call `classifyYoloAction`, honoring `tengu_iron_gate_closed` and denial tracking.
   - **Headless / async (`shouldAvoidPermissionPrompts`, `utils/permissions/permissions.ts:932-952`):** Runs `runPermissionRequestHooksForHeadlessAgent` (`utils/permissions/permissions.ts:400-471`) before auto-denying as `{ type: 'asyncAgent' }`.

Because inner steps `1c` and `2b` return `'allow'` before the outer classifier executes, `utils/permissions/permissionSetup.ts` strips dangerous allow rules on auto-mode entry and restores them on exit:

- **Stripping & restoration (`utils/permissions/permissionSetup.ts:94-579`):** `isDangerousClassifierPermission` (`utils/permissions/permissionSetup.ts:272-285`) matches broad `Bash` (`DANGEROUS_BASH_PATTERNS`, 5 shapes: exact, `:*`, `*`, ` *`, ` -*`), `PowerShell` (`CROSS_PLATFORM_CODE_EXEC` + cmdlets, bare/`.exe`), all `Agent`/`Task` allows, and ant-only `Tmux`.
  - `stripDangerousPermissionsForAutoMode` (`utils/permissions/permissionSetup.ts:510-553`) stashes them in `strippedDangerousRules` (`{}` sentinel if empty); `restoreDangerousPermissions` replays them on exit.
- **Ant broad-shell strip (startup vs. reload):**
  - **Startup:** Under `USER_TYPE === 'ant'` outside `CLAUDE_CODE_REMOTE` and `CLAUDE_CODE_ENTRYPOINT === 'local-agent'`, `utils/permissions/permissionSetup.ts:953-965` detects overly broad `Bash` and `PowerShell` allows in all modes, which caller `main.tsx:1763-1768` strips via `removeDangerousPermissions`.
  - **Live settings reload:** `utils/settings/applySettingsChange.ts:51-59` re-strips overly broad `Bash` allows only, gated on `USER_TYPE === 'ant'` and `CLAUDE_CODE_ENTRYPOINT !== 'local-agent'` (with no `CLAUDE_CODE_REMOTE` check).
- **Centralized transitions (`utils/permissions/permissionSetup.ts:597-646`, `utils/permissions/permissionSetup.ts:1446-1532`):** `transitionPermissionMode` delegates plan entry to `prepareContextForPlanMode` and uses `autoModeStateModule.isAutoModeActive()` as the authoritative classifier signal:

```ts
// utils/permissions/permissionSetup.ts:617-637
// Plan with auto active counts as using the classifier (for the leaving side).
// isAutoModeActive() is the authoritative signal — prePlanMode/strippedDangerousRules
// are unreliable proxies because auto can be deactivated mid-plan (non-opt-in
// entry, transitionPlanAutoMode) while those fields remain set/unset.
const fromUsesClassifier =
  fromMode === 'auto' ||
  (fromMode === 'plan' &&
    (autoModeStateModule?.isAutoModeActive() ?? false))
const toUsesClassifier = toMode === 'auto' // plan entry handled above

if (toUsesClassifier && !fromUsesClassifier) {
  if (!isAutoModeGateEnabled()) {
    throw new Error('Cannot transition to auto mode: gate is not enabled')
  }
  autoModeStateModule?.setAutoModeActive(true)
  context = stripDangerousPermissionsForAutoMode(context)
} else if (fromUsesClassifier && !toUsesClassifier) {
  autoModeStateModule?.setAutoModeActive(false)
  setNeedsAutoModeExitAttachment(true)
  context = restoreDangerousPermissions(context)
}
```

- **CLI init:** `initialPermissionModeFromCLI` (`utils/permissions/permissionSetup.ts:689-811`) orders `--dangerously-skip-permissions` > `--permission-mode` > `defaultMode` (capped in `CLAUDE_CODE_REMOTE`) > `'default'`, using `NO_CACHED_AUTO_MODE_CONFIG` (`Symbol('no-cached-auto-mode-config')` at `utils/permissions/permissionSetup.ts:1335-1352`).
  - `initializeToolPermissionContext` (`utils/permissions/permissionSetup.ts:872-1033`) turns `--tools` exclusions into `cliArg` denies, adds symlinked `PWD` as `'session'`, and validates `--add-dir` in parallel.
- **Bypass killswitch:** GrowthBook `'tengu_disable_bypass_permissions_mode'` downgrades interactive sessions (`utils/permissions/bypassPermissionsKillswitch.ts:19-70`) but calls `gracefulShutdown(1)` headlessly (`utils/permissions/permissionSetup.ts:1411-1431`).
- **Update persistence & deletion:** `PermissionUpdate` (`types/permissions.ts:88-131`, `utils/permissions/PermissionUpdateSchema.ts:27-78`) persists via `persistPermissionUpdate` (`utils/permissions/PermissionUpdate.ts:208-342`) only to editable sources; `deletePermissionRule` (`utils/permissions/permissions.ts:1329-1370`) throws on read-only sources (`utils/permissions/permissions.ts:1334-1340`).

### Hidden Invariants & Production Scars

- **Closure-returning async killswitch (`utils/permissions/permissionSetup.ts:1078-1260`, `utils/permissions/bypassPermissionsKillswitch.ts:74-155`):** Under `feature('TRANSCRIPT_CLASSIFIER')` (`utils/permissions/bypassPermissionsKillswitch.ts:79`), `checkAndDisableAutoModeIfNeeded` awaits `verifyAutoModeGateAccess` (`tengu_auto_mode_config`, `modelSupportsAutoMode` at `utils/betas.ts:160-195`, `disableFastMode`).
  - Applying its returned `updateContext` closure inside `setAppState(prev => ...)` prevents stale awaits from clobbering a Shift+Tab while still evicting auto and defusing `prePlanMode` (`utils/permissions/permissionSetup.ts:1223`).
- **Untrusted `projectSettings` exclusion (`utils/permissions/permissionSetup.ts:1446-1455`, `utils/settings/settings.ts:896-928`):** `hasAutoModeOptIn()` and `getUseAutoModeDuringPlan()` ignore `projectSettings` so cloned repos cannot opt themselves into auto mode.
- **Stale-rule clearing & plan-mode reload re-strip:** `syncPermissionRulesFromDisk` (`utils/permissions/permissions.ts:1448-1470`) pre-clears all 3 behaviors across the 3 editable disk sources (`userSettings`, `projectSettings`, `localSettings` at `utils/permissions/permissions.ts:1453-1457`—not `flagSettings`/`policySettings`—plus `cliArg`/`session` under `allowManagedPermissionRulesOnly`, `utils/permissions/permissions.ts:1426-1446`) before `replaceRules` so deleting a last deny rule never lingers.
  - Next, `transitionPlanAutoMode` (`utils/settings/applySettingsChange.ts:68`, `utils/permissions/permissionSetup.ts:1502-1532`) re-strips dangerous allows during `plan` mode when plan-auto was already active (`utils/permissions/permissionSetup.ts:1516-1521`); guarded by `if (context.mode !== 'plan') return context` (`utils/permissions/permissionSetup.ts:1506`), it is a no-op outside `plan` mode (including direct `mode === 'auto'`).

---

## 3. Filesystem Path Validation, Symlinks, Working Directories, and Protected Paths

### The Problem

Path strings hide traps: `./data` may symlink to `/etc/cron.d/`, `./evil.txt` may be a dangling link targeting `~/.ssh/authorized_keys2`, Windows NTFS 8.3 short names (`GIT~1`) or trailing dots (`.git.`) evade naive checks, and `acceptEdits` must never let the model modify `.claude/settings.json` or `.git/hooks/*`.

### The Mechanism: Multi-Representation Containment and the Write-Safety Lattice

`getPathsForPermissionCheck(inputPath)` (`utils/fsOperations.ts:288-382`) expands each path into all security-relevant forms. `safeResolvePath` (`utils/fsOperations.ts:138-178`) short-circuits `//`/`\\` pre-syscall (stopping Windows NTLM leaks) and checks `lstatSync` so FIFOs/sockets/devices never hang `realpathSync`.

The walk follows symlinks up to `maxDepth = 40` (`visited` guard), appends canonical `realpathSync` (`/etc/passwd -> /private/etc/passwd`), and calls `resolveDeepestExistingAncestorSync` (`utils/fsOperations.ts:215-270`, `utils/fsOperations.ts:325-340`) so new files under live parent symlinks (`./data -> /etc/cron.d/`) and dangling links (`./evil.txt -> ~/.ssh/authorized_keys2`) expose their true target.

Negative checks (`deny`, `ask`, `checkPathSafetyForAutoEdit`) fail closed if **any** representation matches (`some`), whereas working-directory containment requires **every** representation to stay inside **some** symmetrically resolved root (`utils/permissions/filesystem.ts:683-707`):

```ts
// utils/permissions/filesystem.ts:683-707
export function pathInAllowedWorkingPath(
  path: string,
  toolPermissionContext: ToolPermissionContext,
  precomputedPathsToCheck?: readonly string[],
): boolean {
  // Check both the original path and the resolved symlink path
  const pathsToCheck =
    precomputedPathsToCheck ?? getPathsForPermissionCheck(path)

  // Resolve working directories the same way we resolve input paths so
  // comparisons are symmetric. Without this, a resolved input path
  // (e.g. /System/Volumes/Data/home/... on macOS) would not match an
  // unresolved working directory (/home/...), causing false denials.
  const workingPaths = Array.from(
    allWorkingDirectories(toolPermissionContext),
  ).flatMap(wp => getResolvedWorkingDirPaths(wp))

  // All paths must be within allowed working paths
  // If any resolved path is outside, deny access
  return pathsToCheck.every(pathToCheck =>
    workingPaths.some(workingPath =>
      pathInWorkingPath(pathToCheck, workingPath),
    ),
  )
}
```

- **`getOriginalCwd()` anchor & normalization:** `allWorkingDirectories` (`utils/permissions/filesystem.ts:667-674`), `isClaudeConfigFilePath` (`utils/permissions/filesystem.ts:225-242`), `getClaudeSkillScope`, and `rootPathForSource` anchor on startup `getOriginalCwd()`.
  - `pathInWorkingPath` (`utils/permissions/filesystem.ts:709-744`) expands via `expandPath`, normalizes `/private/var/` and `/private/tmp`, lowercases via `normalizeCaseForComparison`, and rejects `..`; `getResolvedWorkingDirPaths` + `precomputedPathsToCheck` avoid ~30 syscalls.
- **Gitignore prefix lattice (`utils/permissions/filesystem.ts:853-1025`):** `patternWithRoot` and `matchingRuleForInput` use `ignore` with tool collapse (`Edit` governs all writes; `Read` governs all reads) and `/**` stripping/back-mapping. Single `/` is **not** filesystem root:

| Rule Prefix | Anchored Root (`patternWithRoot`) | Meaning |
|---|---|---|
| `//path` | `/` (or `${drive}:\\` for Windows `//c/...`) | Absolute filesystem path (`createReadRuleSuggestion` emits `//path/**`, `utils/permissions/PermissionUpdate.ts:361-389`) |
| `~/path` | `homedir().normalize('NFC')` | Relative to user home directory |
| `/path` | `rootPathForSource(source)` (`utils/permissions/filesystem.ts:746-759`, delegating disk sources to `getSettingsRootPathForSource` at `utils/settings/settings.ts:239-253`) | Relative to **settings root** (`getOriginalCwd()`, `~/.claude`, or `dirname(--settings)`) |
| `path` or `./path` | `null` (matched against `getCwd()`) | Relative to current working directory (leading `./` stripped) |

- **Protected paths & auto-edit safety:** `DANGEROUS_FILES` (`utils/permissions/filesystem.ts:57-68`, 10 dotfiles: `.gitconfig`, `.gitmodules`, shell rc/profiles, `.ripgreprc`, `.mcp.json`, `.claude.json`) and `DANGEROUS_DIRECTORIES` (`utils/permissions/filesystem.ts:74-79`: `.git`, `.vscode`, `.idea`, `.claude`—carving out `.claude/worktrees/` at `utils/permissions/filesystem.ts:456-468`).
  - `isClaudeSettingsPath` (`utils/permissions/filesystem.ts:200-222`) matches `.claude/settings.json` and `.claude/settings.local.json` in *any* repo (plus active `getSettingsPaths()`); `isClaudeConfigFilePath` guards `.claude/{commands,agents,skills}`.
  1. `checkPathSafetyForAutoEdit` (`utils/permissions/filesystem.ts:620-665`) step 1 runs `hasSuspiciousWindowsPathPattern` (`utils/permissions/filesystem.ts:537-602`, favoring pattern detection over TOCTOU-prone `GetLongPathNameW`): NTFS ADS (`windows`/`wsl`), 8.3 names (`~\d`), `\\?\`/`//?/` prefixes, trailing dots/spaces, DOS device suffixes, `...` segments (keeping `[...slug]`), and UNC detection, returning `{ safe: false, classifierApprovable: false }`.
     - Its `containsVulnerableUncPath` check (`utils/shell/readOnlyCommandValidation.ts:1562-1638`) is **Windows-only** (`if (getPlatform() !== 'windows') return false` at `utils/shell/readOnlyCommandValidation.ts:1564-1566`).
  2. Steps 2–3 run `isClaudeConfigFilePath` (`utils/permissions/filesystem.ts:642-650`) and `isDangerousFilePathToAutoEdit` (`utils/permissions/filesystem.ts:653-661`), which also carries the explicit non-Windows write-side `//`/`\\` check (`utils/permissions/filesystem.ts:442-444`), returning `{ safe: false, classifierApprovable: true }` (bypass-immune to `bypassPermissions`/`acceptEdits`, reviewable by `auto`).
     - Pre-syscall and read-side non-Windows `//`/`\\` guards sit in `safeResolvePath` (`utils/fsOperations.ts:144-146`), `getPathsForPermissionCheck` (`utils/fsOperations.ts:306-308`), and `checkReadPermissionForTool` (`utils/permissions/filesystem.ts:1053-1064`).
- **Read/Write precedence & internal carve-outs:**
  - `checkReadPermissionForTool` (`utils/permissions/filesystem.ts:1030-1194`): UNC -> suspicious Windows -> Read `deny` -> Read `ask` -> **Edit implies Read** -> `pathInAllowedWorkingPath` -> `checkReadableInternalPath` -> Read `allow` -> `ask` (`getFileReadIgnorePatterns` hides Read-denied paths from `GlobTool`/`GrepTool`).
  - `checkWritePermissionForTool` (`utils/permissions/filesystem.ts:1205-1412`): Edit `deny` -> **1.5** `checkEditableInternalPath` (ahead of safety checks since plans/memory live in `.claude/`) -> **1.6** session-only `.claude/**` / `~/.claude/**` allow rules (`utils/permissions/filesystem.ts:1252-1300`, rejecting `..`, paired with `getClaudeSkillScope`) -> **1.7** `checkPathSafetyForAutoEdit` (beats `acceptEdits` and permanent `Edit` allows) -> Edit `ask` -> `acceptEdits` -> Edit `allow` -> `ask`.
  - **Editable (`utils/permissions/filesystem.ts:1479-1605`, 6 paths):** plans, `tengu_scratch` scratchpad, `feature('TEMPLATES')` `CLAUDE_JOB_DIR` (hijack/symlink guards; `utils/permissions/filesystem.ts:1511-1513` notes absent `jobs/state`), agent memory (`CLAUDE_CODE_REMOTE_MEMORY_DIR`), auto-memory (`!hasAutoMemPathOverride() && isAutoMemPath`, disabled by `CLAUDE_COWORK_MEMORY_PATH_OVERRIDE`; `memdir/paths.ts:172-186` excludes `projectSettings`), and `<origCwd>/.claude/launch.json`.
  - **Readable (`utils/permissions/filesystem.ts:1611-1777`, 11 paths):** session memory, tool results, `CLAUDE_CODE_TMPDIR` temp dirs, tasks/teams, and `getBundledSkillsRoot()` (`utils/permissions/filesystem.ts:350-370`: `{claudeTempDir}/bundled-skills/{MACRO.VERSION}/{128-bit nonce}` stopping `/tmp` squatting).
- **Shell TOCTOU & sandbox allowlist (`utils/permissions/pathValidation.ts:101-485`):** `validatePath` expands only `~`/`~/`/`~\`, rejects UNC, unexpanded `~root`/`~+`, shell expansions (`$`, `%`, leading `=`), and write globs (`GLOB_PATTERN_REGEX`), delegates read globs to `validateGlobPattern`, and passes `isCanonical ? [resolvedPath] : undefined` into `isPathAllowed` (no Step 1.6 `.claude/**`).
  - Step 3.7 (`utils/permissions/pathValidation.ts:233-245`) honors `isPathInSandboxWriteAllowlist` (`utils/permissions/pathValidation.ts:101-123`, symmetrically resolving `allowOnly` and `denyWithinAllow`) **strictly when `!isInWorkingDir`**—otherwise `sandbox-adapter.ts` seeding `'.'` into `allowOnly` would bypass `acceptEdits` inside cwd.
  - `isDangerousRemovalPath` (`utils/permissions/pathValidation.ts:331-367`) blocks `*`, `/*`, `/`, drive roots, `homedir()`, and direct children of `/` or a drive root.

### Hidden Invariants & Production Scars

- **Auto-mode downgrade guard (`utils/permissions/filesystem.ts:1439-1446`):** `generateSuggestions` emits `{ type: 'setMode', mode: 'acceptEdits' }` only in `'default'` or `'plan'`—never `'auto'` or `'bypassPermissions'`—so SDK hosts cannot silently downgrade `'auto'`.
- **Lexical allow vs. expanded deny/ask (`utils/permissions/filesystem.ts:1161`, `utils/permissions/filesystem.ts:1378`, `utils/permissions/filesystem.ts:1428-1463`):** Deny, ask, and safety checks iterate all `pathsToCheck`, whereas `allow` lookups match lexical `path`. Hence `generateSuggestions` emits rules/directories covering **both** the symlink and resolved target.

---

## 4. Shell Wildcard Rule Matching and Dangerous Command Patterns

### The Problem

Users need both legacy prefix rules (`Bash(git:*)`) and modern wildcards (`Bash(git *)`, `Bash(* --version)`), across multiline heredocs and case-insensitive PowerShell. Meanwhile, `auto` mode needs an exact list of interpreter and runner prefixes to strip without touching safe commands.

### The Mechanism: Three-Kind Rule Parsing, Sentinel Escaping, and Dangerous Prefixes

`parsePermissionRule` (`utils/permissions/shellRuleMatching.ts:159-184`) classifies every shell rule into `ShellPermissionRule` (`utils/permissions/shellRuleMatching.ts:25-37`): `prefix` via `permissionRuleExtractPrefix` (`/^(.+):\*$/`), `wildcard` via `hasWildcards` (unescaped `*` by backslash parity), or fallback `exact`.

`matchWildcardPattern(pattern, command, caseInsensitive = false)` (`utils/permissions/shellRuleMatching.ts:90-154`) swaps `\*`/`\\` for null-byte placeholders, escapes regex metacharacters, converts `*` to `.*`, restores placeholders, aligns single trailing ` *` with `:*`, and compiles with `'s'` (dotAll):

```ts
// utils/permissions/shellRuleMatching.ts:142-153
const unescapedStarCount = (processed.match(/\*/g) || []).length
if (regexPattern.endsWith(' .*') && unescapedStarCount === 1) {
  regexPattern = regexPattern.slice(0, -3) + '( .*)?'
}

// Create regex that matches the entire string.
// The 's' (dotAll) flag makes '.' match newlines, so wildcards match
// commands containing embedded newlines (e.g. heredoc content after splitCommand_DEPRECATED).
const flags = 's' + (caseInsensitive ? 'i' : '')
const regex = new RegExp(`^${regexPattern}$`, flags)

return regex.test(command)
```

- **Word boundaries & shell case sensitivity:** `'git *'` compiles to `^git( .*)?$` (rejecting `'gitconfig'`), whereas `'git*'` compiles to `^git.*$`. `BashTool` uses `caseInsensitive = false` (`tools/BashTool/bashPermissions.ts:353-358`); `PowerShellTool` uses `true` (`tools/PowerShellTool/powershellPermissions.ts:243`).
- **Workspace tool reuse:** Five workspace tools reuse `matchWildcardPattern` for `preparePermissionMatcher`: `FileReadTool` (`tools/FileReadTool/FileReadTool.ts:395-397`), `FileEditTool` (`tools/FileEditTool/FileEditTool.ts:122-124`), `FileWriteTool` (`tools/FileWriteTool/FileWriteTool.ts:132-134`), `GlobTool` (`tools/GlobTool/GlobTool.ts:91-93`), and `GrepTool` (`tools/GrepTool/GrepTool.ts:198-200`).
- **Dangerous prefixes (`utils/permissions/dangerousPatterns.ts:18-80`):** Exports `CROSS_PLATFORM_CODE_EXEC` (19 interpreters/runners/shells/`ssh`) and `DANGEROUS_BASH_PATTERNS` (26 external plus 11 `USER_TYPE === 'ant'` entries including `gh`, `gh api`, `curl`, `wget`, `git`, `kubectl`, `aws`, `gcloud`, `gsutil`). Distinct multi-word entries (`'gh'` and `'gh api'`) are needed because `utils/permissions/permissionSetup.ts:117-146` tests fixed 5-shape forms.

### Hidden Invariants & Production Scars

- **The `\*`-only dead-rule scar (`tools/PowerShellTool/powershellPermissions.ts:143-155`):** Escaping a literal `*` to `\*` with no other wildcard makes `hasWildcards()` return `false`, routing it to `{ type: 'exact' }` with the backslash intact—a dead rule that never matches. PowerShell skips exact suggestions containing `*` or `\n`.

---

## 5. The Auto-Mode Security Classifier and Denial Circuit Breaker

### The Problem

In `auto` mode (and auto-backed `plan`), unallowlisted mutations outside `acceptEdits` go to an LLM classifier. Three hazards dominate: prompt injection via `tool_result` data or assistant prose, latency/false-positive tradeoffs, and runaway denial loops during outages or repeated blocks.

### The Mechanism: Sanitized Transcripts, Two-Stage XML, and Bounded Denials

`utils/permissions/yoloClassifier.ts` (1,495 lines) runs auto-mode classification under `feature('TRANSCRIPT_CLASSIFIER')`:

1. **Absent `.txt` templates & `<user_*_to_replace>` (`utils/permissions/yoloClassifier.ts:54-142`):** Module load requires `auto_mode_system_prompt.txt`, `permissions_external.txt`, and ant-only `permissions_anthropic.txt` (`utils/permissions/yoloClassifier.ts:55`, `utils/permissions/yoloClassifier.ts:62`, `utils/permissions/yoloClassifier.ts:67`)—**all three are absent from this snapshot**.
   - `EXTERNAL_PERMISSIONS_TEMPLATE` loads in all `feature('TRANSCRIPT_CLASSIFIER')` builds—**even** in ant builds (`utils/permissions/yoloClassifier.ts:58-63`, consumed by `cli/handlers/autoMode.ts:25`), and `isUsingExternalPermissions()` honors `tengu_auto_mode_config.forceExternalPermissions`.
   - Regexes and comments in `buildYoloSystemPrompt` show `settings.autoMode` (`allow`, `soft_deny`, `environment`) fills `<user_allow_rules_to_replace>`, `<user_deny_rules_to_replace>`, and `<user_environment_to_replace>`: external defaults sit *inside* those tags (user rules **replace** them), while Anthropic defaults sit *outside* empty tags (user rules are **additive**, `utils/permissions/yoloClassifier.ts:511-540`).
   - Ant builds prepend `feature('BASH_CLASSIFIER')` descriptions (stubbed to `[]` in external `utils/permissions/bashClassifier.ts:28-38`) and `feature('POWERSHELL_AUTO_MODE')` `POWERSHELL_DENY_GUIDANCE` (`utils/permissions/yoloClassifier.ts:1402-1411`, guarding `iex`, `Remove-Item -Recurse -Force`, `$PROFILE` persistence, and AMSI bypasses).
2. **Prompt-injection-hardened transcript (`utils/permissions/yoloClassifier.ts:302-477`, `utils/permissions/yoloClassifier.ts:1019-1106`):**
   - `buildClaudeMdMessage()` (`utils/permissions/yoloClassifier.ts:460-477`) reads `getCachedClaudeMdContent()` (`bootstrap/state.ts:1211-1213`) into a cached `<user_claude_md>` prefix, breaking the 4-hop `claudemd -> filesystem -> permissions -> yoloClassifier` cycle ([Chapter 04](04-prompt-engineering-and-cache-boundaries.md), [Chapter 10](10-memory-systems-claudemd-auto-memory-and-dream.md)).
   - `buildTranscriptEntries` (`utils/permissions/yoloClassifier.ts:302-360`) keeps queued commands, user `text`, and assistant `tool_use` blocks—**stripping all `tool_result` outputs and assistant prose/thinking**. `buildTranscriptForClassifier` (`utils/permissions/yoloClassifier.ts:434-442`) also serves subagent handoffs (`tools/AgentTool/agentToolUtils.ts:407`).
   - `toCompactBlock` projects `tool_use` via `tool.toAutoClassifierInput(input)` inside `try/catch`; empty `''` returns `{ shouldBlock: false }` immediately (`utils/permissions/yoloClassifier.ts:1023-1029`) to prevent API 400s on empty cached blocks. Ant-only `CLAUDE_CODE_JSONL_TRANSCRIPT` or `tengu_auto_mode_config.jsonlTranscript` enables JSONL framing (`{"user":"..."}\n`) against newline turn spoofing.
   - **No local truncation & 3-breakpoint cache (`utils/permissions/yoloClassifier.ts:1068-1106`, `utils/permissions/yoloClassifier.ts:1463-1471`):** Relies on projection shrinkage and [Chapter 09](09-five-layer-compaction-pipeline.md) auto-compact (`detectPromptTooLong` catches 400s). Breakpoints on system, optional `CLAUDE.md`, and the action block stay within 3 breakpoints so Stage 2 hits warm cache.
3. **Two-stage XML vs. `classify_result` (`utils/permissions/yoloClassifier.ts:550-996`, `utils/permissions/classifierShared.ts:15-39`):** Controlled by ant-only `CLAUDE_CODE_TWO_STAGE_CLASSIFIER` or `tengu_auto_mode_config.twoStageClassifier`. Off forces `classify_result` `tool_use`; on runs `classifyYoloActionXml` (`'both'` default), escalating `'yes'` or unparseable Stage 1 verdicts (`XML_S1_SUFFIX`, `max_tokens: 64 + thinkingPadding`, `stop_sequences: ['</block>']`) to Stage 2.
   - Stage 2 runs CoT with `XML_S2_SUFFIX` and `max_tokens: 4096 + thinkingPadding` (`utils/permissions/yoloClassifier.ts:868`); `twoStageClassifier` also supports single-stage `'fast'` (`256 + thinkingPadding`, no `stop_sequences`, `utils/permissions/yoloClassifier.ts:781-792`) and `'thinking'` (`utils/permissions/yoloClassifier.ts:703-706`, `utils/permissions/yoloClassifier.ts:1316`). `stripThinking` strips `<thinking>` before matching `<block>`/`<reason>`:

```ts
// utils/permissions/yoloClassifier.ts:567-584
function stripThinking(text: string): string {
  return text
    .replace(/<thinking>[\s\S]*?<\/thinking>/g, '')
    .replace(/<thinking>[\s\S]*$/, '')
}

/**
 * Parse XML block response: <block>yes/no</block>
 * Strips thinking content first to avoid matching tags inside reasoning.
 * Returns true for "yes" (should block), false for "no", null if unparseable.
 */
function parseXmlBlock(text: string): boolean | null {
  const matches = [
    ...stripThinking(text).matchAll(/<block>(yes|no)\b(<\/block>)?/gi),
  ]
  if (matches.length === 0) return null
  return matches[0]![1]!.toLowerCase() === 'yes'
}
```

4. **Allowlist, DCE state & fail-closed denial circuit breaker:** `SAFE_YOLO_ALLOWLISTED_TOOLS` (`utils/permissions/classifierDecision.ts:56-98`) allowlists **22** unconditional tools (7 read/search, 7 task, 3 plan/UI, 3 swarm, `SLEEP_TOOL_NAME`, and `YOLO_CLASSIFIER_TOOL_NAME`) plus **4** gated **snapshot-absent** constants (`= 26` total); `utils/permissions/autoModeState.ts:1-39` isolates `autoModeActive`, `autoModeFlagCli`, and `autoModeCircuitBroken` behind `feature('TRANSCRIPT_CLASSIFIER')`.
   - **Gated snapshot-absent allowlist constants (`utils/permissions/classifierDecision.ts:27-47`):** `TerminalCaptureTool` (`feature('TERMINAL_PANEL')`, `utils/permissions/classifierDecision.ts:27-31`), `OverflowTestTool` (`feature('OVERFLOW_TEST_TOOL')`, `utils/permissions/classifierDecision.ts:32-36`), `VerifyPlanExecutionTool` (`process.env.USER_TYPE === 'ant'`, `utils/permissions/classifierDecision.ts:37-42`), and `WorkflowTool` (`feature('WORKFLOW_SCRIPTS')`, `utils/permissions/classifierDecision.ts:43-47`).
   - **Fail-closed outcomes (`utils/permissions/permissions.ts:818-1058`):** Parse errors always block; Stage-2 throws after Stage-1 escalation keep `unavailable: false` (`utils/permissions/yoloClassifier.ts:977-983`). `transcriptTooLong` aborts headless and asks interactively; `unavailable` checks `tengu_iron_gate_closed` (default `true`, 30 min TTL at `utils/permissions/permissions.ts:107`) to fail closed (`'deny'`) without tripping denial counters.
   - **Denial circuit breaker (`utils/permissions/denialTracking.ts:12-45`):** Caps blocks at `DENIAL_LIMITS` (`maxConsecutive: 3`, `maxTotal: 20`). `recordSuccess` preserves object identity at `0` so React skips redundant renders (`utils/permissions/permissions.ts:974`):

```ts
// utils/permissions/denialTracking.ts:32-45
export function recordSuccess(state: DenialTrackingState): DenialTrackingState {
  if (state.consecutiveDenials === 0) return state // No change needed
  return {
    ...state,
    consecutiveDenials: 0,
  }
}

export function shouldFallbackToPrompting(state: DenialTrackingState): boolean {
  return (
    state.consecutiveDenials >= DENIAL_LIMITS.maxConsecutive ||
    state.totalDenials >= DENIAL_LIMITS.maxTotal
  )
}
```

   When `shouldFallbackToPrompting` trips (`utils/permissions/permissions.ts:984-1058`), headless agents throw `AbortError`, whereas interactive sessions reset counts on `hitTotalLimit` (`utils/permissions/permissions.ts:1034-1040`) and return `'ask'` to open the human dialog.

### Hidden Invariants & Production Scars

- **`alwaysOnThinking` tuple scar (`utils/permissions/yoloClassifier.ts:666-693`, `utils/model/antModels.ts:51-64`):** Models flagged `alwaysOnThinking` in `tengu_ant_model_override` reject `thinking: false` with HTTP 400. `getClassifierThinkingConfig` returns tuple `[undefined, 2048]` (avoiding leaked property names), keeping thinking enabled and padding `max_tokens` by 2,048 above Stage 1's 64-token cap.
- **In-place `localDenialTracking` (`utils/forkedAgent.ts:418-422`, `utils/permissions/permissions.ts:963-1004`):** Forked agents have a no-op `setAppState`; `persistDenialState` mutates `localDenialTracking` via `Object.assign`, so `handleDenialLimitExceeded` snapshots counts *before* resetting.
- **Model selection, `sideQuery` & dumps:** `getClassifierModel` (`utils/permissions/yoloClassifier.ts:1334-1347`) resolves ant-only `CLAUDE_CODE_AUTO_MODE_MODEL` > `tengu_auto_mode_config.model` > `getMainLoopModel()`. `sideQuery` retries 429/5xx without mutating session cost (`utils/permissions/permissions.ts:765-766`); errors dump to `<claudeTempDir>/auto-mode-classifier-errors/<sessionId>.txt`, and ant `CLAUDE_CODE_DUMP_AUTO_MODE` dumps `.req.json`/`.res.json`.

---

## 6. Interactive, Coordinator, and Swarm Permission Handlers

### The Problem

Once `hasPermissionsToUseTool` emits `'ask'`, up to five concurrent sources can answer: the local terminal user, a remote web bridge, an MCP channel, a `PermissionRequest` hook, or a background bash classifier. Because `onAllow` awaits disk persistence and `recheckPermission` awaits re-evaluation, a single `resolved` boolean permits double-resolution races.

### The Mechanism: Four-Tier Waterfall and Two-Phase `claim()` Locking

`hooks/useCanUseTool.tsx` (204 lines; React-Compiler-compiled `.tsx` with `_c(3)` slots and inline source map on line `204`) wraps `hasPermissionsToUseTool` with `createPermissionContext` (`hooks/toolPermission/PermissionContext.ts:96-348`), guarding async boundaries via `ctx.resolveIfAborted(resolve)` (`hooks/useCanUseTool.tsx:34`, `hooks/useCanUseTool.tsx:110`) and clearing `clearClassifierChecking` in `.finally`.

- On `'allow'` (`hooks/useCanUseTool.tsx:39-54`): records `setYoloClassifierApproval` (`hooks/useCanUseTool.tsx:43-45`, `utils/classifierApprovals.ts:41-49`) only under `feature('TRANSCRIPT_CLASSIFIER')` for `auto-mode` classifier allows, logs `accept`/`config`, and resolves.
- On `'deny'` (`hooks/useCanUseTool.tsx:65-92`): logs `reject`/`config`, and—only under `feature('TRANSCRIPT_CLASSIFIER')` for `auto-mode` classifier denies (`hooks/useCanUseTool.tsx:77-89`)—appends to the 20-entry `recordAutoModeDenial` ring buffer (`utils/autoModeDenials.ts:19-22`) and posts an error toast.
- On `'ask'` (`hooks/useCanUseTool.tsx:93-169`), executes a **four-tier waterfall**:
  1. **Coordinator worker (`hooks/toolPermission/handlers/coordinatorHandler.ts:26-62`):** When `awaitAutomatedChecksBeforeDialog` is true, awaits `ctx.runHooks` then `feature('BASH_CLASSIFIER') ? ctx.tryClassifier : null` before interrupting the user.
  2. **Swarm worker (`hooks/toolPermission/handlers/swarmWorkerHandler.ts:40-156`):** Active under `isAgentSwarmsEnabled()` (`utils/agentSwarmsEnabled.ts:24-44`: `USER_TYPE === 'ant'`, or `--agent-teams` / `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` + `tengu_amber_flint`) and `isSwarmWorker()`.
     - Tries `feature('BASH_CLASSIFIER')` `ctx.tryClassifier` (`hooks/toolPermission/handlers/swarmWorkerHandler.ts:52-57`) before registering `registerPermissionCallback` ahead of `sendPermissionRequestViaMailbox` (`hooks/toolPermission/handlers/swarmWorkerHandler.ts:81-123`) to prevent leader-reply races. *(Forward seam to Chapter 19.)*
  3. **2-second speculative bash grace period (`hooks/useCanUseTool.tsx:126-159`, `feature('BASH_CLASSIFIER')`):** Peeks `peekSpeculativeClassifierCheck(command)` (`tools/BashTool/bashPermissions.ts:1491-1495`) against a 2,000 ms timeout; a high-confidence hit skips the modal. (External `utils/permissions/bashClassifier.ts:1-61` is a stub, though plumbing stays wired.)
  4. **Five-racer modal (`hooks/toolPermission/handlers/interactiveHandler.ts:57-531`):** Races local UI (200 ms `GRACE_PERIOD_MS`, `onAllow` calling `persistPermissionUpdates`, `recheckPermission`), CCR bridge (`feature('BRIDGE_MODE')`, `hooks/useCanUseTool.tsx:165`), KAIROS MCP relay (`feature('KAIROS') || feature('KAIROS_CHANNELS')`), background `PermissionRequest` hooks, and background `BASH_CLASSIFIER`.
     - `checkmarkAbortHandler` (`hooks/toolPermission/handlers/interactiveHandler.ts:498-520`) reconciles [Chapter 06](06-executing-tools.md)'s `siblingAbortController` when a sibling aborts while the modal is open.

All five racers coordinate through `createResolveOnce` (`hooks/toolPermission/PermissionContext.ts:75-94`), separating synchronous ownership acquisition (`claim()`) from promise delivery (`resolve()`):

```ts
// hooks/toolPermission/PermissionContext.ts:75-94
function createResolveOnce<T>(resolve: (value: T) => void): ResolveOnce<T> {
  let claimed = false
  let delivered = false
  return {
    resolve(value: T) {
      if (delivered) return
      delivered = true
      claimed = true
      resolve(value)
    },
    isResolved() {
      return claimed
    },
    claim() {
      if (claimed) return false
      claimed = true
      return true
    },
  }
}
```

### Hidden Invariants & Production Scars

- **Telemetry dedup:** `hooks/toolPermission/permissionLogging.ts:181-235` populates `toolUseContext.toolDecisions` so `services/tools/toolExecution.ts:952-966` ([Chapter 06](06-executing-tools.md)) skips duplicate OTel logging.
- **`permissionDenials` ownership (interactive vs. headless/SDK):** `hooks/useCanUseTool.tsx` is mounted exclusively in interactive `screens/REPL.tsx:2382` and does **not** track SDK `permissionDenials`; on headless/SDK paths (`cli/print.ts:91`, `QueryEngine.ts:1249`), `QueryEngine.ts:244-271` wraps `canUseTool` in `wrappedCanUseTool` and pushes every `result.behavior !== 'allow'` onto `this.permissionDenials` (`QueryEngine.ts:631`, `QueryEngine.ts:863`, `QueryEngine.ts:1148`).

> [!NOTE]
> **Snapshot Absences & Build Gates in Chapter 11:** `types/permissions.ts` (441 lines) and `utils/model/antModels.ts` (64 lines) are **present**. Five type-only imports reference absent `types/message.ts` (`hooks/useCanUseTool.tsx:13`, `hooks/toolPermission/PermissionContext.ts:16`, `utils/permissions/permissions.ts:14`, `utils/permissions/yoloClassifier.ts:20`, `utils/permissions/permissionExplainer.ts:4`).
>
> Eight other targets are **absent from this snapshot** (call-site/comment evidence only): the 3 `.txt` prompts in `utils/permissions/yolo-classifier-prompts/` (`utils/permissions/yoloClassifier.ts:55`, `utils/permissions/yoloClassifier.ts:62`, `utils/permissions/yoloClassifier.ts:67`), comment-referenced `jobs/state` (`utils/permissions/filesystem.ts:1511-1513`), and 4 gated allowlist constants (`utils/permissions/classifierDecision.ts:27-47`):
> - `TerminalCaptureTool` (`feature('TERMINAL_PANEL')`, `utils/permissions/classifierDecision.ts:27-31`), `OverflowTestTool` (`feature('OVERFLOW_TEST_TOOL')`, `utils/permissions/classifierDecision.ts:32-36`), `VerifyPlanExecutionTool` (`process.env.USER_TYPE === 'ant'`, `utils/permissions/classifierDecision.ts:37-42`), and `WorkflowTool` (`feature('WORKFLOW_SCRIPTS')`, `utils/permissions/classifierDecision.ts:43-47`).

---

## Putting the Layer Together

```text
runToolUse (Ch 06) -> resolveHookPermissionDecision -> canUseTool
   |   [PreToolUse hook allow -> checkRuleBasedPermissions (1a-1d, 1f-1g)]
   v
hasPermissionsToUseToolInner (utils/permissions/permissions.ts:1158-1319)
  1a Blanket deny | 1b Blanket ask (Bash sandbox bypass) | 1c checkPermissions
  1d Tool deny | 1e requiresUserInteraction | 1f Content ask | 1g safetyCheck
  ------------------ BYPASS-IMMUNE BOUNDARY (1a..1g) --------------------------
  2a Fresh getAppState(): bypassPermissions / plan+bypass -> ALLOW
  2b Blanket allow (stripped on auto entry!) -> ALLOW | 3 passthrough -> ASK
   |
   v
hasPermissionsToUseTool outer wrapper (utils/permissions/permissions.ts:473)
  - dontAsk -> DENY | auto / plan+auto -> safetyCheck | PS guard | acceptEdits
    fast-path (no Agent/REPL) | allowlist | yoloClassifier (S1->S2 XML/tool)
    -> tengu_iron_gate_closed (fail-closed) | denialTracking (3 consec / 20)
  - shouldAvoidPermissionPrompts -> headless PermissionRequest hooks -> DENY
   |  (if ASK)
   v
useCanUseTool.tsx 4-tier waterfall -> interactiveHandler (5 racers + claim())
  -> persistPermissionUpdates (user/project/localSettings) + apply to AppState
```

```mermaid
flowchart TD
    EXEC["Ch 06: runToolUse() & toolHooks.ts"]
    QE["Ch 08: QueryEngine wrappedCanUseTool (permissionDenials)"]
    INNER["permissions.ts: hasPermissionsToUseToolInner (1a-3)"]
    TOOLS["Tool.checkPermissions(): filesystem.ts / pathValidation.ts / shellRuleMatching.ts"]
    OUTER["permissions.ts: hasPermissionsToUseTool (dontAsk / auto / headless)"]
    SETUP["permissionSetup.ts: strip & restore dangerous rules + transitions"]
    YOLO["yoloClassifier.ts: S1->S2 XML + cachedClaudeMdContent (Ch 10)"]
    DENIAL["denialTracking.ts: maxConsecutive 3 / maxTotal 20"]
    HOOK["useCanUseTool.tsx: coordinator / swarm / 2s bash / interactiveHandler (claim)"]
    PERSIST["PermissionUpdate.ts & permissionsLoader.ts (3 disk sources + sync)"]
    EXEC -->|"checkRuleBasedPermissions() on hook allow"| INNER
    EXEC -->|"interactive REPL"| HOOK
    EXEC -->|"headless / SDK"| QE
    HOOK --> OUTER
    QE --> OUTER
    OUTER --> INNER
    INNER --> TOOLS
    OUTER -->|"auto / plan+auto"| YOLO
    YOLO --> DENIAL
    DENIAL -->|"limit exceeded (interactive)"| HOOK
    SETUP <-->|"strippedDangerousRules"| PERSIST
    HOOK -->|"onAllow + persistPermissionUpdates()"| PERSIST
```

---

## How This Snaps Into the Next Layer

Chapter 11 built the generic policy engine; [Chapter 12: Shell Execution, Sandboxing, and Core Workspace Tools](12-shell-execution-sandboxing-and-workspace-tools.md) plugs concrete tools and OS-level isolation directly into these primitives:

- **Shell permission evaluators:** [`tools/BashTool/bashPermissions.ts`](../../tools/BashTool/bashPermissions.ts) (called from `tools/BashTool/BashTool.tsx:540`) consumes `getRuleByContentsForTool`, `createPermissionRequestMessage`, `parsePermissionRule`, and `matchWildcardPattern`.
  - It also owns `speculativeChecks` (`tools/BashTool/bashPermissions.ts:1483-1545`) consumed back by `hooks/useCanUseTool.tsx`, and pairs with `tools/BashTool/pathValidation.ts` (`allWorkingDirectories`, `validatePath`, `isDangerousRemovalPath`).
- **PowerShell evaluator:** [`tools/PowerShellTool/powershellPermissions.ts`](../../tools/PowerShellTool/powershellPermissions.ts) (called from `tools/PowerShellTool/PowerShellTool.tsx:376`) mirrors Bash with case-insensitive `matchWildcardPattern`, `tools/PowerShellTool/pathValidation.ts`, and `utils/powershell/dangerousCmdlets.ts` (`CROSS_PLATFORM_CODE_EXEC`).
- **Workspace file tools (both `checkPermissions()` & `preparePermissionMatcher()`):** [`tools/FileReadTool/FileReadTool.ts`](../../tools/FileReadTool/FileReadTool.ts) (`tools/FileReadTool/FileReadTool.ts:395-405`), [`tools/FileEditTool/FileEditTool.ts`](../../tools/FileEditTool/FileEditTool.ts) (`tools/FileEditTool/FileEditTool.ts:122-132`), and [`tools/FileWriteTool/FileWriteTool.ts`](../../tools/FileWriteTool/FileWriteTool.ts) (`tools/FileWriteTool/FileWriteTool.ts:132-142`), plus `GlobTool` and `GrepTool`.
  - These five delegate `checkPermissions()` to `checkReadPermissionForTool` / `checkWritePermissionForTool` and `preparePermissionMatcher()` to `matchWildcardPattern`; by contrast, `LSPTool` (`tools/LSPTool/LSPTool.ts:210-217`) and `NotebookEditTool` (`tools/NotebookEditTool/NotebookEditTool.ts:125-132`) delegate `checkPermissions()` only (neither implements `preparePermissionMatcher()`).
- **OS sandbox boundary & cycle breaker ([`utils/sandbox/sandbox-adapter.ts`](../../utils/sandbox/sandbox-adapter.ts)):** `SandboxManager` imports `getClaudeTempDir` (`utils/sandbox/sandbox-adapter.ts:57`) and translates Ch 11 `Edit`/`Read` rules via `resolvePathPatternForSandbox` (`utils/sandbox/sandbox-adapter.ts:99-119`, invoked across the rule-conversion loop at `utils/sandbox/sandbox-adapter.ts:304-349`).
  - It locally duplicates `permissionRuleValueFromString` and `permissionRuleExtractPrefix` (`utils/sandbox/sandbox-adapter.ts:61-81`) to break the `permissions.ts -> SandboxManager -> bashPermissions.ts -> permissions.ts` cycle.

---

## Reading Exercises & Code Checkpoints

1. **Trace mode unions, all 8 rule sources, and auto-mode rule stripping:**
   Run `rg -n "EXTERNAL_PERMISSION_MODES|PERMISSION_RULE_SOURCES|stripDangerousPermissionsForAutoMode" types/permissions.ts utils/permissions/permissions.ts utils/permissions/permissionSetup.ts` and verify why `stripDangerousPermissionsForAutoMode` mirrors `isPermissionUpdateDestination` when populating `strippedDangerousRules`.
2. **Inspect protected dotfiles, auto-edit safety, and shell wildcard compilation:**
   Run `rg -n "DANGEROUS_FILES|DANGEROUS_DIRECTORIES|checkPathSafetyForAutoEdit|matchWildcardPattern" utils/permissions/filesystem.ts utils/permissions/pathValidation.ts utils/permissions/shellRuleMatching.ts` and trace why `checkPathSafetyForAutoEdit` returns `classifierApprovable: false` only for `hasSuspiciousWindowsPathPattern`.
3. **Verify two-stage XML prompts, fail-closed `tengu_iron_gate_closed`, and denial limits:**
   Run `rg -n "DENIAL_LIMITS|shouldFallbackToPrompting|tengu_iron_gate_closed|user_allow_rules_to_replace|XML_S1_SUFFIX|XML_S2_SUFFIX" utils/permissions/yoloClassifier.ts utils/permissions/denialTracking.ts utils/permissions/permissions.ts` and confirm why `transcriptTooLong` bypasses `tengu_iron_gate_closed` while `unavailable` honors it.
4. **Check the two-phase `claim()` racer lock and the Ch 11 -> Ch 12 sandbox cycle breaker:**
   Run `rg -n 'createResolveOnce|if \(!claim\(\)\)|Local copies to avoid circular dependency' hooks/toolPermission/ utils/sandbox/sandbox-adapter.ts` and trace what breaks if `onAllow` checks `isResolved()` without first calling `claim()` synchronously before `await`.


---

<!-- chapters/12-shell-execution-sandboxing-and-workspace-tools.md — https://reverseengineeringclaudecode.com/chapters/12-shell-execution-sandboxing-and-workspace-tools -->

# Chapter 12 — Shell Execution, Sandboxing, and Core Workspace Tools

> **Layer:** Layer 4 (Safety, Policy, Sandbox & Lifecycle Hooks)
> **Prerequisites:** [Chapter 01](01-atoms-types-stores-and-primitives.md) (`FileStateCache`), [Chapter 02](02-the-tool-contract.md) (`Tool`, `ToolUseContext`), [Chapter 04](04-prompt-engineering-and-cache-boundaries.md) (prompt-cache stability), [Chapter 06](06-executing-tools.md) (`StreamingToolExecutor`), [Chapter 08](08-session-envelope-query-engine-and-transcripts.md) (`utils/fileHistory.ts`), and [Chapter 11](11-the-permission-engine.md) (modes, rule sources, `useCanUseTool`)
> **Primary Source Files:**
> - [`tools/BashTool/`](../../tools/BashTool/) — `BashTool.tsx`, AST/legacy permissions, security, read-only, path, `sed`, mode, exit-code, and sandbox gating (18 files, 12,414 lines)
> - [`tools/PowerShellTool/`](../../tools/PowerShellTool/) — comparative PowerShell tool, native AST permissions, 24 security validators, and CLM allowlist (14 files, 8,961 lines)
> - [`tools/FileReadTool/`](../../tools/FileReadTool/) — zero-I/O validation, two-tier byte/token caps, multi-modal dispatch, and `FILE_UNCHANGED_STUB` dedup (5 files, 1,603 lines)
> - [`tools/FileEditTool/`](../../tools/FileEditTool/) — two-phase TOCTOU staleness guard, synchronous write critical section, and curly-quote preservation (6 files, 1,813 lines)
> - [`tools/FileWriteTool/`](../../tools/FileWriteTool/) — new-file fast path, overwrite staleness guard, and forced `'LF'` line-ending policy (3 files, 857 lines)
> - [`tools/GrepTool/`](../../tools/GrepTool/) — unconditionally read-only ripgrep wrapper with Ch 11 ignore globs and non-aborting timeouts (3 files, 796 lines)
> - [`utils/bash/`](../../utils/bash/) — pure-TS tree-sitter-compatible parser, fail-closed AST walker, salted heredoc masking, legacy splitter, and snapshots (23 files, 12,306 lines)
> - [`utils/sandbox/sandbox-adapter.ts`](../../utils/sandbox/sandbox-adapter.ts) — `@anthropic-ai/sandbox-runtime` adapter, cycle breaker, and bare-git scrubber (985 lines; sibling [`utils/sandbox/sandbox-ui-utils.ts`](../../utils/sandbox/sandbox-ui-utils.ts), 12 lines)
> - [`utils/shell/`](../../utils/shell/) — `ShellProvider` contract, Bash/PowerShell providers, shared flag/UNC read-only validation, and `pwsh` detection (10 files, 3,069 lines)
> - [`utils/Shell.ts`](../../utils/Shell.ts) and [`utils/ShellCommand.ts`](../../utils/ShellCommand.ts) — file-fd subprocess runner, sync CWD tracking, timeouts, and backgrounding watchdog (474 and 465 lines)

---

## Why This Layer Exists

[Chapter 11](11-the-permission-engine.md) gave Claude Code generic policy machinery: permission modes, eight rule sources, path checks, and `useCanUseTool`. Policy alone cannot spawn a command or patch a file. Spanning 85 primary files (43,743 lines), Chapter 12 builds the concrete enforcement tools that turn untrusted inputs into trustworthy `argv[]` vectors, OS-isolated child processes, bounded timeouts, and staleness-checked workspace writes.

Three production hazards shape every design choice below. First, shell syntax is a parser-differential minefield: any mismatch between Claude Code's static analyzer and the real shell bypasses `Bash(rm:*)` or corrupts [Chapter 06](06-executing-tools.md)'s concurrent read batches. Second, once a binary spawns, static analysis goes blind—children can touch arbitrary files, write 768 GB to disk, or hang the REPL. Third, file tools must eliminate redundant reads without allowing blind overwrites when users or linters edit disk mid-turn.

---

## 1. Shell Parsing, Security Analysis, and Read-Only Classification

### The Problem

Both [Chapter 11](11-the-permission-engine.md) rules (`Bash(git status:*)`) and [Chapter 06](06-executing-tools.md) concurrency (`BashTool.isConcurrencySafe()` at `tools/BashTool/BashTool.tsx:434-436` delegates to `this.isReadOnly`) need trustworthy `argv[]` and redirect targets.

Naive regexes fail on real shells: GNU `getopt_long` abbreviates `--upload-pack=cmd` to `--up=cmd` (`tools/BashTool/readOnlyValidation.ts:1710-1715`), `shell-quote` splits `<<` into two `<` tokens (`utils/bash/heredoc.ts:4-6`), and Zsh expands `=curl` to `/usr/bin/curl`.

### The Mechanism: Fail-Closed AST Gate, Legacy Fallback, and Allowlisted Flags

1. **Pure-TS Parser & Rollout Gates ([`utils/bash/bashParser.ts`](../../utils/bash/bashParser.ts), [`utils/bash/parser.ts`](../../utils/bash/parser.ts)):**
   Despite older WASM/NAPI comments (`utils/bash/parser.ts:47`), `utils/bash/bashParser.ts` (4,436 lines) is a pure-TypeScript recursive-descent parser emitting tree-sitter-bash-compatible `TsNode` trees with UTF-8 byte offsets, verified against a 3,449-input corpus (`utils/bash/bashParser.ts:8-9`). Anti-DoS caps stop parsing at `PARSE_TIMEOUT_MS = 50`, `MAX_NODES = 50_000` (`utils/bash/bashParser.ts:29-32`), and `MAX_COMMAND_LENGTH = 10000` (`utils/bash/parser.ts:19`).

   Two build-time gates govern rollout. `parseCommand()` (`utils/bash/parser.ts:56-84`) runs only under `feature('TREE_SITTER_BASH')` (`utils/bash/parser.ts:65`) so Bun DCE strips the parser in external builds.

   `parseCommandRaw()` (`utils/bash/parser.ts:104-136`) also runs under `feature('TREE_SITTER_BASH_SHADOW')` + GrowthBook `tengu_birch_trellis` (`tools/BashTool/bashPermissions.ts:1683-1739`), logging `tengu_tree_sitter_shadow` before resetting `astResult` to `'parse-unavailable'`.

   When a loaded parser times out or hits `MAX_NODES`, `parseCommandRaw()` returns a dedicated `PARSE_ABORTED` symbol (`utils/bash/parser.ts:93` and `utils/bash/parser.ts:115-133`) rather than `null`, so [`utils/bash/ast.ts`](../../utils/bash/ast.ts) fails closed instead of falling back to legacy checks:

```ts
// utils/bash/ast.ts:444-459
if (root === PARSE_ABORTED) {
  // SECURITY: module loaded but parse aborted (timeout / node budget /
  // panic). Adversarially triggerable — `(( a[0][0]... ))` with ~2800
  // subscripts hits PARSE_TIMEOUT_MICROS under the 10K length limit.
  // Previously indistinguishable from module-not-loaded → routed to
  // legacy (parse-unavailable), which lacks EVAL_LIKE_BUILTINS — `trap`,
  // `enable`, `hash` leaked with Bash(*). Fail closed: too-complex → ask.
  return {
    kind: 'too-complex',
    reason:
      'Parser aborted (timeout or resource limit) — possible adversarial input',
    nodeType: 'PARSE_ABORT',
  }
}

return walkProgram(root)
```

2. **Fail-Closed AST Security Walker ([`utils/bash/ast.ts`](../../utils/bash/ast.ts)):**
   `parseForSecurity()` (`utils/bash/ast.ts:381-392`) skips `.trim()` so Unicode whitespace reaches `parseForSecurityFromAst()` (`utils/bash/ast.ts:400-460`), returning `'simple' | 'too-complex' | 'parse-unavailable'` (`utils/bash/ast.ts:25-45`).

   Six pre-checks reject tokenization differentials up front (`utils/bash/ast.ts:248-371` and `utils/bash/ast.ts:408-437`): `CONTROL_CHAR_RE` (`\r`), `UNICODE_WHITESPACE_RE`, `BACKSLASH_WHITESPACE_RE`, `ZSH_TILDE_BRACKET_RE`, `ZSH_EQUALS_EXPANSION_RE`, and `BRACE_WITH_QUOTE_RE` over `maskBracesInQuotedContexts()`.

   `walkProgram()` (`utils/bash/ast.ts:462-955`) walks an explicit node allowlist with flow-sensitive `varScope`: `&&`/`;` carry literal bindings forward while `||`, pipes, subshells, loops, and `if` branches fork scope copies (`utils/bash/ast.ts:505-558`). It blocks `IFS`/`PS4` poisoning (`utils/bash/ast.ts:1842-1906`), rejects unquoted heredocs in `walkHeredocRedirect()` (`utils/bash/ast.ts:1130-1193`), and rebuilds `.text` from resolved `argv` (`utils/bash/ast.ts:1316-1358`).

   `checkSemantics()` (`utils/bash/ast.ts:2213-2679`) then rejects unknown wrapper flags, bash array-subscript arithmetic RCE (`arr[$(id)]` evaluated even from single quotes via `SUBSCRIPT_EVAL_FLAGS`, `TEST_ARITH_CMP_OPS`, `BARE_SUBSCRIPT_NAME_BUILTINS`, and `declare`/`local` flags at `utils/bash/ast.ts:609-654` and `utils/bash/ast.ts:2422-2540`), `jq` `system()`, `/proc/*/environ`, 17 `ZSH_DANGEROUS_BUILTINS`, and 20 `EVAL_LIKE_BUILTINS` (`utils/bash/ast.ts:2060-2134`).

3. **Legacy Fallback Pipeline ([`utils/bash/heredoc.ts`](../../utils/bash/heredoc.ts), [`utils/bash/commands.ts`](../../utils/bash/commands.ts), [`tools/BashTool/bashSecurity.ts`](../../tools/BashTool/bashSecurity.ts)):**
   - `extractHeredocs()` (`utils/bash/heredoc.ts:113-687`) replaces heredocs with salted `__HEREDOC_<idx>_<16hex>__` tokens, tracks quote-aware logical newlines (`utils/bash/heredoc.ts:381-435`), and supports `quotedOnly` with `skippedHeredocRanges` (`utils/bash/heredoc.ts:527-598`) so unquoted `<<EOF` expansions stay exposed to security scans.
   - `splitCommandWithOperators()` (`utils/bash/commands.ts:85-249`) and `extractOutputRedirections()` (`utils/bash/commands.ts:634-790`) extract heredocs *before* joining odd-backslash continuations, delegate Zsh force-clobber (`>!`, `>&!`) to `handleRedirection()` (`utils/bash/commands.ts:860-1091`), and fail closed on parse errors.
   - [`utils/bash/ParsedCommand.ts`](../../utils/bash/ParsedCommand.ts) (`utils/bash/ParsedCommand.ts:151-238`) slices UTF-8 `Buffer`s for tree-sitter byte offsets, while `analyzeCommand()` (`utils/bash/treeSitterAnalysis.ts:496-506`) eliminates `find -exec \;` false positives (`hasActualOperatorNodes`).
   - `bashCommandIsSafe_DEPRECATED()` / `Async` (`tools/BashTool/bashSecurity.ts:2257-2592`) run 23 validators (`BASH_SECURITY_CHECK_IDS`, `tools/BashTool/bashSecurity.ts:77-101`), **deferring** non-misparsing asks (`validateNewlines`, `validateRedirections`) until loop end (`tools/BashTool/bashSecurity.ts:2334-2407`) so an early `>` never masks a misparsing failure.

4. **The `bashToolHasPermission()` Cascade & Specialized Guards ([`tools/BashTool/bashPermissions.ts`](../../tools/BashTool/bashPermissions.ts)):**
   `BashTool.checkPermissions()` (`tools/BashTool/BashTool.tsx:539-541`) delegates to `bashToolHasPermission()` (`tools/BashTool/bashPermissions.ts:1663-2557`):
   1. **AST / Shadow gate (`tools/BashTool/bashPermissions.ts:1678-1827`):** Unless bypassed by `CLAUDE_CODE_DISABLE_COMMAND_INJECTION_CHECK` (`tools/BashTool/bashPermissions.ts:1678-1680`), parses via AST; on `'too-complex'` or `!checkSemantics.ok`, evaluates `checkEarlyExitDeny` / `checkSemanticsDeny` *first* so explicit deny rules are never downgraded to `'ask'`.
   2. **Sandbox auto-allow (`tools/BashTool/bashPermissions.ts:1831-1843`):** Covered in Section 3.
   3. **Exact deny & prompt classifiers (`tools/BashTool/bashPermissions.ts:1846-1971`):** Checks exact deny rules (`tools/BashTool/bashPermissions.ts:1846-1854`), then awaits parallel prompt `deny`/`ask` `classifyBashCommand()` calls (`tools/BashTool/bashPermissions.ts:1859-1971`, skipped in `auto` mode under `feature('TRANSCRIPT_CLASSIFIER')`).

      On `ask` under `feature('BASH_CLASSIFIER')`, it attaches `pendingClassifierCheck` (`tools/BashTool/bashPermissions.ts:1960-1967`) for the speculative `allow` classifier started upstream in `services/tools/toolExecution.ts:746` (`startSpeculativeClassifierCheck()`, `tools/BashTool/bashPermissions.ts:1497-1527`) and consumed via `consumeSpeculativeClassifierCheck()` (`tools/BashTool/bashPermissions.ts:1533-1541`, `tools/BashTool/bashPermissions.ts:1561`, `tools/BashTool/bashPermissions.ts:1612`, `hooks/useCanUseTool.tsx:136`).

      In this checkout, [`utils/permissions/bashClassifier.ts`](../../utils/permissions/bashClassifier.ts) (61 lines) is an **ANT-ONLY stub** whose `isClassifierPermissionsEnabled()` always returns `false`.
   4. **Compound / pipe recursion (`tools/BashTool/bashPermissions.ts:1976-2076`, `tools/BashTool/bashCommandHelpers.ts:181-265`):** Blocks subshells and cross-segment `cd` + `git`, recursively validates pipe segments, and re-checks original redirections when all segments return `'allow'`.
   5. **Per-subcommand `bashToolCheckPermission()` (`tools/BashTool/bashPermissions.ts:1050-1178`, `tools/BashTool/bashPermissions.ts:2147-2385`):** Caps legacy fanout at `MAX_SUBCOMMANDS_FOR_SECURITY_CHECK = 50` (`tools/BashTool/bashPermissions.ts:103`), blocks compound `cd` + `git`, and runs strict order: exact deny/ask → prefix/wildcard deny/ask **before** `checkPathConstraints()` → allow → `checkSedConstraints()` → `checkPermissionMode()` (`tools/BashTool/modeValidation.ts:7-115`) → `BashTool.isReadOnly()`.
   6. **Compound merge (`tools/BashTool/bashPermissions.ts:2296-2331`, `tools/BashTool/bashPermissions.ts:2492-2526`):** Short-circuits single asks only when `nonAllowCount === 1` (preventing GH#28784 where `cd <outside> && python3 foo.py` surfaced only `Read(<dir>/**)`), capping compound suggestions at `MAX_SUGGESTED_RULES_FOR_COMPOUND = 5`.

   Before matching rules, `stripSafeWrappers()` (`tools/BashTool/bashPermissions.ts:524-615`) splits env stripping (Phase 1: `SAFE_ENV_VARS` plus `ANT_ONLY_SAFE_ENV_VARS` when `USER_TYPE === 'ant'`) from wrapper stripping (Phase 2, HackerOne #3543050):

```ts
// tools/BashTool/bashPermissions.ts:598-614
// Phase 2: Strip wrapper commands and comments only. Do NOT strip env vars.
// Wrapper commands (timeout, time, nice, nohup) use execvp to run their
// arguments, so VAR=val after a wrapper is treated as the COMMAND to execute,
// not as an env var assignment. Stripping env vars here would create a
// mismatch between what the parser sees and what actually executes.
// (HackerOne #3543050)
previousStripped = ''
while (stripped !== previousStripped) {
  previousStripped = stripped
  stripped = stripCommentLines(stripped)

  for (const pattern of SAFE_WRAPPER_PATTERNS) {
    stripped = stripped.replace(pattern, '')
  }
}

return stripped.trim()
```

   Companion `stripAllLeadingEnvVars()` (`tools/BashTool/bashPermissions.ts:733-776`) enforces asymmetry: allow rules strip only `SAFE_ENV_VARS`, deny/ask rules strip *all* leading env vars, and sandbox exclusions strip all except `BINARY_HIJACK_VARS = /^(LD_|DYLD_|PATH$)/` (`tools/BashTool/bashPermissions.ts:708`).

   Three specialized validators complete the cascade:
   - **Read-only flag allowlisting (`tools/BashTool/readOnlyValidation.ts:1246-1408`, `tools/BashTool/readOnlyValidation.ts:1876-1990`, `utils/shell/readOnlyCommandValidation.ts:1562-1893`):** `checkReadOnlyConstraints()` blocks Windows UNC/WebDAV NTLM leaks (`containsVulnerableUncPath()`), enforces a 4-way bare-git guard (`cd` + `git`, bare-repo CWD, git-internal writes + `git`, sandboxed `git` outside `getOriginalCwd()`), and rejects unquoted globs/`$` expansions.
   - **Why flag allowlists beat regexes:** `isCommandSafeViaFlagParsing()` → `validateFlags()` types flag values, gates `--` on `respectsDoubleDash` (`false` for `pyright`, `utils/shell/readOnlyCommandValidation.ts:1506-1507` and `utils/shell/readOnlyCommandValidation.ts:1719-1731`), separates `hasEquals` (`xargs -E= EOF`), and requires bundled short flags (`-nr`) to take `'none'`.
   - **Path validation (`tools/BashTool/pathValidation.ts:190-589`, `tools/BashTool/pathValidation.ts:1013-1150`):** Extracts paths for 36 `PathCommand`s via `PATH_EXTRACTORS` and `COMMAND_OPERATION_TYPE` (honoring POSIX `--` in `filterOutFlags()` at `tools/BashTool/pathValidation.ts:110-139`), keeps symlinks unresolved in `checkDangerousRemovalPaths()` (`tools/BashTool/pathValidation.ts:70-108`, catching `/tmp` on macOS), and prefers AST `argv`/redirects when available.
   - **`sed` guard & hidden preview (`tools/BashTool/sedValidation.ts:247-301`, `tools/BashTool/sedValidation.ts:473-684`, `tools/BashTool/sedEditParser.ts:40-322`):** Allows only strict `-n` line-printing or single `s///` substitutions, denylisting GNU `e`/`w` and non-ASCII homoglyphs. Approved `sed -i` applies `_simulatedSedEdit` directly (`tools/BashTool/BashTool.tsx:360-419`), while **omitting `_simulatedSedEdit` from the model-facing Zod schema** (`tools/BashTool/BashTool.tsx:249-259`) so the model cannot smuggle arbitrary writes.

5. **Comparative `PowerShellTool` & `ShellProvider` ([`utils/shell/shellProvider.ts`](../../utils/shell/shellProvider.ts), [`tools/PowerShellTool/`](../../tools/PowerShellTool/)):**
   Both shell tools share `ShellProvider` (`utils/shell/shellProvider.ts:1-33`) and `validateFlags()`, gated on Windows by `isPowerShellToolEnabled()` (`utils/shell/shellToolUtils.ts:17-22`: ON by default for `USER_TYPE === 'ant'`, opt-in via `CLAUDE_CODE_USE_POWERSHELL_TOOL=1` externally):

| Dimension | `BashTool` (`tools/BashTool/`) | `PowerShellTool` (`tools/PowerShellTool/`) |
|---|---|---|
| **AST Parser** | Pure-TS `utils/bash/bashParser.ts` (`TREE_SITTER_BASH`) + legacy fallback | Live `pwsh` `.NET Language.Parser` subprocess (`utils/powershell/parser.ts:1130-1294`, LRU-256) |
| **Security Gate** | Fail-closed `utils/bash/ast.ts` + 23 legacy checks | 24 AST checks (`tools/PowerShellTool/powershellSecurity.ts:1042-1090`) + inverted `CLM_ALLOWED_TYPES` (`tools/PowerShellTool/clmTypes.ts:18-211`, minus `adsi`/`wmi`/`cimsession`) |
| **Sync `isReadOnly()`** | Sync evaluation → unlocks Ch 06 parallel read batches (`isConcurrencySafe`) | Always returns `false` synchronously (`tools/PowerShellTool/PowerShellTool.tsx:300-316`, `tools/PowerShellTool/readOnlyValidation.ts:1178-1180`) → runs serially; AST read-only runs async in `powershellToolHasPermission()` |
| **Windows Sandbox** | Uses Git Bash (`utils/Shell.ts`) | Refuses via `WINDOWS_SANDBOX_POLICY_REFUSAL` (`tools/PowerShellTool/PowerShellTool.tsx:208-222`) when `sandbox.enabled` & `!allowUnsandboxedCommands` |

   `PowerShellTool`'s async read-only classifier rests on `isProvablySafeStatement()` (`tools/PowerShellTool/readOnlyValidation.ts:1072-1082`) plus `Object.create(null)` alias resolution (`utils/powershell/parser.ts:1326`) and degraded-mode backtick/fragment deny scanning (`tools/PowerShellTool/powershellPermissions.ts:764-853`):

```ts
// tools/PowerShellTool/readOnlyValidation.ts:1072-1082
export function isProvablySafeStatement(stmt: ParsedStatement): boolean {
  if (stmt.statementType !== 'PipelineAst') return false
  // Empty commands → vacuously passes the loop below. PowerShell's
  // parser guarantees PipelineAst.PipelineElements ≥ 1 for valid source,
  // but this gate is the linchpin — defend against parser/JSON edge cases.
  if (stmt.commands.length === 0) return false
  for (const cmd of stmt.commands) {
    if (cmd.elementType !== 'CommandAst') return false
  }
  return true
}
```

### Hidden Invariants & Production Scars

- **Bun `feature()` DCE cliff (`tools/BashTool/bashPermissions.ts:81-89`, `tools/BashTool/pathValidation.ts:1152-1164`):** `bashToolHasPermission` sits at Bun's per-function constant-folding budget. Using `import { X as Y }` aliases—or deleting ~80 lines of dead code—caused `feature('BASH_CLASSIFIER')` to fold silently to `false` (causing 22/30 classifier tests to fail from a 30/30 passing baseline, i.e., 8/30 passing). Top-level `const` rebindings preserve DCE.
- **PowerShell symlink/junction guard (`tools/PowerShellTool/modeValidation.ts:56-117`):** `isSymlinkCreatingCommand()` catches `New-Item -ItemType SymbolicLink|Junction|HardLink` across abbreviated flags (`-it`), Unicode dashes, colon bindings, and backtick escapes.

---

## 2. Subprocess Execution, Timeouts, and Foreground-to-Background Promotion

### The Problem

Running a validated command in an ephemeral subprocess must preserve user functions and working directories, avoid buffering gigabytes in JS memory, recognize informational non-zero exits (`grep` exit `1`), and promote long-running commands without stalling the REPL.

### The Mechanism: Snapshots, File-FD Execution, and Four Promotion Paths

1. **Snapshots & `ShellProvider` Wrapping ([`utils/bash/ShellSnapshot.ts`](../../utils/bash/ShellSnapshot.ts), [`utils/shell/bashProvider.ts`](../../utils/shell/bashProvider.ts), [`utils/shell/powershellProvider.ts`](../../utils/shell/powershellProvider.ts)):**
   `createAndSaveSnapshot()` (`utils/bash/ShellSnapshot.ts:413-582`) runs one login shell capture per session (honoring `CLAUDE_CODE_DONT_INHERIT_ENV`), emits `unalias -a` first (`utils/bash/ShellSnapshot.ts:368-372`), captures functions/aliases, installs `rg` and build-time `EMBEDDED_SEARCH_TOOLS`-gated ant-native `bfs`/`ugrep` `ARGV0` shims (`utils/embeddedTools.ts:15-21`, `utils/bash/ShellSnapshot.ts:65-92`, `utils/bash/ShellSnapshot.ts:153-179`), and registers shutdown deletion.

   `createBashShellProvider()` (`utils/shell/bashProvider.ts:58-255`) disables `extglob`, reorders pipeline stdin (`rearrangePipeCommand()`), wraps execution in `eval ... && pwd -P >| <cwdFilePath>` (`utils/shell/bashProvider.ts:181-187`), and sets `TMPPREFIX` for sandboxed Zsh heredocs (`utils/shell/bashProvider.ts:242-247`).

   It also applies `CLAUDE_CODE_SHELL_PREFIX` via `formatShellPrefixCommand()` (`utils/bash/shellPrefix.ts:15-28`), logs multiline commands under `feature('COMMIT_ATTRIBUTION')` (`utils/shell/bashProvider.ts:134`), and sets an ant tmux socket (`utils/shell/bashProvider.ts:222`).

   `createPowerShellProvider()` (`utils/shell/powershellProvider.ts:27-123`) builds `['-NoProfile', '-NonInteractive', '-Command', cmd]` via `buildPowerShellArgs()` (`utils/shell/powershellProvider.ts:11-13`), prefers `$LASTEXITCODE` over PowerShell 5.1's `$?` (`utils/shell/powershellProvider.ts:55-65`), and Base64 UTF-16LE encodes `-EncodedCommand` under Linux/macOS sandboxing (`utils/shell/powershellProvider.ts:68-94`) to survive `sandbox-runtime`'s `shellquote.quote()`.

   Sibling `utils/shell/powershellDetection.ts:24-107` bypasses hanging Linux `/snap/` launchers via `realpath()`.

2. **Zero-JS-Copy File Mode & Microtask-Sync CWD ([`utils/Shell.ts`](../../utils/Shell.ts)):**
   `findSuitableShell()` (`utils/Shell.ts:73-137`) resolves `CLAUDE_CODE_SHELL`, `SHELL`, and `zsh`/`bash`. `exec()` (`utils/Shell.ts:181-442`) binds both `stdout` and `stderr` to one file descriptor (`utils/Shell.ts:289-332`): POSIX uses `O_WRONLY | O_CREAT | O_APPEND | O_NOFOLLOW` (atomic interleaving + anti-symlink); Windows uses `'w'` because libuv `'a'` omits `FILE_WRITE_DATA` and MSYS2 silently drops output.

   Inside `shellCommand.result.then(...)`—before any `await`—`utils/Shell.ts:385-421` runs synchronous `SandboxManager.cleanupAfterCommand()`, reads `nativeCwdFilePath` via `readFileSync`/`unlinkSync` (eliminating CWD microtask races), normalizes macOS APFS NFD→NFC, and calls `setCwd()` (`utils/Shell.ts:447-474`).

3. **Timeouts, Semantic Exit Codes, and Watchdogged Promotion ([`utils/timeouts.ts`](../../utils/timeouts.ts), [`utils/ShellCommand.ts`](../../utils/ShellCommand.ts), [`tools/BashTool/BashTool.tsx`](../../tools/BashTool/BashTool.tsx)):**
   `tools/BashTool/prompt.ts:27-33` re-exports `utils/timeouts.ts:1-39`: `DEFAULT_TIMEOUT_MS = 120_000` (`BASH_DEFAULT_TIMEOUT_MS`) and `MAX_TIMEOUT_MS = 600_000` (`BASH_MAX_TIMEOUT_MS`, clamped `>= default`). Under `feature('MONITOR_TOOL')`, `validateInput()` runs `detectBlockedSleepPattern()` (`tools/BashTool/BashTool.tsx:322-337` and `tools/BashTool/BashTool.tsx:524-534`), blocking foreground integer `sleep N >= 2`.

   `interpretCommandResult()` (`tools/BashTool/commandSemantics.ts:124-140`) consults `COMMAND_SEMANTICS` (`tools/BashTool/commandSemantics.ts:31-89`) to treat exit code `1` as non-error for `grep`, `rg`, `find`, `diff`, `test`, and `[`, throwing `ShellError` only for `>= 2` (`tools/BashTool/BashTool.tsx:690` and `tools/BashTool/BashTool.tsx:714-719`).

   `wrapSpawn()` (`utils/ShellCommand.ts:387-403`) listens on `'exit'` rather than `'close'` (so detached grandchildren holding fds do not hang the shell, `utils/ShellCommand.ts:269-272`), ignores `abortSignal.reason === 'interrupt'` (`utils/ShellCommand.ts:186-193`), and kills via `treeKill(pid, 'SIGKILL')`. On background promotion, `background()` arms a 5s `stat()` watchdog (`SIZE_WATCHDOG_INTERVAL_MS = 5_000`, `utils/ShellCommand.ts:54` and `utils/ShellCommand.ts:239-261`) capped at 5 GB (`utils/task/diskOutput.ts:30-31`):

```ts
// utils/ShellCommand.ts:349-366
background(taskId: string): boolean {
  if (this.#status === 'running') {
    this.#backgroundTaskId = taskId
    this.#status = 'backgrounded'
    this.#cleanupListeners()
    if (this.taskOutput.stdoutToFile) {
      // File mode: child writes directly to the fd with no JS involvement.
      // The foreground timeout is gone, so watch file size to prevent
      // a stuck append loop from filling the disk (768GB incident).
      this.#startSizeWatchdog()
    } else {
      // Pipe mode: spill the in-memory buffer so readers can find it on disk.
      this.taskOutput.spillToDisk()
    }
    return true
  }
  return false
}
```

   `runShellCommand()` (`tools/BashTool/BashTool.tsx:826-1143`) unifies all **four promotion paths**:
   1. **Explicit `run_in_background` (`tools/BashTool/BashTool.tsx:989-1001`):** Spawns via `spawnShellTask()` unless `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` is set (which also strips `run_in_background` from the model schema at `tools/BashTool/BashTool.tsx:224-226` and `tools/BashTool/BashTool.tsx:254-259`).
   2. **Timeout auto-background (`tools/BashTool/BashTool.tsx:880` and `tools/BashTool/BashTool.tsx:967-971`):** Promotes on timeout, excluding `sleep` (`DISALLOWED_AUTO_BACKGROUND_COMMANDS`, `tools/BashTool/BashTool.tsx:220`).
   3. **`KAIROS` 15s budget (`tools/BashTool/BashTool.tsx:57` and `tools/BashTool/BashTool.tsx:976-983`):** Under `feature('KAIROS') && getKairosActive() && isMainThread`, an `.unref()` timer promotes blocking commands after `ASSISTANT_BLOCKING_BUDGET_MS = 15_000`.
   4. **`Ctrl+B` past 2s (`tools/BashTool/BashTool.tsx:55` and `tools/BashTool/BashTool.tsx:1007-1126`):** Fast commands under `PROGRESS_THRESHOLD_MS = 2000` skip task registration; slower ones call `registerForeground()` so user `Ctrl+B` promotes them via `backgroundAll()` → `backgroundTask()` (`tools/BashTool/UI.tsx:49`, `tasks/LocalShellTask/LocalShellTask.tsx:293-410`), observed via `shellCommand.status === 'backgrounded'` (`tools/BashTool/BashTool.tsx:1089-1102`).

      By contrast, timer-driven auto-backgrounding (Paths #2 and #3) promotes an already-registered foreground task **in-place** via `backgroundExistingForegroundTask()` (`tools/BashTool/BashTool.tsx:929-939`, `tasks/LocalShellTask/LocalShellTask.tsx:413-474`).

   If a process exits simultaneously with promotion, `markTaskNotified()` (`tools/BashTool/BashTool.tsx:1037-1065`) suppresses duplicate notifications and returns the completed output. Subagents set `preventCwdChanges = true` and register tasks via `toolUseContext.setAppStateForTasks ?? setAppState` (`tools/BashTool/BashTool.tsx:642-653`, [Chapter 02](02-the-tool-contract.md)).

   *(Forward seam to Chapter 17: [`tasks/LocalShellTask/LocalShellTask.tsx`](../../tasks/LocalShellTask/LocalShellTask.tsx) — note `.tsx`, 523 lines — implements `spawnShellTask`, `registerForeground`, `backgroundExistingForegroundTask`, `markTaskNotified`, and the 45s interactive-prompt stall watchdog; its `TaskStateBase` runtime lives in Chapter 17.)*

---

## 3. OS-Level Sandboxing and the `@anthropic-ai/sandbox-runtime` Boundary

### The Problem

Static AST checks inspect only top-level commands; once `make build` or `python build.py` spawns, child binaries can touch arbitrary files or open sockets unseen by static analysis. Prompting on every command kills throughput. OS-level sandboxing enforces kernel filesystem and network limits across the process tree so safe sandboxed commands auto-allow (`sandbox.autoAllowBashIfSandboxed`, default `true` at `utils/sandbox/sandbox-adapter.ts:469-472`).

> [!NOTE]
> **External Package Boundary (`@anthropic-ai/sandbox-runtime`):** This checkout contains `utils/sandbox/sandbox-adapter.ts` (985 lines) and `utils/sandbox/sandbox-ui-utils.ts` (12 lines), **not** `@anthropic-ai/sandbox-runtime` (`BaseSandboxManager`, `SandboxRuntimeConfigSchema`, `SandboxViolationStore`, imported at `utils/sandbox/sandbox-adapter.ts:7-22`). Seatbelt `.sb` profiles, `bwrap` args, and proxy internals live outside this repo.
>
> Evidenced platform mentions confirm macOS Seatbelt (`components/sandbox/SandboxDependenciesTab.tsx:57`, `sandbox-exec` at `tools/PowerShellTool/PowerShellTool.tsx:208`) plus log monitor (`utils/sandbox/sandbox-adapter.ts:772`), and Linux/WSL2 `bubblewrap`/`socat` (`utils/sandbox/sandbox-adapter.ts:587-600`) plus `seccomp` (`components/sandbox/SandboxDependenciesTab.tsx:85`).
> Native Windows (`tools/PowerShellTool/PowerShellTool.tsx:208`) and WSL1 (`utils/sandbox/sandbox-adapter.ts:571-574`) are unsupported; neither `utils/sandbox/*` nor `tools/BashTool/shouldUseSandbox.ts` uses `feature()` flags.

### The Mechanism: Policy Translation, Cycle Breaking, and Per-Command Gating

1. **The Static Import Cycle Breaker ([`utils/sandbox/sandbox-adapter.ts`](../../utils/sandbox/sandbox-adapter.ts)):**
   `utils/permissions/permissions.ts:19` and `utils/permissions/pathValidation.ts:12` statically import `SandboxManager`, while `tools/BashTool/bashPermissions.ts:54-67` imports `permissions.ts` and `SandboxManager`. To avoid a circular import, `utils/sandbox/sandbox-adapter.ts:61-81` embeds local rule parsers (while `utils/hooks/execHttpHook.ts:18-24` dynamically `await import`s `sandbox-adapter.js` to break a second cycle through hooks):

```ts
// utils/sandbox/sandbox-adapter.ts:61-81
// Local copies to avoid circular dependency
// (permissions.ts imports SandboxManager, bashPermissions.ts imports permissions.ts)
function permissionRuleValueFromString(
  ruleString: string,
): PermissionRuleValue {
  const matches = ruleString.match(/^([^(]+)\(([^)]+)\)$/)
  if (!matches) {
    return { toolName: ruleString }
  }
  const toolName = matches[1]
  const ruleContent = matches[2]
  if (!toolName || !ruleContent) {
    return { toolName: ruleString }
  }
  return { toolName, ruleContent }
}

function permissionRuleExtractPrefix(permissionRule: string): string | null {
  const match = permissionRule.match(/^(.+):\*$/)
  return match?.[1] ?? null
}
```

   Notice the forensic drift: canonical `utils/permissions/permissionRuleParser.ts:93-133` unescapes `\(`/`\)` and normalizes legacy names (`Task` → `Agent`), whereas this local regex (`[^)]+`) silently drops any path rule containing a literal `)`.

2. **Permission-to-Sandbox Translation (`convertToSandboxRuntimeConfig`, `utils/sandbox/sandbox-adapter.ts:172-381`):**
   - **Dual path semantics (`#30067`):** `resolvePathPatternForSandbox()` (`utils/sandbox/sandbox-adapter.ts:99-119`) uses Ch 11 rule syntax (`//path` = absolute, `/path` = settings-relative), whereas `resolveSandboxFilesystemPath()` (`utils/sandbox/sandbox-adapter.ts:138-146`) treats `/Users/foo/.cargo` in `sandbox.filesystem.*` as absolute and expands `~` because `sandbox-runtime`'s `getFsWriteConfig()` skips `normalizePathForSandbox()`.
   - **Rule translation:** Write allow/deny comes from **`Edit(...)`** rules (not `Write(...)`) plus `sandbox.filesystem.{allowWrite,denyWrite}`, seeded with `['.', getClaudeTempDir()]`, `worktreeMainRepoPath`, and `additionalDirectories` (`utils/sandbox/sandbox-adapter.ts:225-339`). Read rules map **`Read(...)` deny** plus `sandbox.filesystem.{denyRead,allowRead}`. Network rules map `WebFetch(domain:...)` allow/deny plus `sandbox.network.allowedDomains` (`utils/sandbox/sandbox-adapter.ts:178-220`).
   - **Hard protections & locks:** `denyWrite` protects every `SETTING_SOURCES` settings file and `.claude/skills` (omitted by `sandbox-runtime`'s `getDangerousDirectories()`, `utils/sandbox/sandbox-adapter.ts:232-255`). Enterprise locks `shouldAllowManagedSandboxDomainsOnly()` (`utils/sandbox/sandbox-adapter.ts:152-157`, also forcing `sandboxAskCallback` to `false` at `utils/sandbox/sandbox-adapter.ts:745-755`) and `shouldAllowManagedReadPathsOnly()` (`utils/sandbox/sandbox-adapter.ts:159-164`) pin domains and `allowRead` to `policySettings`.
   - **Lifecycle & availability:** `initialize()` sets `initializationPromise` pre-`await` (`utils/sandbox/sandbox-adapter.ts:757-759`), exposing sync **`refreshConfig()`** (`utils/sandbox/sandbox-adapter.ts:798-803`) and `addToExcludedCommands()` (`utils/sandbox/sandbox-adapter.ts:828-874`). Startup (`screens/REPL.tsx:2318-2336`, `cli/print.ts:601-615`) checks `getSandboxUnavailableReason()` (`#34044`, `utils/sandbox/sandbox-adapter.ts:554-592`), `enabledPlatforms`, and `failIfUnavailable` (`utils/sandbox/sandbox-adapter.ts:483`).

3. **Bare-Git Escape Defense (`#29316`, `utils/sandbox/sandbox-adapter.ts:257-280`):**
   Planting `HEAD`, `objects/`, `refs/`, and `config` (`core.fsmonitor`) turns `cwd` into a bare repo that executes attacker code on Claude Code's next unsandboxed `git` call. Adding missing paths to `denyWrite` makes Linux `bwrap` mount `/dev/null`, leaving a 0-byte `HEAD` stub that breaks `git log HEAD`—so `convertToSandboxRuntimeConfig()` splits existing vs. missing targets:

```ts
// utils/sandbox/sandbox-adapter.ts:257-280
// SECURITY: Git's is_git_directory() treats cwd as a bare repo if it has
// HEAD + objects/ + refs/. An attacker planting these (plus a config with
// core.fsmonitor) escapes the sandbox when Claude's unsandboxed git runs.
//
// Unconditionally denying these paths makes sandbox-runtime mount
// /dev/null at non-existent ones, which (a) leaves a 0-byte HEAD stub on
// the host and (b) breaks `git log HEAD` inside bwrap ("ambiguous argument").
// So: if a file exists, denyWrite (ro-bind in place, no stub). If not, scrub
// it post-command in scrubBareGitRepoFiles() — planted files are gone before
// unsandboxed git runs; inside the command, git is itself sandboxed.
bareGitRepoScrubPaths.length = 0
const bareGitRepoFiles = ['HEAD', 'objects', 'refs', 'hooks', 'config']
for (const dir of cwd === originalCwd ? [originalCwd] : [originalCwd, cwd]) {
  for (const gitFile of bareGitRepoFiles) {
    const p = resolve(dir, gitFile)
    try {
      // eslint-disable-next-line custom-rules/no-sync-fs -- refreshConfig() must be sync
      statSync(p)
      denyWrite.push(p)
    } catch {
      bareGitRepoScrubPaths.push(p)
    }
  }
}
```

   Existing paths become `denyWrite`; missing paths enter `bareGitRepoScrubPaths` and are synchronously removed via `rmSync(..., { recursive: true })` (`utils/sandbox/sandbox-adapter.ts:408`) by `scrubBareGitRepoFiles()` inside `SandboxManager.cleanupAfterCommand()` (`utils/sandbox/sandbox-adapter.ts:395-414`, `utils/sandbox/sandbox-adapter.ts:963-966`) right when `utils/Shell.ts:391-393` finishes.

4. **Per-Command Gate & Ch 11 Interplay ([`tools/BashTool/shouldUseSandbox.ts`](../../tools/BashTool/shouldUseSandbox.ts)):**
   `shouldUseSandbox(input)` (`tools/BashTool/shouldUseSandbox.ts:130-153`) returns `false` if sandboxing is off, if `dangerouslyDisableSandbox && areUnsandboxedCommandsAllowed()`, if `!input.command`, or if `containsExcludedCommand()` (`tools/BashTool/shouldUseSandbox.ts:21-128`) matches.

   `containsExcludedCommand()` checks ant-only GrowthBook `tengu_sandbox_disabled_commands` (`USER_TYPE === 'ant'`, `tools/BashTool/shouldUseSandbox.ts:23-50`), then matches fixed-point stripped candidates (refusing `BINARY_HIJACK_VARS`) against `sandbox.excludedCommands` (`tools/BashTool/shouldUseSandbox.ts:53-125`).

   `excludedCommands` is a **convenience escape hatch, not a bypass**: returning `false` disables sandbox auto-allow and falls back to [Chapter 11](11-the-permission-engine.md) prompts across three seams:
   - `utils/permissions/permissions.ts:1091-1111` and `utils/permissions/permissions.ts:1183-1206` skip a tool-wide `Bash` `ask` rule *only* when `canSandboxAutoAllow` holds.
   - `checkSandboxAutoAllow()` (`tools/BashTool/bashPermissions.ts:1270-1359`, `tools/BashTool/bashPermissions.ts:1831-1843`) evaluates all subcommand `deny` rules *before* returning any `ask` rule.
   - `utils/permissions/pathValidation.ts:225-245` honors sandbox write allowlists only when `!isInWorkingDir` so the `'.'` seed (`utils/sandbox/sandbox-adapter.ts:225`) never bypasses `acceptEdits`.

### Hidden Invariants & Production Scars

- **Prompt-cache `$TMPDIR` normalization (`tools/BashTool/prompt.ts:185-190`):** Replaces per-UID `/private/tmp/claude-<uid>/` with literal `'$TMPDIR'` so the sandbox prompt section preserves [Chapter 04](04-prompt-engineering-and-cache-boundaries.md)'s cross-user global prompt cache.
- **Render-loop retry storm (`#21605`, `tools/BashTool/BashTool.tsx:498-502`):** `userFacingName()` checks `CLAUDE_CODE_BASH_SANDBOX_SHOW_INDICATOR` *before* `shouldUseSandbox()`, avoiding per-render `shell-quote` `new RegExp` work across history that exceeded the shimmer tick.
- **Dual `<sandbox_violations>` view (`tools/BashTool/BashTool.tsx:710`, `tools/BashTool/BashTool.tsx:718`, `utils/sandbox/sandbox-ui-utils.ts:10-12`):** `BashTool.call()` preserves `<sandbox_violations>` inside `ShellError` so the model can decide whether to retry (`tools/BashTool/prompt.ts:228-256`). Meanwhile `removeSandboxViolationTags()` strips them in `tools/BashTool/BashToolResultMessage.tsx:35` and `components/FallbackToolUseErrorMessage.tsx:36`, routing user visibility to `SandboxViolationStore` panels.

---

## 4. Core Workspace Tools and the `FileStateCache` Staleness Protocol

### The Problem

Repeatedly reading unchanged files wastes prompt tokens (`tools/FileReadTool/FileReadTool.ts:526-535` cites ~18% same-file Read collisions and up to 2.64% of fleet `cache_creation` tokens). Yet writing without proving the model saw current disk state risks clobbering user or linter edits—and checking timestamps only before permission prompts leaves a TOCTOU window while the human responds.

### The Mechanism: Coordinated `FileStateCache` Semantics Across Four Tools

1. **`FileReadTool`: Zero-I/O Validation, Budgeting, and `FILE_UNCHANGED_STUB` ([`tools/FileReadTool/FileReadTool.ts`](../../tools/FileReadTool/FileReadTool.ts), [`tools/FileReadTool/limits.ts`](../../tools/FileReadTool/limits.ts)):**
   - **Contract invariants:** Sets `maxResultSizeChars: Infinity` (`tools/FileReadTool/FileReadTool.ts:340-342`) so [Chapter 06](06-executing-tools.md)'s `toolResultStorage.ts` never creates a circular Read→spill→Read loop; expands paths in `backfillObservableInput()` (`tools/FileReadTool/FileReadTool.ts:388-394`); and returns `''` from `extractSearchText()` (`tools/FileReadTool/FileReadTool.ts:409-416`).
   - **Zero-I/O `validateInput()` (`tools/FileReadTool/FileReadTool.ts:418-495`):** Validates PDF page ranges, checks Ch 11 deny rules, short-circuits UNC paths (`\\` or `//`) before any `stat()` to stop SMB/NTLM leaks, rejects binaries, and blocks infinite/TTY paths in `BLOCKED_DEVICE_PATHS` (`tools/FileReadTool/FileReadTool.ts:98-128`). Missing files retry macOS screenshot thin spaces (`U+202F`, `tools/FileReadTool/FileReadTool.ts:130-159`) in `call()`.
   - **Two-tier budgeting (`tools/FileReadTool/limits.ts:18-92`):** Enforces `MAX_OUTPUT_SIZE` (256 KiB, `utils/file.ts:48`) and `DEFAULT_MAX_OUTPUT_TOKENS = 25000`, overridden by `fileReadingLimits`, `CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS`, and memoized GrowthBook `tengu_amber_wren`. PR #21841 tested truncating oversized reads and was **reverted** (`tools/FileReadTool/limits.ts:9-13`) because ~100-byte errors beat 25K-token truncations.
   - **Multi-modal dispatch (`tools/FileReadTool/FileReadTool.ts:804-1086`):** Routes `.ipynb`, images (`tools/FileReadTool/imageProcessor.ts:37-67`, `image-processor-napi` → `sharp`), PDFs, and text, appending `CYBER_RISK_MITIGATION_REMINDER` except on `claude-opus-4-6` (`tools/FileReadTool/FileReadTool.ts:729-738`).
   - **Exact deduplication (`tools/FileReadTool/FileReadTool.ts:536-573`):** Behind killswitch `tengu_read_dedup_killswitch` (default `false` = active), returns `FILE_UNCHANGED_STUB` (`tools/FileReadTool/prompt.ts:7-8`) only when `!isPartialView`, `offset !== undefined`, `(offset, limit)` match, and `Math.floor(mtimeMs)` matches:

```ts
// tools/FileReadTool/FileReadTool.ts:547-573
if (
  existingState &&
  !existingState.isPartialView &&
  existingState.offset !== undefined
) {
  const rangeMatch =
    existingState.offset === offset && existingState.limit === limit
  if (rangeMatch) {
    try {
      const mtimeMs = await getFileModificationTimeAsync(fullFilePath)
      if (mtimeMs === existingState.timestamp) {
        const analyticsExt = getFileExtensionForAnalytics(fullFilePath)
        logEvent('tengu_file_read_dedup', {
          ...(analyticsExt !== undefined && { ext: analyticsExt }),
        })
        return {
          data: {
            type: 'file_unchanged' as const,
            file: { filePath: file_path },
          },
        }
      }
    } catch {
      // stat failed — fall through to full read
    }
  }
}
```

   Normalizing timestamps via `Math.floor(mtimeMs)` (`utils/file.ts:60-82`) suppresses sub-millisecond IDE watcher noise. Because `FileReadTool` always records numeric `offset` (default `1`, `tools/FileReadTool/FileReadTool.ts:497`) while `FileEditTool`, `FileWriteTool`, and `BashTool` `applySedEdit()` store `offset: undefined`, checking `existingState.offset !== undefined` ensures a `Read` after an `Edit` never points back to stale pre-edit content (`tools/FileReadTool/FileReadTool.ts:543-546`).

2. **`FileEditTool` & `FileWriteTool`: Two-Phase TOCTOU Guard & Curly Quotes ([`tools/FileEditTool/`](../../tools/FileEditTool/), [`tools/FileWriteTool/`](../../tools/FileWriteTool/)):**
   - **Phase 1 (`validateInput()` before prompts):** `FileEditTool` (`tools/FileEditTool/FileEditTool.ts:137-362`) checks team-memory secrets, deny rules, UNC NTLM guard, `MAX_EDIT_FILE_SIZE` (1 GiB), mandatory read-before-edit (`!readTimestamp || readTimestamp.isPartialView`), floored mtime staleness, and match uniqueness. `FileWriteTool` (`tools/FileWriteTool/FileWriteTool.ts:153-222`) fast-paths new files on `ENOENT` and enforces the same staleness check on overwrites.
   - **Phase 2 (`call()` synchronous critical section):** Both tools hoist `await fs.mkdir()` and [Chapter 08](08-session-envelope-query-engine-and-transcripts.md)'s idempotent `fileHistoryTrackEdit()` (`tools/FileEditTool/FileEditTool.ts:428-440`, `tools/FileWriteTool/FileWriteTool.ts:249-264`) strictly *before* a zero-`await` read-check-write critical section:

```ts
// tools/FileEditTool/FileEditTool.ts:442-468
// 2. Load current state and confirm no changes since last read
// Please avoid async operations between here and writing to disk to preserve atomicity
const {
  content: originalFileContents,
  fileExists,
  encoding,
  lineEndings: endings,
} = readFileForEdit(absoluteFilePath)

if (fileExists) {
  const lastWriteTime = getFileModificationTime(absoluteFilePath)
  const lastRead = readFileState.get(absoluteFilePath)
  if (!lastRead || lastWriteTime > lastRead.timestamp) {
    // Timestamp indicates modification, but on Windows timestamps can change
    // without content changes (cloud sync, antivirus, etc.). For full reads,
    // compare content as a fallback to avoid false positives.
    const isFullRead =
      lastRead &&
      lastRead.offset === undefined &&
      lastRead.limit === undefined
    const contentUnchanged =
      isFullRead && originalFileContents === lastRead.content
    if (!contentUnchanged) {
      throw new Error(FILE_UNEXPECTEDLY_MODIFIED_ERROR)
    }
  }
}
```

   A subtle scar hides in `isFullRead`: it tests `offset === undefined && limit === undefined` (`tools/FileEditTool/FileEditTool.ts:458-461`, `tools/FileWriteTool/FileWriteTool.ts:286-289`), while `FileReadTool` stores `offset: 1` (`tools/FileReadTool/FileReadTool.ts:1035`). Thus the Windows content-equality fallback engages after in-session `Edit`/`Write`/`sed -i` writes (`tools/FileEditTool/FileEditTool.ts:520-525`, `tools/FileWriteTool/FileWriteTool.ts:332-337`, `tools/BashTool/BashTool.tsx:404-409`), not after a default `Read`.

   Two writer-specific scars stand out. `FileWriteTool` always writes `'LF'` (`tools/FileWriteTool/FileWriteTool.ts:300-305`) because preserving old or repo-sampled endings corrupted Linux bash scripts with `\r`. Both tools compute remote `fetchSingleFileGitDiff()` only when `CLAUDE_CODE_REMOTE` and GrowthBook `tengu_quartz_lantern` are active (`tools/FileEditTool/FileEditTool.ts:545-558`, `tools/FileWriteTool/FileWriteTool.ts:344-357`).

   In [`tools/FileEditTool/utils.ts`](../../tools/FileEditTool/utils.ts), `findActualString()` (`tools/FileEditTool/utils.ts:73-93`) falls back to `normalizeQuotes()` when straight quotes miss curly quotes on disk, `preserveQuoteStyle()` (`tools/FileEditTool/utils.ts:104-199`) restores curly quotes while keeping contractions (`don’t`) closed, `applyEditToFile()` (`tools/FileEditTool/utils.ts:206-228`) uses `() => replace` to neutralize `$&`/`$1`, and `DESANITIZATIONS` (`tools/FileEditTool/utils.ts:531-657`) reverses API-sanitized strings.

3. **`GrepTool`: Why Search Is Separate from `BashTool` `rg` ([`tools/GrepTool/GrepTool.ts`](../../tools/GrepTool/GrepTool.ts), [`utils/ripgrep.ts`](../../utils/ripgrep.ts)):**
   `GrepTool` is unconditionally `isReadOnly: true` and `isConcurrencySafe: true` (`tools/GrepTool/GrepTool.ts:183-188`) with zero shell-injection surface or sandbox overhead. It enforces `maxResultSizeChars: 20_000` (`tools/GrepTool/GrepTool.ts:164`), `--max-columns 500`, VCS exclusions, `-e` for leading-dash regexes, and Ch 11 read-deny globs (`getFileReadIgnorePatterns` → `--glob !` / `--glob !**/`, `tools/GrepTool/GrepTool.ts:412-427`, BurntSushi/ripgrep #2156).

   All three modes (`content`, `count`, and `files_with_matches` sorted by mtime via `Promise.allSettled`) apply `DEFAULT_HEAD_LIMIT = 250` (`tools/GrepTool/GrepTool.ts:108-128`) before path relativization (`tools/GrepTool/GrepTool.ts:447-575`).

   `utils/ripgrep.ts:31-65` selects system vs. bundled/embedded `rg` via `USE_BUILTIN_RIPGREP` (`utils/ripgrep.ts:32-34`), while `utils/ripgrep.ts:98-182` and `utils/ripgrep.ts:221-231` enforce a 60s WSL2 / 20s default timeout (`CLAUDE_CODE_GLOB_TIMEOUT_SECONDS`), throwing `RipgrepTimeoutError` when `isTimeout && lines.length === 0` (`utils/ripgrep.ts:446-454`) instead of firing `AbortController` so slow searches never abort the turn (`tools/GrepTool/GrepTool.ts:436-441`).

### Gate & Snapshot-Absence Summary

| Category | Verified Identifiers & Scope in Chapter 12 |
|---|---|
| **Build-time `feature()` (7)** | `TREE_SITTER_BASH`, `TREE_SITTER_BASH_SHADOW` (`utils/bash/parser.ts`, `tools/BashTool/bashPermissions.ts`); `BASH_CLASSIFIER`, `TRANSCRIPT_CLASSIFIER` (`tools/BashTool/bashPermissions.ts`); `KAIROS`, `MONITOR_TOOL` (`tools/BashTool/BashTool.tsx`, `tools/PowerShellTool/PowerShellTool.tsx`, `tools/BashTool/prompt.ts`); `COMMIT_ATTRIBUTION` (`utils/shell/bashProvider.ts`) |
| **GrowthBook Flags (6)** | `tengu_birch_trellis` (`tools/BashTool/bashPermissions.ts:1684`); `tengu_sandbox_disabled_commands` (`tools/BashTool/shouldUseSandbox.ts:24-27`); `tengu_cork_m4q` (Haiku prefix-spec prompt caching, `utils/shell/prefix.ts:215-235`); `tengu_read_dedup_killswitch` (`tools/FileReadTool/FileReadTool.ts:536-539`); `tengu_amber_wren` (`tools/FileReadTool/limits.ts:55-58`); `tengu_quartz_lantern` (`tools/FileEditTool/FileEditTool.ts:548`, `tools/FileWriteTool/FileWriteTool.ts:347`) |
| **`USER_TYPE === 'ant'` & Key Env Vars** | Ant gates across 9 files (14 sites: `ANT_ONLY_SAFE_ENV_VARS`, `ANT_ONLY_COMMAND_ALLOWLIST`, `tengu_sandbox_disabled_commands`, undercover/commit skills at `tools/BashTool/prompt.ts:49` and `tools/BashTool/prompt.ts:56`, `CLAUDE_CODE_SESSION_ID`, tmux socket, Windows PowerShell default, `gh` read-only, `minimalUniquenessHint`, classifier telemetry). Key env vars: `BASH_DEFAULT_TIMEOUT_MS`, `BASH_MAX_TIMEOUT_MS`, `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS`, `CLAUDE_CODE_DISABLE_COMMAND_INJECTION_CHECK` (bypasses AST/injection checks), `CLAUDE_CODE_SHELL`, `CLAUDE_CODE_SHELL_PREFIX`, `CLAUDE_CODE_TMPDIR` (custom/sandbox temp dir), `CLAUDE_CODE_BASH_SANDBOX_SHOW_INDICATOR`, `CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS`, `CLAUDE_CODE_REMOTE`, `CLAUDE_CODE_GLOB_TIMEOUT_SECONDS`, `USE_BUILTIN_RIPGREP`, `EMBEDDED_SEARCH_TOOLS` (ant-native `bfs`/`ugrep` shims) |
| **Snapshot Absences & External Packages** | **Absent (type-only imports, never linked):** `types/tools.js` (`BashProgress`, `PowerShellProgress`), `constants/querySource.js` (`QuerySource`), `types/message.js` (`AssistantMessage`, `ProgressMessage`, `Message`). **External npm packages:** `@anthropic-ai/sandbox-runtime`, `image-processor-napi`. **ANT-ONLY stub:** [`utils/permissions/bashClassifier.ts`](../../utils/permissions/bashClassifier.ts). |

---

## Putting Layer 4's Concrete Tool Stack Together

```text
Layer 4 Concrete Tool Enforcement (Ch 11 Policy -> Kernel & Disk Reality)
+---------------------------------------------------------------------------+
| SHELL PATH (BashTool / PowerShellTool)                                    |
|  cmd -> [AST / Legacy Parse] -> [bash/powershellToolHasPermission + Ch11] |
|       -> shouldUseSandbox() -> ShellProvider.buildExecCommand()           |
|          (Bash: eval + pwd -P >| ; PS: Get-Location / -EncodedCommand)    |
|       -> [if useSandbox] SandboxManager.wrapWithSandbox(commandString)    |
|       -> utils/Shell.ts (file-fd: O_APPEND|O_NOFOLLOW POSIX / 'w' Win)    |
|       -> utils/ShellCommand.ts ('exit', 2m/10m timeout, 5GB cap -> Ch 17) |
|       -> sync cleanupAfterCommand() (scrubBareGitRepoFiles) + setCwd()    |
+---------------------------------------------------------------------------+
| WORKSPACE FILE & SEARCH PATHS                                             |
|  Read (FileReadTool):                                                     |
|   zero-I/O validateInput() (UNC guard, deny, devices) -> call() dedup on  |
|   prior Read (offset !== undefined && mtime match -> FILE_UNCHANGED_STUB) |
|   else read + readFileState.set(numeric offset, default 1)                |
|  Edit / Write (FileEditTool / FileWriteTool):                             |
|   validateInput() (UNC skip; else fs.stat + !isPartialView + mtimeMs)     |
|   -> hoist async mkdir + fileHistoryTrackEdit() (Ch 08 /rewind)           |
|   -> sync critical section (re-stat -> FILE_UNEXPECTEDLY_MODIFIED_ERROR   |
|      or writeTextContent()) -> readFileState.set(offset: undefined)       |
|      (next Read bypasses dedup)                                           |
|  Grep (GrepTool):                                                         |
|   unconditionally read-only ripgrep + Ch 11 --glob ! + non-abort timeout  |
+---------------------------------------------------------------------------+
```

```mermaid
flowchart TD
    IN["Model ToolUseBlock (Bash / PowerShell / Read / Edit / Write / Grep)"]
    SPLIT{"Tool Family"}
    AST["utils/bash/ast.ts or utils/powershell/parser.ts: Fail-Closed AST"]
    PERM["bashToolHasPermission() or powershellToolHasPermission() + Ch 11"]
    PROV["ShellProvider.buildExecCommand() (given shouldUseSandbox())"]
    SBGATE{"useSandbox?"}
    SBWRAP["utils/sandbox/sandbox-adapter.ts: wrapWithSandbox() -> @anthropic-ai/sandbox-runtime"]
    EXEC["utils/Shell.ts (file-fd spawn) -> utils/ShellCommand.ts ('exit', 5GB watchdog)"]
    BG["tasks/LocalShellTask/LocalShellTask.tsx (Forward Seam -> Ch 17)"]
    RVAL["FileReadTool: zero-I/O validateInput() -> dedup / FILE_UNCHANGED_STUB or set(numeric offset, default 1)"]
    FVAL["Edit/Write validateInput(): UNC guard, fs.stat, !isPartialView, mtimeMs"]
    FHIST["Hoisted async mkdir + utils/fileHistory.ts (Ch 08)"]
    FCRIT["Sync Read-Check-Write Critical Section + set(offset: undefined)"]
    GVAL["GrepTool: read-only ripgrep + Ch 11 --glob ! ignores + non-aborting timeout"]
    IN --> SPLIT
    SPLIT -->|"Shell"| AST
    AST --> PERM
    PERM --> PROV
    PROV --> SBGATE
    SBGATE -->|"Yes"| SBWRAP
    SBGATE -->|"No (unsandboxed)"| EXEC
    SBWRAP --> EXEC
    EXEC -->|"bg promotion (Bash: 4 paths)"| BG
    SPLIT -->|"Read"| RVAL
    SPLIT -->|"Edit / Write"| FVAL
    FVAL --> FHIST
    FHIST --> FCRIT
    SPLIT -->|"Grep"| GVAL
```

---

## How This Snaps Into the Next Layer

Chapter 12's shell runners and tools plug directly into **Chapter 13 (The Hook System)**:

- [`utils/hooks.ts`](../../utils/hooks.ts) (5,022 lines) imports five Chapter 12 primitives (`utils/hooks.ts:9`, `utils/hooks.ts:13`, and `utils/hooks.ts:21-23`) for `execCommandHook()` (`utils/hooks.ts:747-1335`): `DEFAULT_HOOK_SHELL` (`utils/hooks.ts:790`), `formatShellPrefixCommand` (`utils/hooks.ts:872-875`), `getCachedPowerShellPath` (`utils/hooks.ts:959`), `buildPowerShellArgs` (`utils/hooks.ts:967`), and `wrapSpawn` (`utils/hooks.ts:989`, using pipe mode so stdout line 1 can signal `{"async": true}`).
- [`services/tools/toolHooks.ts`](../../services/tools/toolHooks.ts) (650 lines) wraps every tool call with `runPreToolUseHooks()` (`services/tools/toolHooks.ts:435-650`), `resolveHookPermissionDecision()` (`services/tools/toolHooks.ts:332-433`, guaranteeing hook `'allow'` never bypasses `settings.json` `deny`/`ask` rules), `runPostToolUseHooks()` (`services/tools/toolHooks.ts:39-191`), and `runPostToolUseFailureHooks()` (`services/tools/toolHooks.ts:193-319`).
- `BashTool.preparePermissionMatcher()` (`tools/BashTool/BashTool.tsx:445-468`) feeds `parseForSecurity()` directly into Chapter 13's conditional hook filters, failing safe (`() => true`) on `'too-complex'` commands and matching resolved `argv` so `FOO=bar git push` still fires a `Bash(git *)` hook.

---

## Reading Exercises & Code Checkpoints

1. **Trace the tree-sitter AST rollout and shadow-mode killswitch:**
   Run `rg -n "TREE_SITTER_BASH|tengu_birch_trellis" utils/bash/parser.ts tools/BashTool/bashPermissions.ts` and verify why `parseCommand()` gates strictly on `TREE_SITTER_BASH` while `parseCommandRaw()` also runs under `TREE_SITTER_BASH_SHADOW` before resetting `astResult` to `'parse-unavailable'`.
2. **Audit the `@anthropic-ai/sandbox-runtime` boundary and dynamic exclusion gate:**
   Run `rg -n "@anthropic-ai/sandbox-runtime|tengu_sandbox_disabled_commands|SandboxViolationStore" utils/sandbox/sandbox-adapter.ts tools/BashTool/shouldUseSandbox.ts` and trace what Claude Code owns versus what lives in the external npm runtime.
3. **Follow the `FileStateCache` deduplication and TOCTOU staleness handshake:**
   Run `rg -n "FILE_UNCHANGED_STUB|FILE_UNEXPECTEDLY_MODIFIED_ERROR|isPartialView|tengu_read_dedup_killswitch" tools/FileReadTool/ tools/FileEditTool/ tools/FileWriteTool/` and check why `FileEditTool` writes `offset: undefined` after every edit while `FileReadTool` requires `offset !== undefined` to deduplicate.
4. **Inspect the exact Chapter 12 → Chapter 13 shell-hook handoff:**
   Run `rg -n "formatShellPrefixCommand|DEFAULT_HOOK_SHELL|getCachedPowerShellPath|buildPowerShellArgs|wrapSpawn" utils/hooks.ts` and confirm why `execCommandHook()` uses `wrapSpawn` in pipe mode rather than `utils/Shell.ts`'s file-fd mode.


---

<!-- chapters/13-the-hook-system.md — https://reverseengineeringclaudecode.com/chapters/13-the-hook-system -->

# Chapter 13 — The Hook System: Intercepting Every Lifecycle Event

> **Layer:** Layer 4 (Safety, Policy, Sandbox & Lifecycle Hooks)
> **Prerequisites:** [Chapter 02](02-the-tool-contract.md), [Chapter 06](06-executing-tools.md), [Chapter 07](07-the-heartbeat-query-loop.md), [Chapter 11](11-the-permission-engine.md), [Chapter 12](12-shell-execution-sandboxing-and-workspace-tools.md)
> **Primary Source Files:**
> - [`types/hooks.ts`](../../types/hooks.ts) — Zod response envelopes (`syncHookResponseSchema`, `hookJSONOutputSchema`), prompt-elicitation schemas, and internal `HookCallback` / `HookResult` types
> - [`schemas/hooks.ts`](../../schemas/hooks.ts) — cycle-breaking Zod schemas for the 4 persisted hook backends (`command`, `prompt`, `http`, `agent`) and `if` rule filters
> - [`entrypoints/sdk/coreTypes.ts`](../../entrypoints/sdk/coreTypes.ts) — runtime `HOOK_EVENTS` tuple (27 events); re-exports generated SDK hook input/output types (`coreTypes.generated.ts` is absent from this snapshot, though its source Zod schemas live in [`entrypoints/sdk/coreSchemas.ts`](../../entrypoints/sdk/coreSchemas.ts))
> - [`utils/hooks.ts`](../../utils/hooks.ts) — 5,022-line core hook engine: trust gate, matcher/dedup/`if`-filter pipeline, `execCommandHook()`, `executeHooks()`, `executeHooksOutsideREPL()`, and all 27 event entrypoints
> - [`utils/hooks/execHttpHook.ts`](../../utils/hooks/execHttpHook.ts) & [`utils/hooks/ssrfGuard.ts`](../../utils/hooks/ssrfGuard.ts) — HTTP webhook runner, header env-var allowlisting/CRLF sanitization, sandbox/env proxy routing, and DNS-rebinding-safe SSRF lookup guard
> - [`utils/hooks/execPromptHook.ts`](../../utils/hooks/execPromptHook.ts), [`utils/hooks/execAgentHook.ts`](../../utils/hooks/execAgentHook.ts) & [`utils/hooks/hookHelpers.ts`](../../utils/hooks/hookHelpers.ts) — single-shot structured-JSON LLM hooks and multi-turn verifier-agent hooks
> - [`utils/hooks/hooksConfigSnapshot.ts`](../../utils/hooks/hooksConfigSnapshot.ts), [`utils/hooks/hooksConfigManager.ts`](../../utils/hooks/hooksConfigManager.ts) & [`utils/hooks/hooksSettings.ts`](../../utils/hooks/hooksSettings.ts) — startup hook snapshotting, enterprise policy precedence, and `/hooks` UI aggregation
> - [`utils/hooks/sessionHooks.ts`](../../utils/hooks/sessionHooks.ts), [`utils/hooks/registerFrontmatterHooks.ts`](../../utils/hooks/registerFrontmatterHooks.ts) & [`utils/hooks/registerSkillHooks.ts`](../../utils/hooks/registerSkillHooks.ts) — ephemeral per-session/per-agent hooks, `FunctionHook` callbacks, and `once: true` self-removal
> - [`utils/hooks/AsyncHookRegistry.ts`](../../utils/hooks/AsyncHookRegistry.ts), [`utils/hooks/hookEvents.ts`](../../utils/hooks/hookEvents.ts) & [`utils/hooks/fileChangedWatcher.ts`](../../utils/hooks/fileChangedWatcher.ts) — non-blocking background hook polling, out-of-band progress event bus, and `CwdChanged`/`FileChanged` env watchers
> - [`services/tools/toolHooks.ts`](../../services/tools/toolHooks.ts) — `PreToolUse` / `PostToolUse` / `PostToolUseFailure` adapters and the `resolveHookPermissionDecision()` rule-preservation guard

> [!NOTE]
> **Snapshot boundaries:** Two type modules imported across the hook subsystem are absent from this checkout: `types/message.ts` (observed at call sites for `Message`, `AssistantMessage`, `AttachmentMessage`, `ProgressMessage`, and `HookResultMessage`) and `entrypoints/sdk/coreTypes.generated.ts` (re-exported by [`entrypoints/sdk/coreTypes.ts:19`](../../entrypoints/sdk/coreTypes.ts) for `HookInput` / `HookJSONOutput` types, whose authoritative Zod schemas are present in [`entrypoints/sdk/coreSchemas.ts:355-795`](../../entrypoints/sdk/coreSchemas.ts)).

---

## Why This Layer Exists

By the end of [Chapter 12](12-shell-execution-sandboxing-and-workspace-tools.md), the agent harness can enforce static permission rules (`allow`/`deny`/`ask`), run an auto-mode security classifier, and isolate shell processes inside an OS sandbox. Static policy covers *what* the agent may touch, but real engineering teams quickly need *programmable interception* across the entire lifecycle:

- Rewriting or blocking dangerous tool invocations before they reach the permission dialog (`PreToolUse`).
- Running a formatter, linter, or MCP response scrubber immediately after a tool finishes (`PostToolUse`).
- Answering permission prompts from an external enterprise policy server (`PermissionRequest`).
- Forcing the model to keep working if tests are still red or a structured output tool was skipped (`Stop`, `SubagentStop`).
- Reloading `direnv`/virtualenv exports when directories or `.envrc` files change (`CwdChanged`, `FileChanged`), delegating worktrees to Mercurial or Jujutsu (`WorktreeCreate`), or auditing mid-session config edits (`ConfigChange`).

Yet letting `.claude/settings.json` execute arbitrary shell commands, HTTP webhooks, or nested LLM queries inside an agent harness opens a minefield of failure modes: pre-trust remote code execution on untrusted repos, SSRF into cloud metadata endpoints (`169.254.169.254`), infinite recursion when a prompt hook submits a prompt, hidden mid-session hook tampering, subagent hook leakage, and permissive hooks punching holes through enterprise `deny` rules. Every abstraction in `utils/hooks/` and `services/tools/toolHooks.ts` exists to tame one of those hazards without turning every tool call into a latency cliff.

---

## 1. The 27-Event Lifecycle Bus, Matching Pipeline, and Dual Dispatch Paths

### The Problem

A single hook engine has to serve two wildly different runtime worlds. Inside the interactive `query()` generator loop, hooks need progress spinners, abort propagation, model-visible attachments, and structured permission/input overrides. Outside the REPL — during process shutdown (`SessionEnd`), chokidar file-watch events (`ConfigChange`, `FileChanged`), compaction (`PreCompact`), or MCP elicitations — there is no active turn stream or `ToolUseContext` at all. Worse, on the hot path (`PreToolUse` / `PostToolUse`), 99% of sessions have either zero user hooks or only internal analytics callbacks; allocating `JSON.stringify` payloads or spawning shells just to inspect `tool_name` would stall every tool batch.

### The Real Implementation

[`entrypoints/sdk/coreTypes.ts:25-53`](../../entrypoints/sdk/coreTypes.ts) defines the canonical 27-member `HOOK_EVENTS` tuple (mirrored with Zod input schemas in [`entrypoints/sdk/coreSchemas.ts:355-795`](../../entrypoints/sdk/coreSchemas.ts) and UI descriptions in [`utils/hooks/hooksConfigManager.ts:26-267`](../../utils/hooks/hooksConfigManager.ts)):

| Lifecycle Family | Events (`HOOK_EVENTS`) | Primary `matchQuery` Field (`utils/hooks.ts:1616-1670`) | Dispatch Path |
| --- | --- | --- | --- |
| **Tools & Permissions** | `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, `PermissionRequest`, `PermissionDenied` | `tool_name` | `executeHooks()` |
| **Turn & Session** | `SessionStart`, `Setup`, `UserPromptSubmit`, `Stop`, `StopFailure`, `SessionEnd`, `Notification` | `source` / `trigger` / — / `error` / `reason` / `notification_type` | Mixed (`StopFailure`, `SessionEnd`, `Notification` outside REPL) |
| **Context & Compaction** | `PreCompact`, `PostCompact`, `InstructionsLoaded` | `trigger` / `load_reason` | `executeHooksOutsideREPL()` |
| **Subagents & Swarms** | `SubagentStart`, `SubagentStop`, `TeammateIdle`, `TaskCreated`, `TaskCompleted` | `agent_type` / — | `executeHooks()` |
| **MCP & Workspace** | `Elicitation`, `ElicitationResult`, `ConfigChange`, `WorktreeCreate`, `WorktreeRemove`, `CwdChanged`, `FileChanged` | `mcp_server_name` / `source` / — / `basename(file_path)` | `executeHooksOutsideREPL()` |

Two additional settings-configured command runners — `StatusLine` and `FileSuggestion` (`utils/hooks.ts:4584-4738`) — bypass event matching but reuse `execCommandHook()`, the trust gate, and managed-only policy. Separately, [`utils/hooks/postSamplingHooks.ts`](../../utils/hooks/postSamplingHooks.ts) maintains a programmatic-only registry (`registerPostSamplingHook`) not exposed in `settings.json`; for example, [`utils/hooks/skillImprovement.ts:175-182`](../../utils/hooks/skillImprovement.ts) registers a post-sampling LLM hook via [`utils/hooks/apiQueryHookHelper.ts`](../../utils/hooks/apiQueryHookHelper.ts) behind `feature('SKILL_IMPROVEMENT')` and GrowthBook flag `tengu_copper_panda`.

To break a circular dependency between `utils/settings/types.ts` and `utils/plugins/schemas.ts`, the persisted hook schemas live in [`schemas/hooks.ts`](../../schemas/hooks.ts), while the response envelopes live in [`types/hooks.ts`](../../types/hooks.ts) with a compile-time `type-fest` lockstep guard:

```ts
// types/hooks.ts:195-200
// Compile-time assertion that SDK and Zod types match
import type { IsEqual } from 'type-fest'
type Assert<T extends true> = T
type _assertSDKTypesMatch = Assert<
  IsEqual<SchemaHookJSONOutput, HookJSONOutput>
>
```

Before *any* hook runs — inside or outside the REPL — `executeHooks()` (`utils/hooks.ts:1978-1999`) and `executeHooksOutsideREPL()` (`utils/hooks.ts:3016-3036`) enforce three centralized gates in order:

1. `shouldDisableAllHooksIncludingManaged()` — enterprise `policySettings.disableAllHooks === true` kills everything.
2. `isEnvTruthy(process.env.CLAUDE_CODE_SIMPLE)` — simple/minimal mode disables all hooks.
3. `shouldSkipHookDueToTrust()` (`utils/hooks.ts:286-296`) — in interactive mode, **every** hook requires `checkHasTrustDialogAccepted()`; in non-interactive SDK mode, trust is implicit.

On hot paths (`PreToolUse`, `PostToolUseFailure`, `PermissionDenied`, `Stop`, `StopFailure`, `UserPromptSubmit`), callers first probe `hasHookForEvent()` (`utils/hooks.ts:1582-1593`), which intentionally over-approximates across all three hook sources so unconfigured sessions skip `createBaseHookInput()` path joins and matching completely. If only internal callbacks (`hook.type === 'callback' && hook.internal === true`, such as file-access analytics or commit attribution) match, `executeHooks()` takes a zero-overhead fast path (`utils/hooks.ts:2036-2067`) that skips OTEL spans, progress messages, `createCombinedAbortSignal`, and JSON processing — cutting `PostToolUse` overhead from **6.01µs to ~1.8µs (-70%)**.

When user hooks do exist, `getMatchingHooks()` (`utils/hooks.ts:1603-1874`) executes a four-stage funnel:

1. **Matcher filtering (`matchesPattern`, `utils/hooks.ts:1346-1381`):** Empty string or `*` matches all; pure alphanumeric/pipe strings (`Write|Edit`) run fast exact checks with `normalizeLegacyToolName()`; anything else compiles a `RegExp` tested against both `matchQuery` and `getLegacyToolNames(matchQuery)` so legacy patterns like `^Task$` keep matching `Agent`.
2. **Source-namespaced deduplication (`hookDedupKey`, `utils/hooks.ts:1453-1455, 1735-1806`):** Settings-file hooks share the `''` prefix so identical commands across user/project/local collapse (last-merged scope wins via `new Map`), while plugin and skill hooks prefix with `pluginRoot` or `skillRoot` so two plugins referencing `${CLAUDE_PLUGIN_ROOT}/hook.sh` never collide (`gh-29724`). Identity also folds in `shell` (defaulting to `'bash'`) and the `if` condition.
3. **Pre-spawn `if` condition filtering (`prepareIfConditionMatcher`, `utils/hooks.ts:1390-1421`):** Hooks on `PreToolUse`, `PostToolUse`, `PostToolUseFailure`, and `PermissionRequest` may declare an `if` field in permission-rule syntax (e.g., `"Bash(git *)"`, `"Read(*.ts)"`). Expensive work — tool lookup, Zod input parsing, and [Chapter 12](12-shell-execution-sandboxing-and-workspace-tools.md)'s `tool.preparePermissionMatcher()` (which invokes `parseForSecurity()` for Bash) — runs **once per event batch**, returning a closure evaluated per hook before spawning a single subprocess.
4. **Event-specific transport exclusions (`utils/hooks.ts:1850-1864`):** HTTP hooks are stripped from `SessionStart` and `Setup`.

```ts
// utils/hooks.ts:1390-1421
async function prepareIfConditionMatcher(
  hookInput: HookInput,
  tools: Tools | undefined,
): Promise<IfConditionMatcher | undefined> {
  if (
    hookInput.hook_event_name !== 'PreToolUse' &&
    hookInput.hook_event_name !== 'PostToolUse' &&
    hookInput.hook_event_name !== 'PostToolUseFailure' &&
    hookInput.hook_event_name !== 'PermissionRequest'
  ) {
    return undefined
  }

  const toolName = normalizeLegacyToolName(hookInput.tool_name)
  const tool = tools && findToolByName(tools, hookInput.tool_name)
  const input = tool?.inputSchema.safeParse(hookInput.tool_input)
  const patternMatcher =
    input?.success && tool?.preparePermissionMatcher
      ? await tool.preparePermissionMatcher(input.data)
      : undefined

  return ifCondition => {
    const parsed = permissionRuleValueFromString(ifCondition)
    if (normalizeLegacyToolName(parsed.toolName) !== toolName) {
      return false
    }
    if (!parsed.ruleContent) {
      return true
    }
    return patternMatcher ? patternMatcher(parsed.ruleContent) : false
  }
}
```

Once matched, `executeHooks()` lazily stringifies `hookInput` at most once per batch (`getJsonInput()`, `utils/hooks.ts:2124-2140`), yields a `hook_progress` message for every matched hook, and runs all hooks **concurrently** via [Chapter 01](01-atoms-types-stores-and-primitives.md)'s `all(hookPromises)` (`utils/hooks.ts:2744`). Independently of the REPL message stream, [`utils/hooks/hookEvents.ts`](../../utils/hooks/hookEvents.ts) broadcasts `started`, 1-second `.unref()`-ed `progress`, and `response` events for SDK consumers — always emitting `SessionStart` and `Setup` (`ALWAYS_EMITTED_HOOK_EVENTS`), buffering up to `MAX_PENDING_EVENTS = 100` events until `registerHookEventHandler()` attaches, and unlocking all 27 events when `setAllHookEventsEnabled(true)` is set (SDK `includeHookEvents` or `CLAUDE_CODE_REMOTE`).

### Hidden Invariants & Failure Modes

> [!WARNING]
> **The pre-trust RCE scar (`utils/hooks.ts:268-296`):** `captureHooksConfigSnapshot()` runs in `setup.ts:166` *before* the workspace trust dialog appears. Two historical bugs — `SessionEnd` firing when a user declined trust and `SubagentStop` firing before trust — forced `shouldSkipHookDueToTrust()` to be centralized inside `executeHooks()`, `executeHooksOutsideREPL()`, `executeStatusLineCommand()`, and `executeFileSuggestionCommand()`.

- **Never add Zod `.transform()` to `schemas/hooks.ts` (`schemas/hooks.ts:130-137`, `gh-24920` / `CC-79`):** `parseSettingsFile()` uses `HooksSchema`, and `updateSettingsForSource()` round-trips parsed objects through `JSON.stringify`. An earlier `.transform()` wrapping `AgentHookSchema.prompt` into a closure silently vanished on stringify, deleting users' prompts from `settings.json`.
- **Headless HTTP deadlock (`utils/hooks.ts:1850-1864`):** HTTP hooks are filtered out on `SessionStart` and `Setup` because in headless mode the sandbox network ask callback deadlocks before the `structuredInput` consumer loop has started.
- **Session-ID alignment on `StopFailure` (`utils/hooks.ts:3600-3604`):** `executeHooksOutsideREPL()` always queries hooks under the main `getSessionId()`, so `executeStopFailureHooks()` deliberately gates with `getSessionId()` rather than `agentId` to prevent passing the gate and failing execution.
- **Unblockable enterprise policy audits (`utils/hooks.ts:4232-4236`):** `executeConfigChangeHooks()` runs hooks when `policy_settings` changes so admins get audit logs, then overwrites `blocked: false` on every result so local hooks can never veto enterprise policy.

---

## 2. The Four Hook Execution Backends (Plus In-Process Callbacks & Functions)

### The Problem

Not every hook can — or should — shell out to `/bin/sh`. Teams want local shell scripts with cross-platform Windows support, remote HTTPS policy webhooks that cannot be abused for SSRF or secret exfiltration, cheap single-shot LLM judges for semantic guardrails, and full multi-turn verifier agents that can inspect the repo and conversation transcript before letting the main agent finish. Each backend requires a different isolation boundary.

### The Real Implementation

`HookCommandSchema` (`schemas/hooks.ts:176-189`) defines four persisted backends discriminated on `type`: `'command'`, `'http'`, `'prompt'`, and `'agent'`. Two additional in-memory backends — `'callback'` ([`types/hooks.ts:211-226`](../../types/hooks.ts)) and `'function'` ([`utils/hooks/sessionHooks.ts:24-31`](../../utils/hooks/sessionHooks.ts)) — serve SDK control hooks, internal telemetry hooks, and ephemeral validators.

#### Backend 1: Shell Command (`type: 'command'`) — `execCommandHook()`

[`utils/hooks.ts:747-1335`](../../utils/hooks.ts) runs shell hooks with a default 10-minute timeout (`TOOL_HOOK_EXECUTION_TIMEOUT_MS`, overridden to 1,500ms or `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` for `SessionEnd`, `utils/hooks.ts:166-182`). It builds directly on [Chapter 12](12-shell-execution-sandboxing-and-workspace-tools.md)'s shell primitives:

- **Dual shell dispatch (`utils/hooks.ts:790-811, 957-984`):** Resolves `hook.shell ?? DEFAULT_HOOK_SHELL` (`'bash'` vs `'powershell'`). Bash hooks on Windows run via `findGitBashPath()` (Cygwin/Git Bash, not `cmd.exe`), convert all injected paths with `windowsPathToPosixPath()`, auto-prepend `bash` for `.sh` scripts, and apply `CLAUDE_CODE_SHELL_PREFIX` via `formatShellPrefixCommand()`. PowerShell hooks spawn `getCachedPowerShellPath()` with `buildPowerShellArgs()` (`-NoProfile -NonInteractive -Command`), keep native Windows paths, and intentionally skip `.sh` auto-prepend, `SHELL_PREFIX`, and `CLAUDE_ENV_FILE` (since PowerShell writes `$env:FOO` syntax that bash cannot source).
- **Ordered template substitution & missing-plugin pre-check (`utils/hooks.ts:818-857`):** For plugin hooks, `execCommandHook()` checks `await pathExists(pluginRoot)` *before* spawning. Without that guard, `python3 <missing>.py` exits with code **2** — identical to the hook protocol's blocking code, which would brick `UserPromptSubmit` or `Stop` until restart! It then substitutes `${CLAUDE_PLUGIN_ROOT}` and `${CLAUDE_PLUGIN_DATA}` using function-form `.replace(..., () => path)` (avoiding `$`-pattern mangling on Windows UNC shares like `\\server\c$\plugin`) *before* `substituteUserConfigVariables()`, so user-entered config values containing `${CLAUDE_PLUGIN_ROOT}` are treated as opaque literals. Plugin options are also exported as `CLAUDE_PLUGIN_OPTION_<KEY>`.
- **Stable root, safe cwd, and `CLAUDE_ENV_FILE` (`utils/hooks.ts:816, 882-938`):** `CLAUDE_PROJECT_DIR` pins to `getProjectRoot()` (stable even inside a mid-session worktree), while `cwd` falls back from `getCwd()` to `getOriginalCwd()` if a worktree directory was deleted out from under AsyncLocalStorage. For `SessionStart`, `Setup`, `CwdChanged`, and `FileChanged`, `CLAUDE_ENV_FILE` points to a per-hook `.sh` file whose exports are sourced into subsequent `BashTool` commands.
- **Pipe-mode `wrapSpawn()`, newline-terminated stdin, and bidirectional prompt elicitation (`utils/hooks.ts:986-1282`):** Unlike `BashTool` (which uses file-fd output), hooks use `wrapSpawn()` in **pipe mode** so JS inspects `stdout` incrementally:
  1. Line 1 is sniffed for `{"async": true}` (`utils/hooks.ts:1117-1164`) to background immediately without blocking if the process emits more lines quickly.
  2. When `requestPrompt` is passed, `stdout` is parsed line-by-line against `promptRequestSchema` (`types/hooks.ts:28-47`), serialized through `promptChain`, and answered over open `stdin` as `{ prompt_response, selected }\n`; processed prompt lines are recorded in `processedPromptLines` and stripped by content match on close (`utils/hooks.ts:1243-1249`) so elicitation frames never leak into `parseHookOutput()`.
  3. Input JSON is always written with a trailing `\n` (`jsonInput + '\n'`, `utils/hooks.ts:1006, 1210`) — a production scar (`gh-30509` / `CC-161`) because bash `read -r line` exits 1 on EOF without a newline!

#### Backend 2: HTTP Webhook (`type: 'http'`) — `execHttpHook()` + `ssrfGuard.ts`

[`utils/hooks/execHttpHook.ts`](../../utils/hooks/execHttpHook.ts) POSTs `jsonInput` to `hook.url` with layered defenses against project-configured exfiltration and SSRF:

1. **URL allowlist before any I/O (`execHttpHook.ts:137-145`):** Reads `allowedHttpHookUrls` from `getInitialSettings()` (`undefined` = unrestricted, `[]` = block all, non-empty = wildcard `*` match).
2. **Double-gated env-var interpolation & CRLF sanitization (`execHttpHook.ts:76-108, 161-172`):** Header values may reference `$VAR` or `${VAR}`, but only variables in the intersection of `hook.allowedEnvVars` and enterprise `settings.httpHookAllowedEnvVars` resolve; everything else becomes `''`, and `sanitizeHeaderValue()` strips `\r`, `\n`, and `\x00` to prevent header injection from poisoned env vars.
3. **DNS-rebinding-proof SSRF guard (`utils/hooks/ssrfGuard.ts:42-283`):** Rather than pre-resolving DNS and letting axios resolve again (a classic TOCTOU DNS-rebinding window), `execHttpHook()` passes `ssrfGuardedLookup` directly into axios's `lookup` option, alongside `maxRedirects: 0`:

```ts
// utils/hooks/ssrfGuard.ts:245-268 (trimmed)
dnsLookup(hostname, { all: true }, (err, addresses) => {
  if (err) {
    callback(err, '')
    return
  }

  for (const { address } of addresses) {
    if (isBlockedAddress(address)) {
      callback(ssrfError(hostname, address), '')
      return
    }
  }

  const first = addresses[0]
  if (!first) {
    callback(Object.assign(new Error(`ENOTFOUND ${hostname}`), {
      code: 'ENOTFOUND', hostname,
    }), '')
    return
  }
  // ... returns validated address(es) directly to the socket
})
```

`isBlockedAddress()` rejects `0.0.0.0/8`, `10.0.0.0/8`, `100.64.0.0/10` (RFC 6598 CGNAT — used by Alibaba Cloud metadata `100.100.100.200`), `169.254.0.0/16` (AWS/GCP/Azure link-local metadata), `172.16.0.0/12`, `192.168.0.0/16`, IPv6 `::`, `fc00::/7`, `fe80::/10`, AND **IPv4-mapped IPv6 in any representation** — `expandIPv6Groups()` + `extractMappedIPv4()` (`ssrfGuard.ts:133-204`) unpack hex-form addresses like `::ffff:a9fe:a9fe` (`169.254.169.254`) before delegating to `isBlockedV4()`. Loopback (`127.0.0.0/8`, `::1`) is intentionally allowed so developers can run local policy servers.

4. **Proxy handoff (`execHttpHook.ts:21-41, 176-217`):** `getSandboxProxyConfig()` dynamically imports `SandboxManager` (breaking a static cycle `sandbox-adapter → settings → ... → hooks → execHttpHook`) and awaits `SandboxManager.waitForNetworkInitialization()`. When either the sandbox proxy or an env-var proxy (`HTTP_PROXY`/`HTTPS_PROXY`, respecting `NO_PROXY`) is active, `lookup` is set to `undefined` — because the proxy resolves the target's DNS, and running `ssrfGuardedLookup` would mistakenly block a corporate proxy hosted on `10.0.0.1:3128`!

HTTP hooks must return valid JSON (`parseHttpHookOutput`, `utils/hooks.ts:453-487`; empty body normalizes to `{}`). Non-2xx statuses, network errors, and schema failures all yield `non_blocking_error`.

#### Backend 3: Single-Shot LLM Prompt Hook (`type: 'prompt'`) — `execPromptHook()`

[`utils/hooks/execPromptHook.ts`](../../utils/hooks/execPromptHook.ts) turns a natural-language check into a single structured API call (`queryModelWithoutStreaming()`, `querySource: 'hook_prompt'`, default 30s timeout, `model: hook.model ?? getSmallFastModel()`, `thinkingConfig: { type: 'disabled' }`):

- Expands `$ARGUMENTS` via `addArgumentsToPrompt()` and builds `createUserMessage()` directly — deliberately skipping `processUserInput()` so a `UserPromptSubmit` prompt hook never triggers infinite recursion (`execPromptHook.ts:40-42`).
- Prepends conversation `messages` when available (e.g., on `Stop`), constrains output via `outputFormat: { type: 'json_schema' }` to `{ ok: boolean, reason?: string }`, and validates with `hookResponseSchema()`.
- `{ ok: false, reason }` returns `outcome: 'blocking'`, `blockingError`, `preventContinuation: true`, and `stopReason: reason`. Malformed JSON or API failures degrade safely to `non_blocking_error`.

#### Backend 4: Multi-Turn Agent Hook (`type: 'agent'`) — `execAgentHook()`

[`utils/hooks/execAgentHook.ts`](../../utils/hooks/execAgentHook.ts) escalates verification to a full multi-turn `query()` loop (`querySource: 'hook_agent'`, default 60s timeout, `MAX_AGENT_TURNS = 50`, `model: hook.model ?? getSmallFastModel()`, `thinkingConfig: { type: 'disabled' }`). Running an agent inside a hook demands four explicit containment boundaries:

```ts
// utils/hooks/execAgentHook.ts:100-160 (trimmed)
const tools: Tool[] = [
  ...filteredTools.filter(
    tool => !ALL_AGENT_DISALLOWED_TOOLS.has(tool.name),
  ),
  structuredOutputTool,
]
// ...
const hookAgentId = asAgentId(`hook-agent-${randomUUID()}`)
const agentToolUseContext: ToolUseContext = {
  ...toolUseContext,
  agentId: hookAgentId,
  abortController: hookAbortController,
  // ...
  getAppState() {
    const appState = toolUseContext.getAppState()
    const existingSessionRules =
      appState.toolPermissionContext.alwaysAllowRules.session ?? []
    return {
      ...appState,
      toolPermissionContext: {
        ...appState.toolPermissionContext,
        mode: 'dontAsk' as const,
        alwaysAllowRules: {
          ...appState.toolPermissionContext.alwaysAllowRules,
          session: [...existingSessionRules, `Read(/${transcriptPath})`],
        },
      },
    }
  },
}
registerStructuredOutputEnforcement(toolUseContext.setAppState, hookAgentId)
```

1. **Tool filtering:** Removes any parent `StructuredOutput` tool (avoiding duplicate-schema clashes under `--json-schema`) and strips `ALL_AGENT_DISALLOWED_TOOLS` so a `Stop` verifier cannot spawn recursive subagents or enter plan mode.
2. **Non-interactive transcript permission:** Overrides `getAppState()` to force `mode: 'dontAsk'` while injecting a scoped session allow rule `Read(/${transcriptPath})` so the verifier can inspect the conversation log without hanging on a dialog.
3. **Self-bootstrapped structured output enforcement:** Calls `registerStructuredOutputEnforcement()` (`utils/hooks/hookHelpers.ts:70-83`), which registers a session-scoped `Stop` **function hook** under `hookAgentId` verifying `hasSuccessfulToolCall(messages, SYNTHETIC_OUTPUT_TOOL_NAME)`. The moment the `structured_output` attachment arrives, `execAgentHook()` aborts `hookAbortController`, breaks out of `for await`, and calls `clearSessionHooks(toolUseContext.setAppState, hookAgentId)` (`execAgentHook.ts:212-233`).
4. **Fail-open exhaustion (`execAgentHook.ts:236-268`):** Hitting `MAX_AGENT_TURNS` or exiting without structured output logs telemetry (`tengu_agent_stop_hook_max_turns` / `tengu_agent_stop_hook_error`) and returns `outcome: 'cancelled'` rather than trapping the user in an unbreakable stop loop.

### Hidden Invariants & Failure Modes

- **Outside-REPL backend limits (`utils/hooks.ts:3152-3186`):** `executeHooksOutsideREPL()` only executes `command`, `http`, and `callback` hooks; `prompt`, `agent`, and `function` hooks return non-blocking errors because no `ToolUseContext` or `messages` array exists outside the query loop.
- **No timeout double-stacking on HTTP hooks (`utils/hooks.ts:2299-2307`):** `executeHooks()` passes the raw parent `signal` (not the wrapper's `abortSignal`) to `execHttpHook()`, because `execHttpHook()` constructs its own combined timeout signal internally.

---

## 3. Exit Codes, JSON Decision Envelopes, and Safe Permission Composition

### The Problem

Hooks speak through two channels — legacy POSIX exit codes and structured JSON envelopes — and multiple hooks run concurrently for the same event. That creates three subtle composition hazards:
1. Conflicting decisions from parallel `PreToolUse` hooks (one says `'allow'`, another says `'deny'`).
2. A hook returning `{ permissionDecision: "allow", updatedInput: ... }` attempting to bypass a user or enterprise `settings.json` `deny`/`ask` rule (the exact class of bug flagged as `inc-4788` in source comments).
3. `Stop` hooks needing to either *continue* the turn with corrective feedback (exit 2 / blocking error) or *halt* the entire turn immediately (`continue: false`).

### The Real Implementation

#### Exit Codes vs. `syncHookResponseSchema`

For command hooks, `executeHooks()` checks `parseHookOutput(result.stdout)` first (`utils/hooks.ts:2500-2697`). If `stdout.trim()` starts with `{`, it validates against `hookJSONOutputSchema()` (`types/hooks.ts:50-176`) and dispatches through `processHookJSONOutput()` (`utils/hooks.ts:489-737`). Otherwise, it falls back to three exit-code semantics:

| Exit Code / Envelope | Outcome | Effect on Execution |
| --- | --- | --- |
| Exit `0` (plain text) | `'success'` | `stdout` becomes `hook_success` attachment content (model-visible on `UserPromptSubmit`, `SessionStart`, `Setup`, `SubagentStart`; transcript-visible on `PostToolUse`). |
| Exit `2` (plain text) | `'blocking'` | `stderr` becomes `blockingError`, blocking tool call (`PreToolUse`), prompt (`UserPromptSubmit`), stop (`Stop`/`SubagentStop`), task creation/completion, or config change (`ConfigChange`). |
| Other non-zero exit | `'non_blocking_error'` | `stderr` shown to user only; execution proceeds. |
| JSON `continue: false` | `preventContinuation: true` | Halts turn continuation with optional `stopReason` (takes precedence over `blockingErrors` in `Stop` hooks). |
| JSON `decision: 'approve' \| 'block'` | Legacy top-level decision | Maps to `permissionBehavior: 'allow'` or `'deny'` + `blockingError`. |
| JSON `hookSpecificOutput` | Event-scoped structured output | Validated against `expectedHookEvent` (`utils/hooks.ts:583-590`); carries `permissionDecision`, `updatedInput`, `additionalContext`, `updatedMCPToolOutput`, `permissionRequestResult`, `retry`, `watchPaths`, `worktreePath`, or elicitation actions. |

Notice two UI/transcript deduplication scars in this layer: JSON-output hooks create their `hook_success` attachment with `content: ''` (`utils/hooks.ts:725-729`) so `messages.ts` suppresses noisy `"X hook success: Success"` reminders (context travels via `additionalContext` instead), and [`services/tools/toolHooks.ts:90-103`](../../services/tools/toolHooks.ts) skips `hook_blocking_error` messages already yielded alongside `result.blockingError` on `PostToolUse` / `PostToolUseFailure` (`#31301`).

#### Parallel Precedence and Three-Way `updatedInput`

As concurrent hooks settle via `all(hookPromises)`, `executeHooks()` aggregates `permissionBehavior` monotonically with strict precedence **`deny > ask > allow`** (`utils/hooks.ts:2820-2847`): once `'deny'` is observed, neither `'ask'` nor `'allow'` can downgrade it; `'ask'` overrides `'allow'`; `'passthrough'` makes no decision.

Crucially, `PreToolUse` hooks can rewrite `updatedInput` in **three** distinct ways:
1. Paired with `permissionDecision: 'allow'` (`utils/hooks.ts:2850-2868`).
2. Paired with `permissionDecision: 'ask'` (rewritten input shown in the prompt dialog).
3. **Passthrough** — returning `updatedInput` with *no* `permissionDecision` (`utils/hooks.ts:2873-2880` → `toolHooks.ts:558-563` → `toolExecution.ts:834-838`), rewriting `processedInput` while letting normal permission evaluation run untouched.

#### The `inc-4788` Invariant: `resolveHookPermissionDecision()`

After `runPreToolUseHooks()` finishes in [`services/tools/toolExecution.ts:800-862`](../../services/tools/toolExecution.ts), `toolExecution.ts:921` hands `hookPermissionResult` to `resolveHookPermissionDecision()` in [`services/tools/toolHooks.ts:332-433`](../../services/tools/toolHooks.ts) (shared with `REPLTool/toolWrappers.ts` so REPL inner calls enforce identical policy):

```ts
// services/tools/toolHooks.ts:347-406
  if (hookPermissionResult?.behavior === 'allow') {
    const hookInput = hookPermissionResult.updatedInput ?? input

    // Hook provided updatedInput for an interactive tool — the hook IS the
    // user interaction (e.g. headless wrapper that collected AskUserQuestion
    // answers). Treat as non-interactive for the rule-check path.
    const interactionSatisfied =
      requiresInteraction && hookPermissionResult.updatedInput !== undefined

    if ((requiresInteraction && !interactionSatisfied) || requireCanUseTool) {
      return {
        decision: await canUseTool(
          tool, hookInput, toolUseContext, assistantMessage, toolUseID,
        ),
        input: hookInput,
      }
    }

    // Hook allow skips the interactive prompt, but deny/ask rules still apply.
    const ruleCheck = await checkRuleBasedPermissions(
      tool,
      hookInput,
      toolUseContext,
    )
    if (ruleCheck === null) {
      return { decision: hookPermissionResult, input: hookInput }
    }
    if (ruleCheck.behavior === 'deny') {
      return { decision: ruleCheck, input: hookInput }
    }
    // ask rule — dialog required despite hook approval
    return {
      decision: await canUseTool(
        tool, hookInput, toolUseContext, assistantMessage, toolUseID,
      ),
      input: hookInput,
    }
  }
```

> [!IMPORTANT]
> **Hook `'allow'` never bypasses `settings.json` `deny` or `ask` rules.** `resolveHookPermissionDecision()` runs `checkRuleBasedPermissions()` against the *post-rewrite* `hookInput`, closing the escalation vector where a hook rewrites a benign command into a denied command and simultaneously approves it. Only when `ruleCheck === null` (and neither `requireCanUseTool` nor an unsatisfied `requiresUserInteraction()` applies) does hook `'allow'` skip the interactive prompt.

When `hookPermissionResult` is `'ask'`, `resolveHookPermissionDecision()` passes it as `forceDecision` to `canUseTool()` (`toolHooks.ts:415-432`) so the permission dialog displays the hook's explanation and `updatedInput`. Before `tool.call()` executes (`toolExecution.ts:1181-1205`), if a hook modified or schema-parsed `processedInput` from a `backfillObservableInput` clone while leaving `file_path` equal to the expanded backfill value, `toolExecution.ts` restores the model's original `file_path` string so transcript and VCR hashes stay stable.

#### `PermissionRequest`, `PermissionDenied`, `PostToolUse`, and `Stop`

- **`PermissionRequest` (`hooks/toolPermission/PermissionContext.ts:216-263`):** Fires inside the permission dialog handler when interactive approval would be shown. Returning `{ behavior: 'allow', updatedInput?, updatedPermissions? }` persists permanent permission updates via `handleHookAllow()` and approves without prompting; returning `{ behavior: 'deny', message?, interrupt: true }` rejects and calls `toolUseContext.abortController.abort()`.
- **`PermissionDenied` (`services/tools/toolExecution.ts:1075-1101`, gated on `feature('TRANSCRIPT_CLASSIFIER')`):** Fires after an auto-mode classifier denial; if any hook yields `retry: true`, `toolExecution.ts` appends an `isMeta: true` user message notifying the model it may retry.
- **`PostToolUse` (`services/tools/toolHooks.ts:39-191`):** Can append `additionalContext`, stop continuation (`continue: false`), or replace an MCP tool's output via `updatedMCPToolOutput` (strictly guarded by `isMcpTool(tool)` at `toolHooks.ts:146`, so hooks cannot spoof built-in tool output shapes).
- **`Stop` / `SubagentStop` (`query/stopHooks.ts:180-455`):** `executeStopHooks()` switches to `'SubagentStop'` whenever `subagentId` is present and passes `stop_hook_active` so hooks can detect re-entry and avoid infinite loops. Blocking errors become `isMeta: true` user messages that keep `query()` iterating — **unless** any hook sets `preventContinuation: true`, which short-circuits and drops `blockingErrors` (`query/stopHooks.ts:325-327`). For swarm teammates, `TaskCompleted` (for each in-progress owned task) and `TeammateIdle` execute right after `Stop` passes (`query/stopHooks.ts:335-453`).

### Hidden Invariants & Failure Modes

- **Interactive-tool override (`toolHooks.ts:350-355`):** For tools declaring `requiresUserInteraction()` (like `AskUserQuestion`), a hook returning `allow` *without* `updatedInput` still falls into `canUseTool`; returning `allow` *with* `updatedInput` sets `interactionSatisfied = true` because the hook itself collected the user's answer.
- **No double `hook_blocking_error` (`toolHooks.ts:90-103, 245-255`):** Exit-code-2 hooks only yield `{ blockingError }`, whereas JSON `{ decision: 'block' }` hooks yield both `{ blockingError }` and `{ message: hook_blocking_error }`. `runPostToolUseHooks` and `runPostToolUseFailureHooks` filter out the duplicate attachment message explicitly.

---

## 4. Consistency Across Time, Subagents, and Background Execution

### The Problem

Three operational dynamics threaten hook reliability in long-running sessions:
1. **Mid-session settings drift:** Re-reading `.claude/settings.json` on every tool call would let an agent (or rogue script) silently install a hook mid-session; yet legitimate `/hooks` edits, `--worktree` switches, and enterprise policy pushes *do* need controlled reloads.
2. **Subagent and skill isolation:** Skills and subagents declare temporary frontmatter hooks, and `StructuredOutput` registers temporary `Stop` function hooks. Cross-session leakage breaks parent turns, while naive immutable copies of `AppState` trigger O(N²) overhead and UI listener storms under parallel workflow agents.
3. **Blocking latency vs. background wakeups:** Long verification scripts cannot block every tool call synchronously, but backgrounding naively drops stderr or fails to notify an idle agent when a background check fails.

### The Real Implementation

#### Startup Snapshots & Three-Source Merging (`hooksConfigSnapshot.ts`, `hooksConfigManager.ts`)

[`setup.ts:166`](../../setup.ts) calls `captureHooksConfigSnapshot()` immediately after `setCwd(cwd)` (and re-calls `updateHooksConfigSnapshot()` at `setup.ts:284` after `--worktree` changes directories, at `ExitWorktreeTool.ts:140` on worktree exit, and in `applySettingsChange.ts:42` on approved settings reloads). Inside [`utils/hooks/hooksConfigSnapshot.ts:18-53`](../../utils/hooks/hooksConfigSnapshot.ts), `getHooksFromAllowedSources()` enforces a four-tier enterprise precedence ladder:

1. `policySettings.disableAllHooks === true` → `{}` (all hooks disabled, including managed).
2. `policySettings.allowManagedHooksOnly === true` → `policySettings.hooks ?? {}` (ignores user, project, local, plugin, and session hooks).
3. `isRestrictedToPluginOnly('hooks')` → `policySettings.hooks ?? {}` (blocks user/project/local settings hooks, while plugin hooks and admin-trusted agent frontmatter hooks remain permitted — gated at registration time in `tools/AgentTool/runAgent.ts:564-568` where `agentDefinition.source` is known).
4. Non-managed `mergedSettings.disableAllHooks === true` → `policySettings.hooks ?? {}` (**non-managed settings cannot disable enterprise managed hooks**).

`updateHooksConfigSnapshot()` calls `resetSettingsCache()` first (`hooksConfigSnapshot.ts:104-112`) so external edits followed immediately by `/hooks` never read stale cached settings before chokidar's stability threshold elapses.

At execution time, `getHooksConfig()` (`utils/hooks.ts:1492-1566`) assembles matchers from three independent registries:
1. **Snapshot settings hooks** (`getHooksConfigFromSnapshot()`).
2. **Process-level registered hooks** (`getRegisteredHooks()` in [`bootstrap/state.ts:1419-1465`](../../bootstrap/state.ts) — plugin native hooks carrying `pluginRoot`, SDK control callbacks, and internal hooks). When `shouldAllowManagedHooksOnly()` is true, entries with `'pluginRoot' in matcher` are skipped (`utils/hooks.ts:1524`).
3. **Ephemeral session hooks** (`appState.sessionHooks`, skipped entirely under `managedOnly` so agent/skill frontmatter cannot bypass enterprise lock-down).

For the `/hooks` management UI, [`utils/hooks/hooksConfigManager.ts`](../../utils/hooks/hooksConfigManager.ts) and [`utils/hooks/hooksSettings.ts`](../../utils/hooks/hooksSettings.ts) group hooks by event and matcher, deduplicate identical resolved file paths (when running from `$HOME`, `userSettings` and `projectSettings` both resolve to `~/.claude/settings.json`, `hooksSettings.ts:109-122`), hide all settings hooks when `allowManagedHooksOnly` is active, and expose `[ANT-ONLY] Built-in Hook` entries only under `process.env.USER_TYPE === 'ant'` (`hooksConfigManager.ts:346-359`).

#### Subagent & Skill Scoping and the `Map` Identity Scar (`sessionHooks.ts`)

[`utils/hooks/sessionHooks.ts`](../../utils/hooks/sessionHooks.ts) scopes every temporary hook to a `sessionId` — either the main session ID or a subagent's `agentId` (`utils/hooks.ts:2003`). Three helpers build on it:

- [`registerFrontmatterHooks()`](../../utils/hooks/registerFrontmatterHooks.ts) (called from `tools/AgentTool/runAgent.ts:568` with `isAgent = true`, cleaned up via `clearSessionHooks(rootSetAppState, agentId)` at `runAgent.ts:821`): automatically converts `Stop` hooks to `SubagentStop` because subagents fire `SubagentStop` (`registerFrontmatterHooks.ts:40-45`).
- [`registerSkillHooks()`](../../utils/hooks/registerSkillHooks.ts) (called from `utils/processUserInput/processSlashCommand.tsx:877`): preserves `skillRoot` (exported as `CLAUDE_PLUGIN_ROOT` for skill/plugin parity) and implements `once: true` by registering an `onHookSuccess` callback that invokes `removeSessionHook()` after the first `outcome === 'success'` (`utils/hooks.ts:2919-2927`).
- `addFunctionHook()` (`sessionHooks.ts:93-115`): attaches in-memory `FunctionHook` callbacks (e.g., `registerStructuredOutputEnforcement` and `teammateInit.ts:98`).

The container type itself carries a textbook performance scar:

```ts
// utils/hooks/sessionHooks.ts:48-62
/**
 * Map (not Record) so .set/.delete don't change the container's identity.
 * Mutator functions mutate the Map and return prev unchanged, letting
 * store.ts's Object.is(next, prev) check short-circuit and skip listener
 * notification. Session hooks are ephemeral per-agent runtime callbacks,
 * never reactively read (only getAppState() snapshots in the query loop).
 *
 * This matters under high-concurrency workflows: parallel() with N
 * schema-mode agents fires N addFunctionHook calls in one synchronous
 * tick. With a Record + spread, each call cost O(N) to copy the growing
 * map (O(N²) total) plus fired all ~30 store listeners. With Map: .set()
 * is O(1), return prev means zero listener fires.
 */
export type SessionHooksState = Map<string, SessionStore>
```

#### Non-Blocking Async Hooks, `asyncRewake`, and Reactive Env Watchers

Command hooks can opt into background execution either statically (`async: true` or `asyncRewake: true` in `BashCommandHookSchema`) or dynamically by emitting `{"async": true, "asyncTimeout": ...}` on stdout line 1 (`utils/hooks.ts:995-1030, 1117-1151`, suppressed if `forceSyncExecution` is true). From there, `executeInBackground()` (`utils/hooks.ts:184-265`) splits into **two** distinct delivery engines:

1. **Standard Async (`AsyncHookRegistry.ts`):** Calls `shellCommand.background(processId)` and registers a `PendingAsyncHook` (default 15s timeout, 1s progress polling). Before each subsequent model turn, `getAsyncHookResponseAttachments()` (`utils/attachments.ts:3464-3518`) polls `checkForAsyncHookResponses()` (`AsyncHookRegistry.ts:113-268`), which uses `Promise.allSettled()` so one throwing hook cannot orphan another's cleanup, scans completed stdout for the first non-async JSON line, marks `responseAttachmentSent = true`, emits `hookResponse`, invalidates the session env cache if a `SessionStart` hook completed (`AsyncHookRegistry.ts:257-262`), and yields `async_hook_response` attachments. In headless/print mode, `cli/print.ts:2674, 4134` calls `finalizePendingAsyncHooks()` to flush completed hooks and kill still-running stragglers on shutdown.
2. **Wake-on-Failure (`asyncRewake: true`, `utils/hooks.ts:205-246`):** Bypasses `AsyncHookRegistry` *and* deliberately skips `shellCommand.background()` — because `background()` invokes `taskOutput.spillToDisk()`, under which `getStderr()` returns `''`! Instead, the `StreamWrapper`s keep piping into in-memory `TaskOutput` buffers; when `shellCommand.result` resolves, it yields one tick via `await new Promise(resolve => setImmediate(resolve))` so pending stdio `'data'` events drain after `'exit'`, then on exit code `2` enqueues a `task-notification` via `enqueuePendingNotification()` to wake an idle model or inject mid-query.

Finally, [`utils/hooks/fileChangedWatcher.ts`](../../utils/hooks/fileChangedWatcher.ts) closes the loop for environment-sync hooks: `initializeFileChangedWatcher(cwd)` (`setup.ts:172`) watches pipe-separated filenames from `FileChanged` matchers (e.g., `.envrc|.env`) plus dynamic `watchPaths` returned by `SessionStart`, `CwdChanged`, or `FileChanged` hooks (`chokidar` with `stabilityThreshold: 500`). Whenever `CwdChanged` or `FileChanged` runs, `executeEnvHooks()` (`utils/hooks.ts:4241-4258`) invalidates the session environment cache so new `CLAUDE_ENV_FILE` exports immediately apply to future `BashTool` commands.

### Hidden Invariants & Failure Modes

- **Mirroring `managedOnly` in existence checks (`utils/hooks.ts:4910-4920`):** `hasWorktreeCreateHook()` must skip plugin hooks when `shouldAllowManagedHooksOnly()` is true — mirroring `getHooksConfig()`. Otherwise `hasWorktreeCreateHook()` would return `true`, skip native git worktree setup, and then `executeWorktreeCreateHook()` would find zero runnable hooks and throw.
- **`onHookSuccess` scoping nuance (`utils/hooks.ts:2907-2928`):** The `onHookSuccess` lookup calls `getSessionId()` (the main session ID) rather than `toolUseContext?.agentId`, which works for main-session `registerSkillHooks` (`once: true`) while subagent frontmatter hooks rely on `clearSessionHooks(..., agentId)` at teardown.
- **Post-exit stream drain (`utils/hooks.ts:219-222`):** In `asyncRewake`, `shellCommand.result` resolves on process `'exit'` before final stdout/stderr `'data'` chunks finish flushing into `TaskOutput`; the `setImmediate` yield prevents truncating the very stderr message meant to wake the model.

---

## Putting the Layer Together

First, the full hook configuration, matching, and multi-backend execution pipeline:

```mermaid
flowchart TD
    S1["Snapshot Settings (hooksConfigSnapshot.ts)"] --> M["getHooksConfig()"]
    S2["STATE.registeredHooks (plugins + SDK callbacks)"] --> M
    S3["AppState.sessionHooks Map (skills + subagents + functions)"] --> M

    M --> G["Central Gates: disableAllHooks / CLAUDE_CODE_SIMPLE / trust"]
    G --> F["getMatchingHooks(): pattern -> dedup -> if-rule AST -> HTTP filter"]

    F --> B1["command: execCommandHook() (bash / pwsh / pipe wrapSpawn)"]
    F --> B2["http: execHttpHook() + ssrfGuardedLookup()"]
    F --> B3["prompt: execPromptHook() (single-shot json_schema)"]
    F --> B4["agent: execAgentHook() (50-turn dontAsk query())"]
    F --> B5["callback / function (in-process fast path)"]

    B1 -- "async / line-1 async" --> AR["AsyncHookRegistry -> attachments.ts poll"]
    B1 -- "asyncRewake + exit 2" --> QN["enqueuePendingNotification() (task-notification)"]

    B1 & B2 & B3 & B4 & B5 --> AGG["all() parallel merge: deny > ask > allow + updatedInput"]
    AGG --> TH["toolHooks.ts / stopHooks.ts / PermissionContext.ts"]
```

And the exact tool-execution interception envelope (where hooks compose safely with [Chapter 11](11-the-permission-engine.md)'s permission engine):

```
  tool_use (Zod parsed + validateInput + backfillObservableInput)
     │
     ▼
  runPreToolUseHooks() ──► parallel hooks ──► precedence: deny > ask > allow
     │                                        (+ updatedInput on passthrough)
     ▼
  resolveHookPermissionDecision()
     ├─ hook 'deny'  ─────────────────────────► tool_result (is_error: true)
     ├─ hook 'allow' ──► checkRuleBasedPermissions(tool, hookInput)
     │                      ├─ deny rule ─────► DENIED (inc-4788 invariant!)
     │                      ├─ ask / reqUI ───► canUseTool() ─► PermissionReq
     │                      └─ null ──────────► execute tool.call(callInput)
     └─ 'ask' / none ──► canUseTool(forceDecision) ─► PermissionRequest hooks
                                                        │
     ┌───────────────────── denied (auto-mode) ◄────────┤ allowed
     ▼                                                  ▼
  PermissionDenied hooks (retry?)               tool.call(callInput)
                                                   ├─ ok  ─► PostToolUse
                                                   │         (updatedMCPOut?)
                                                   └─ err ─► PostToolUseFail
```

---

## How This Snaps Into the Next Layer

Chapter 13's hook snapshot and `ConfigChange` event form a tight bidirectional contract with **[Chapter 14 (Configuration, Settings Precedence, and Enterprise Policy)](14-configuration-settings-and-enterprise-policy.md)**:

- **Hooks gate live settings reloads:** In [`utils/settings/changeDetector.ts:290-301`](../../utils/settings/changeDetector.ts) and [`utils/settings/changeDetector.ts:343-353`](../../utils/settings/changeDetector.ts), every detected disk edit or deletion fires `executeConfigChangeHooks()` *before* calling `fanOut(source)`. If any hook exits `2` or returns `{ decision: 'block' }` (`hasBlockingResult()`), the reload is vetoed — except for `policy_settings`, where [`utils/hooks.ts:4234-4236`](../../utils/hooks.ts) forces `blocked: false` so enterprise policy always lands.
- **Settings reloads refresh the hook snapshot:** Once `fanOut(source)` passes, [`utils/settings/applySettingsChange.ts:42`](../../utils/settings/applySettingsChange.ts) invokes `updateHooksConfigSnapshot()` alongside `loadAllPermissionRulesFromDisk()`, keeping both interactive (`AppState.tsx`) and headless (`cli/print.ts`) hook snapshots synchronized with disk.
- **Enterprise policy knobs live in the settings schema:** [`utils/settings/types.ts:459-499`](../../utils/settings/types.ts) declares `disableAllHooks`, `allowManagedHooksOnly`, `allowedHttpHookUrls`, and `httpHookAllowedEnvVars` and imports `HooksSchema` from [`schemas/hooks.ts`](../../schemas/hooks.ts) — the exact multi-source settings hierarchy Chapter 14 dissects next.

---

## Reading Exercises & Code Checkpoints

1. **Audit the `inc-4788` permission-composition invariant and `updatedInput` backfill restoration:**
   Run `rg -n "checkRuleBasedPermissions|interactionSatisfied|hookUpdatedInput|backfilledClone" services/tools/toolHooks.ts services/tools/toolExecution.ts` and trace why `resolveHookPermissionDecision()` evaluates `checkRuleBasedPermissions()` on `hookInput` (not the original `input`) and why `toolExecution.ts:1189-1205` restores `callInput.file_path` when unchanged from `backfilledClone`.
2. **Verify the SSRF guard's IPv6 hex-mapped defense and proxy bypass:**
   Inspect [`utils/hooks/ssrfGuard.ts:88-204`](../../utils/hooks/ssrfGuard.ts) and [`utils/hooks/execHttpHook.ts:176-217`](../../utils/hooks/execHttpHook.ts). Trace how `::ffff:a9fe:a9fe` is decoded into `169.254.169.254`, why `100.64.0.0/10` is blocked while `127.0.0.0/8` is allowed, and why `lookup` becomes `undefined` under `sandboxProxy` or `envProxyActive`.
3. **Trace the three hook registries, `allowManagedHooksOnly`, and the `SessionHooksState` `Map` trick:**
   Run `rg -n "getHooksConfigFromSnapshot|getRegisteredHooks|sessionHooks|shouldAllowManagedHooksOnly" utils/hooks.ts utils/hooks/hooksConfigSnapshot.ts utils/hooks/sessionHooks.ts` and confirm why `hasWorktreeCreateHook()` (`utils/hooks.ts:4910-4920`) must mirror `getHooksConfig()`'s `pluginRoot` filter, and why `sessionHooks.ts` mutates `prev.sessionHooks` in place and returns `prev`.
4. **Follow the Chapter 13 ↔ Chapter 14 `ConfigChange` feedback loop:**
   Run `rg -n "executeConfigChangeHooks|hasBlockingResult|updateHooksConfigSnapshot|policy_settings" utils/settings/changeDetector.ts utils/settings/applySettingsChange.ts utils/hooks.ts` and verify which config sources a `ConfigChange` hook can block versus audit-only.


---

<!-- chapters/14-configuration-settings-and-enterprise-policy.md — https://reverseengineeringclaudecode.com/chapters/14-configuration-settings-and-enterprise-policy -->

# Chapter 14 — Configuration, Settings Precedence, and Enterprise Policy

> **Layer:** Layer 4 (Safety, Policy, Sandbox & Lifecycle Hooks)
> **Prerequisites:** [Chapter 01](01-atoms-types-stores-and-primitives.md), [Chapter 11](11-the-permission-engine.md), [Chapter 13](13-the-hook-system.md)
> **Primary Source Files:**
> - [`utils/config.ts`](../../utils/config.ts) — Global (`~/.claude.json`) and per-project mutable state, lockfile persistence, backup rotation, auth-loss guard, and `fs.watchFile` freshness polling.
> - [`utils/settings/constants.ts`](../../utils/settings/constants.ts) — Canonical `SETTING_SOURCES` cascade, `--setting-sources` parser, and editable vs. read-only source types.
> - [`utils/settings/settings.ts`](../../utils/settings/settings.ts) — Multi-source deep merge, `managed-settings.d/` drop-in loading, policy first-source-wins resolution, and trusted-source guards.
> - [`utils/settings/types.ts`](../../utils/settings/types.ts), [`utils/settings/validation.ts`](../../utils/settings/validation.ts), [`utils/settings/settingsCache.ts`](../../utils/settings/settingsCache.ts) — Zod v4 `SettingsSchema`, per-rule permission filtering, forward-compat validation, and three-tier caching.
> - [`utils/settings/mdm/rawRead.ts`](../../utils/settings/mdm/rawRead.ts), [`utils/settings/mdm/settings.ts`](../../utils/settings/mdm/settings.ts), [`utils/settings/mdm/constants.ts`](../../utils/settings/mdm/constants.ts) — Early-boot OS MDM subprocess reads (`plutil` / `reg query`) and admin vs. user-writable registry tiers.
> - [`utils/settings/changeDetector.ts`](../../utils/settings/changeDetector.ts), [`utils/settings/applySettingsChange.ts`](../../utils/settings/applySettingsChange.ts), [`utils/settings/internalWrites.ts`](../../utils/settings/internalWrites.ts) — Live chokidar watcher, echo suppression, deletion grace window, centralized cache invalidation, and interactive/headless state sync.
> - [`utils/managedEnv.ts`](../../utils/managedEnv.ts), [`utils/managedEnvConstants.ts`](../../utils/managedEnvConstants.ts) — Two-phase environment variable loading across the workspace trust boundary and host-integrity strip filters.
> - [`services/remoteManagedSettings/index.ts`](../../services/remoteManagedSettings/index.ts), [`syncCache.ts`](../../services/remoteManagedSettings/syncCache.ts), [`syncCacheState.ts`](../../services/remoteManagedSettings/syncCacheState.ts), [`securityCheck.tsx`](../../services/remoteManagedSettings/securityCheck.tsx) — Enterprise remote settings fetch, ETag SHA-256 caching, dangerous-setting approval dialog, and SCC cycle-breaking leaf cache.
> - [`services/policyLimits/index.ts`](../../services/policyLimits/index.ts) — Organization-level feature kill-switches and the HIPAA essential-traffic fail-closed exception.
> - [`migrations/`](../../migrations/) and [`main.tsx`](../../main.tsx) — Version-gated (`CURRENT_MIGRATION_VERSION = 11`) startup migration runner and idempotence patterns.

---

## Why This Layer Exists

By the end of [Chapter 13](13-the-hook-system.md), the agent harness can enforce permissions, sandbox shell commands, and run lifecycle hooks. Every one of those mechanisms asks the same foundational question: **whose rules are currently in force, and can we trust the file they came from?**

In a toy CLI, configuration is a single `readFileSync('config.json')`. In Claude Code, configuration sits directly on an adversarial boundary:

1. **Untrusted repositories ship config.** Cloning a repo and running `claude` puts `.claude/settings.json` in the working directory. If Claude Code blindly applied `env.ANTHROPIC_BASE_URL`, `apiKeyHelper`, `hooks`, or `skipDangerousModePermissionPrompt` from that file before workspace trust, opening a malicious repository would be instant credential exfiltration or remote code execution.
2. **Enterprise IT policy must win—without bricking offline laptops.** Admins deploy policy through four different mechanisms (cloud API, macOS MDM plists, Windows registry keys, or root-owned `/etc`/`/Library` files and drop-in fragments). Policy must override user and project files, stay fresh during long sessions, and never deadlock cold start when a laptop is on an airplane.
3. **Concurrent CLI tabs mutate state simultaneously.** Ten open terminals share one `~/.claude.json` holding OAuth account metadata, trust decisions, and startup caches. A naive read-modify-write loses authentication state and forces users back through login.

To survive all three constraints, Claude Code splits persistence into **two separate stores**—mutable machine state (`utils/config.ts`) and declarative layered policy (`utils/settings/`)—wired together by a live change-propagation pipeline, two remote enterprise policy services, and a version-gated migration runner.

---

## 1. Two Stores, One Trust Boundary: `GlobalConfig` vs. the Settings Cascade

### The Problem

Why not put everything in `~/.claude/settings.json`? Because user-authored preferences and harness-managed bookkeeping have opposite failure modes:

- Bookkeeping state (`numStartups`, `oauthAccount`, per-project `hasTrustDialogAccepted`, GrowthBook/Statsig caches, `migrationVersion`) is written programmatically dozens of times across concurrent processes. Humans rarely edit it, and losing it logs the user out or re-prompts every dialog.
- Declarative settings (`permissions`, `hooks`, `sandbox`, `env`, `model`, enterprise lockouts) are hand-edited by developers, committed to git, passed via `--settings`, or pushed via MDM. They must merge across scopes, tolerate schema evolution across client versions, and hot-reload when modified externally.

Separating them puts high-churn internal state in `~/.claude.json` (`getGlobalClaudeFile()` in [`utils/env.ts:14-26`](../../utils/env.ts)) and layered policy in the `settings.json` cascade.

### The Real Implementation

`GlobalConfig` in [`utils/config.ts`](../../utils/config.ts) is guarded by a boot latch, a file lock, an auth-loss detector, a rotating backup ring, and a background freshness poller.

First, **no module may read `~/.claude.json` during module evaluation.** `configReadingAllowed` starts `false`; calling `getConfig()` before `enableConfigs()` throws `'Config accessed before allowed.'` (`utils/config.ts:1332-1356, 1427-1429`). During `entrypoints/init.ts:65`, `enableConfigs()` flips the latch and immediately parses `~/.claude.json` with `throwOnInvalid = true`. That makes startup **fail-closed** on a corrupted global config: in non-interactive mode, `init()` prints the error to `stderr` and exits with code `1` (`entrypoints/init.ts:220-226`); in interactive mode, it lazy-imports `InvalidConfigDialog` (`entrypoints/init.ts:229-231`) so the user can inspect or reset the file before the app overwrites it.

After boot, `saveGlobalConfig()` and `saveCurrentProjectConfig()` share `saveConfigWithLock()` (`utils/config.ts:1153-1329`):

```ts
// utils/config.ts:1169-1232 (condensed)
release = lockfile.lockSync(file, {
  lockfilePath: `${file}.lock`,
  onCompromised: err => {
    // Default onCompromised throws from a setTimeout callback, which
    // becomes an unhandled exception. Log instead -- the lock being
    // stolen (e.g. after a 10s event-loop stall) is recoverable.
    logForDebugging(`Config lock compromised: ${err}`, { level: 'error' })
  },
})

const currentConfig = getConfig(file, createDefault)
if (file === getGlobalClaudeFile() && wouldLoseAuthState(currentConfig)) {
  logEvent('tengu_config_auth_loss_prevented', {})
  return false
}

const mergedConfig = mergeFn(currentConfig)
if (mergedConfig === currentConfig) {
  return false
}
```

Four production scars live right inside that write path:

1. **The GH #3117 auth-loss guard (`wouldLoseAuthState()`, `utils/config.ts:783-795`).** If another process truncates `~/.claude.json` mid-write, `getConfig()` fails open to `createDefaultGlobalConfig()`. Writing those defaults back would permanently wipe `oauthAccount` and `hasCompletedOnboarding`. Comparing the freshly read disk config against the in-memory `globalConfigCache.config` aborts the write whenever auth or onboarding would vanish—in *both* the locked path (`1217`) and the unlocked catch-block fallback (`846, 1673`).
2. **Rate-limited backup rotation (`utils/config.ts:1245-1309`).** Before writing, `saveConfigWithLock()` copies the existing file into `~/.claude/backups/.claude.json.backup.<timestamp>`, throttled to `MIN_BACKUP_INTERVAL_MS = 60_000` (preventing startup write bursts from flooding disk) and capped at `MAX_BACKUPS = 5`. Corrupted files discovered on read are separately snapshotted to `.claude.json.corrupted.<timestamp>`, deduplicated by exact file content (`utils/config.ts:1521-1561`).
3. **Default stripping and symlink-preserving atomic writes.** `pickBy` strips any key whose JSON serialization equals `defaultConfig[key]` (`utils/config.ts:1235-1239`), keeping `~/.claude.json` minimal. `writeFileSyncAndFlush_DEPRECATED()` (`utils/file.ts:362-395`) resolves symlinks first (so dotfiles managers keep their symlinks intact) and writes to `${targetPath}.tmp.${process.pid}.${Date.now()}` with `mode: 0o600` before renaming into place.
4. **Write-through cache + `fs.watchFile` cross-process sync (`utils/config.ts:992-1086`).** After the first synchronous load, `getGlobalConfig()` is a pure memory hit. Our own writes update `globalConfigCache = { config, mtime: Date.now() }`—intentionally overshooting the file's `mtime` so the background `fs.watchFile(..., { interval: 1000, persistent: false })` callback skips our own writes via `curr.mtimeMs <= globalConfigCache.mtime`. Writes from *other* `claude` processes advance `curr.mtimeMs`, triggering an async background re-read without ever blocking the main thread on `statSync`.

Finally, **workspace trust** lives in `GlobalConfig.projects[path].hasTrustDialogAccepted`. `checkHasTrustDialogAccepted()` (`utils/config.ts:697-743`) latches `true` once accepted (never caching `false`, since trust can be granted mid-session), checks in-memory session trust (used when running directly in `$HOME`, where trust is never persisted), checks the canonical git root, and walks parent directories all the way to `/`: trusting a parent directory implicitly trusts its children.

### Hidden Invariants & Failure Modes

> [!WARNING]
> **Re-entrancy recursion on corrupted config (`utils/config.ts:48-51, 1477-1501`).** When `getConfig()` logs a `ConfigParseError` via `logEvent('tengu_config_parse_error', ...)`, the telemetry sampler checks a GrowthBook feature cached in `GlobalConfig`, which calls `getGlobalConfig()` → `getConfig()` again. Without the module-level `insideGetConfig` boolean guard, a single malformed `~/.claude.json` triggers a stack overflow.

A second invariant protects the cache from self-sabotage: `saveConfigWithLock()` returns a `boolean` (`didWrite`) specifically so `saveGlobalConfig()` only calls `writeThroughGlobalConfigCache()` when a write actually landed (`utils/config.ts:828-833`). If `wouldLoseAuthState()` tripped and returned `false`, clearing or overwriting `globalConfigCache` would destroy the very in-memory auth snapshot the guard relies on to protect the next write. Similarly, updater callbacks signal a no-op by returning the exact `current` reference (`mergedConfig === currentConfig`), avoiding lock contention and unnecessary disk flushes.

---

## 2. The Five-Source Settings Cascade, Merge Semantics, and Fail-Closed vs. Fail-Open

### The Problem

Unlike `~/.claude.json`, declarative settings come from up to **six layers** (plugins plus five `SETTING_SOURCES`), and the highest layer (`policySettings`) itself has **four competing origins** across three operating systems. We need deterministic precedence, predictable array/object merging, zero-thrash caching, and clear rules for what fails closed versus what degrades gracefully.

### The Real Implementation

#### Canonical Precedence Order

[`utils/settings/constants.ts:7-22`](../../utils/settings/constants.ts) defines the five file/policy sources from lowest to highest priority:

```ts
// utils/settings/constants.ts:7-24
export const SETTING_SOURCES = [
  'userSettings',    // ~/.claude/settings.json (or cowork_settings.json)
  'projectSettings', // <originalCwd>/.claude/settings.json
  'localSettings',   // <originalCwd>/.claude/settings.local.json (gitignored)
  'flagSettings',    // --settings <file|json> + SDK inline overrides
  'policySettings',  // remote API > OS MDM > managed-settings.json + .d/ > HKCU
] as const
```

In [`utils/settings/settings.ts:645-796`](../../utils/settings/settings.ts), `loadSettingsFromDisk()` seeds `mergedSettings` with `getPluginSettingsBase()` (allowlisted plugin-contributed keys, lowest priority of all—set in [`utils/settings/settingsCache.ts:66-76`](../../utils/settings/settingsCache.ts)), then iterates `getEnabledSettingSources()` in order and deep-merges each source with `lodash-es/mergeWith` and `settingsMergeCustomizer`.

Three subtle path and source details matter in production:

- **Cowork user file swap (`utils/settings/settings.ts:264-272`).** When `--cowork` or `CLAUDE_CODE_USE_COWORK_PLUGINS` is truthy, `userSettings` switches from `settings.json` to `cowork_settings.json`.
- **The `--settings` 12× prompt-cache scar (`main.tsx:432-458`).** When a caller passes inline JSON to `--settings '{...}'`, `loadSettingsFromFlag()` writes it to a temporary file so the rest of the settings pipeline sees a uniform path. Crucially, it uses a **content-hash filename** (`generateTempFilePath('claude-settings', '.json', { contentHash: trimmedSettings })`) instead of a random UUID. Why? Because the active settings file path is injected into the Bash tool's sandbox `denyWithinAllow` list—which is serialized into the tool definition sent to the Anthropic API (see [Chapter 04](04-prompt-engineering-and-cache-boundaries.md) and [Chapter 12](12-shell-execution-sandboxing-and-workspace-tools.md)). A random UUID per spawned SDK subprocess busted the API prompt cache on every `query()` turn, causing a 12× input token cost penalty.
- **Deduplicating identical resolved paths (`utils/settings/settings.ts:743-748`).** `seenFiles` tracks `resolve(filePath)` so running Claude Code from `~/.claude` doesn't merge the same file twice under `userSettings` and `projectSettings`.

#### Inside `policySettings`: Strict First-Source-Wins & Drop-In Fragments

Unlike the outer five-source cascade (which merges across sources), **`policySettings` uses strict first-source-wins** across its four origins (`utils/settings/settings.ts:322-345, 375-407, 677-739`):

1. **Remote managed settings** (from `~/.claude/remote-settings.json` / Anthropic API cache — highest).
2. **Admin-only OS MDM**:
   - macOS: `/Library/Managed Preferences/<username>/com.anthropic.claudecode.plist`, then device-level `/Library/Managed Preferences/com.anthropic.claudecode.plist` (plus `~/Library/Preferences/...` **only** when `process.env.USER_TYPE === 'ant'`, [`utils/settings/mdm/constants.ts:45-81`](../../utils/settings/mdm/constants.ts)).
   - Windows: `HKLM\SOFTWARE\Policies\ClaudeCode`, value `Settings` (`REG_SZ` or `REG_EXPAND_SZ`). Living under `SOFTWARE\Policies` is a deliberate WOW64 invariant: Windows places `SOFTWARE\Policies` on the shared key list so 32-bit and 64-bit builds read the exact same key without silent `WOW6432Node` redirection (`mdm/constants.ts:17-26`).
3. **File-based managed settings (`loadManagedFileSettings()`, `utils/settings/settings.ts:74-121`)**:
   - Base file: `<managedDir>/managed-settings.json`, where `getManagedFilePath()` (`utils/settings/managedPath.ts:8-25`) resolves to `/Library/Application Support/ClaudeCode` (macOS), `C:\Program Files\ClaudeCode` (Windows), or `/etc/claude-code` (Linux)—with an ant-only override via `CLAUDE_CODE_MANAGED_SETTINGS_PATH`.
   - Drop-in directory: `<managedDir>/managed-settings.d/*.json` (ignoring dotfiles, following symlinks, sorted alphabetically). Following systemd/sudoers conventions, the base file merges first and drop-ins merge on top so independent teams can ship `10-otel.json` and `20-security.json` without editing a monolithic file.
4. **Windows `HKCU\SOFTWARE\Policies\ClaudeCode`** (lowest—user-writable, only used if none of the three admin/remote sources above exist; `consumeRawReadResult()` in `utils/settings/mdm/settings.ts:255-270` explicitly checks `hasManagedSettingsFile()` before falling through to HKCU).

To keep MDM reads off the startup critical path, [`main.tsx:13-16`](../../main.tsx) calls `startMdmRawRead()` at module evaluation—before ~135ms of heavy imports run. On macOS, [`utils/settings/mdm/rawRead.ts:60-77`](../../utils/settings/mdm/rawRead.ts) performs a synchronous `existsSync(path)` check before spawning `/usr/bin/plutil`: non-MDM laptops skip the ~5ms `plutil` spawn completely, while MDM machines still spawn `execFile` before the first `await` so the child process overlaps with JS module loading. `main.tsx:914` then awaits `Promise.all([ensureMdmSettingsLoaded(), ensureKeychainPrefetchCompleted()])` inside Commander's `preAction` hook right before `init()` triggers the first settings read.

#### Asymmetric Merge Semantics: Reads vs. Writes

The merge algorithm intentionally behaves differently when **reading across sources** versus **writing to one source**:

- **Cross-source read (`settingsMergeCustomizer`, `utils/settings/settings.ts:529-547`):** Objects deep-merge; scalar keys take the higher-priority source; **arrays concatenate and deduplicate** (`uniq([...targetArray, ...sourceArray])`). That lets user, project, and policy sources all contribute entries to `permissions.deny` or `deniedMcpServers` without clobbering one another.
- **Single-source write (`updateSettingsForSource()`, `utils/settings/settings.ts:416-524`):** Read-only sources (`policySettings`, `flagSettings`) are silent no-ops (`420-425`). For editable sources, arrays **replace** the previous array (the caller computes the desired final list), and setting a key to explicit `undefined` **deletes** that key from the target object (`482-486`)—calling JS `delete` on your patch object before passing it in leaves the existing disk key untouched. When updating `localSettings`, Claude Code also asynchronously registers `.claude/settings.local.json` in `.gitignore` (`508-514`).
- **SDK inline flag clearing (`cli/print.ts:3709-3718`):** Because JSON serialization strips `undefined`, the SDK `apply_flag_settings` control request uses `null` to mean "clear this key"; `print.ts` deletes `null` keys before calling `setFlagSettingsInline()` so `SettingsSchema().safeParse()` doesn't reject the whole object.

#### Three-Tier Caching and Defensive Cloning

[`utils/settings/settingsCache.ts`](../../utils/settings/settingsCache.ts) maintains three synchronized caches cleared together by `resetSettingsCache()`:

1. `parseFileCache` (`Map<string, ParsedSettings>`): deduplicates disk read + Zod parse when both `getSettingsForSource()` and `loadSettingsFromDisk()` inspect the same path during boot. `parseSettingsFile()` **deep-clones on every return—including the first uncached return** (`utils/settings/settings.ts:182-199`) because callers feed the returned object directly into lodash's mutating `mergeWith`.
2. `perSourceCache` (`Map<SettingSource, SettingsJson | null>`): distinguishes a cache miss (`undefined`) from a cached absent source (`null`). `updateSettingsForSource()` deliberately bypasses this cache via `getSettingsForSourceUncached()` (`436-440`) so a failed write cannot leak mutated nested objects into the cache.
3. `sessionSettingsCache` (`SettingsWithErrors | null`): caches the full merged result of `loadSettingsFromDisk()` (protected against recursive calls by the `isLoadingSettings` flag at `settings.ts:639-649`).

#### Fail-Closed vs. Fail-Open Behavior Across Every Failure Mode

| Surface / Operation | Failure Mode | Policy | Exact Mechanism |
| --- | --- | --- | --- |
| `enableConfigs()` (`~/.claude.json` at startup) | Malformed JSON | **Fail-closed** | Throws `ConfigParseError`; exits `1` in headless mode or shows `InvalidConfigDialog` (`entrypoints/init.ts:216-232`). |
| `--settings` / `--setting-sources` CLI flags | Invalid JSON, missing file, bad source name | **Fail-closed** | Prints red error to `stderr` and calls `process.exit(1)` (`main.tsx:439-495`). |
| `FileEditTool` editing a `settings.json` | Edit breaks `SettingsSchema().strict()` | **Fail-closed** (if previously valid) | `validateInputForSettingsFileEdit()` (`utils/settings/validateEditTool.ts:14-45`) rejects the edit with full JSON Schema; if the *before* file was already invalid, allows the edit so it can be repaired. |
| `updateSettingsForSource()` write | Target file has JSON syntax error | **Fail-closed** | Refuses to overwrite (`settings.ts:455-463`). If valid JSON fails schema validation, merges onto the raw JSON object to avoid losing unknown/broken keys (`464-469`). |
| `parseSettingsFile()` single bad permission rule | Malformed rule in `permissions.{allow,deny,ask}` | **Surgical strip (fail-open)** | `filterInvalidPermissionRules()` (`validation.ts:224-265`) drops only the offending rule and records a warning *before* Zod parses the file, so one typo never voids the entire file. |
| `parseSettingsFile()` unknown future keys | Older client sees newer schema field | **Fail-open (preserve)** | `SettingsSchema()` ends with `.passthrough()` (`types.ts:1072`). `strictPluginOnlyCustomization` also uses `.preprocess()` + `.catch(undefined)` (`types.ts:518-540`) so an unknown surface name degrades to locking known surfaces rather than nulling `managed-settings.json`. |
| `parseSettingsFile()` top-level schema/JSON failure | File fails `SettingsSchema().safeParse()` | **Fail-open (skip source)** | Returns `{ settings: null, errors }` (`settings.ts:221-224`); errors surface in UI/doctor. For `policySettings`, an invalid remote payload surfaces errors and falls through to MDM/file (`settings.ts:684-720`). |
| `rawSettingsContainsKey()` (`settings.ts:984-1015`) | Settings file invalid, but user set `cleanupPeriodDays` | **Intent-preserving** | Scans raw JSON without schema validation so invalid unrelated fields don't trigger default transcript cleanup. |

### Hidden Invariants & Failure Modes

> [!WARNING]
> **The `--setting-sources` `Set`-insertion precedence quirk (`utils/settings/constants.ts:159-167`).**
> Look closely at `getEnabledSettingSources()`:
> ```ts
> // utils/settings/constants.ts:159-167
> export function getEnabledSettingSources(): SettingSource[] {
>   const allowed = getAllowedSettingSources()
>   const result = new Set<SettingSource>(allowed)
>   result.add('policySettings')
>   result.add('flagSettings')
>   return Array.from(result)
> }
> ```
> By default, `STATE.allowedSettingSources` ([`bootstrap/state.ts:313-319`](../../bootstrap/state.ts)) already lists `'flagSettings'` before `'policySettings'`, so both `.add()` calls are no-ops and `policySettings` wins. However, when `--setting-sources user,project` (or `--setting-sources ""`) is passed, `parseSettingSourcesFlag()` returns only the requested subset of `user`/`project`/`local`. Because `getEnabledSettingSources()` inserts `'policySettings'` *before* `'flagSettings'` and `loadSettingsFromDisk()` iterates that array directly (`settings.ts:674`), scalar fields from `--settings` actually merge *after* `policySettings` whenever `--setting-sources` is explicitly passed!
>
> **Why enterprise security lockouts still hold:** Every hard enterprise boundary (`allowManagedPermissionRulesOnly`, `allowManagedHooksOnly`, `allowManagedMcpServersOnly`, `strictPluginOnlyCustomization`) bypasses the merged `SettingsJson` and calls `getSettingsForSource('policySettings')` directly. (By contrast, `isBypassPermissionsModeDisabled()` in [`utils/permissions/permissionSetup.ts:1371-1384`](../../utils/permissions/permissionSetup.ts) reads merged `getSettings_DEPRECATED()` plus the GrowthBook gate `tengu_disable_bypass_permissions_mode`.)

Separately, **security-sensitive opt-in readers exclude `projectSettings` entirely** (`utils/settings/settings.ts:882-982`): `hasSkipDangerousModePermissionPrompt()`, `hasAutoModeOptIn()`, `getUseAutoModeDuringPlan()`, and `getAutoModeConfig()` (the latter three behind build-time `feature('TRANSCRIPT_CLASSIFIER')`, with an ant-only `deny` alias at `settings.ts:965`) query `userSettings`, `localSettings`, `flagSettings`, and `policySettings` individually—never `projectSettings`. Otherwise, a malicious repository could commit `skipDangerousModePermissionPrompt: true` or permissive classifier rules to `.claude/settings.json` and achieve RCE on checkout.

---

## 3. Live Settings Propagation: File Watching, Trust Boundaries, and Headless Parity

### The Problem

Enterprise policies and developer settings do not stay frozen after startup. An admin updates `/etc/claude-code/managed-settings.d/20-security.json`, an MDM profile refreshes on a corporate laptop, a user edits `~/.claude/settings.json` in another terminal, or a host IDE pushes `apply_flag_settings` over the SDK JSON-RPC channel.

Propagating those updates into both the React TUI and headless `--print` / SDK sessions without thrashing or leaking untrusted project settings requires solving five concrete hazards:

1. Watching `--settings` temp files in `$TMPDIR` crashes or hangs chokidar on sibling sockets and FIFOs (macOS `EOPNOTSUPP`, GH #16469).
2. Writing a settings file from inside Claude Code triggers our own watcher.
3. Atomic editor saves and auto-updaters delete and recreate files, masquerading as a settings wipe.
4. Multiple subscribers resetting the settings cache independently cause N full disk reloads per edit.
5. Applying `settings.env` from `.claude/settings.json` before workspace trust gives an untrusted repo control over `ANTHROPIC_BASE_URL`, `HTTPS_PROXY`, or `LD_PRELOAD`.

### The Real Implementation

#### File Watching, Echo Suppression, and Single-Producer Fan-Out

[`utils/settings/changeDetector.ts`](../../utils/settings/changeDetector.ts) is initialized lazily in `startDeferredPrefetches()` ([`main.tsx:422`](../../main.tsx))—*after* the first REPL paint, and skipped entirely in `--bare` mode and remote mode (`changeDetector.ts:85`).

`getWatchTargets()` (`changeDetector.ts:180-250`) collects parent directories that already contain at least one settings file, **explicitly skipping `flagSettings`** (avoiding `$TMPDIR`), and adds `managed-settings.d/` as its own `depth: 0` watch target. Every potential settings filename in a watched directory is whitelisted so files created mid-session (like a brand-new `.claude/settings.local.json`) are detected, while chokidar's `ignored` predicate rejects non-file/non-directory special nodes (sockets/FIFOs/devices), `.git`, and unrelated siblings (`changeDetector.ts:113-136`).

Four stabilization layers sit between raw OS filesystem events and listener callbacks:

```ts
// utils/settings/changeDetector.ts:31-63, 268-302, 437-440 (condensed)
const FILE_STABILITY_THRESHOLD_MS = 1000
const FILE_STABILITY_POLL_INTERVAL_MS = 500
const INTERNAL_WRITE_WINDOW_MS = 5000
const DELETION_GRACE_MS =
  FILE_STABILITY_THRESHOLD_MS + FILE_STABILITY_POLL_INTERVAL_MS + 200 // 1700ms

function handleChange(path: string): void {
  const source = getSourceForPath(path)
  if (!source) return
  const pendingTimer = pendingDeletions.get(path)
  if (pendingTimer) {
    clearTimeout(pendingTimer)
    pendingDeletions.delete(path)
  }
  if (consumeInternalWrite(path, INTERNAL_WRITE_WINDOW_MS)) return

  void executeConfigChangeHooks(
    settingSourceToConfigChangeSource(source),
    path,
  ).then(results => {
    if (hasBlockingResult(results)) return
    fanOut(source)
  })
}

function fanOut(source: SettingSource): void {
  resetSettingsCache()
  settingsChanged.emit(source)
}
```

Each piece solves a real scar:

- **Self-write echo suppression via a zero-import leaf (`utils/settings/internalWrites.ts`).** `updateSettingsForSource()` calls `markInternalWrite(filePath)` immediately before writing (`settings.ts:498`). When chokidar fires within `5000ms`, `consumeInternalWrite()` returns `true` and deletes the timestamp so only the single echo is suppressed. That 37-line module was split out of `changeDetector.ts` purely to break a circular import: `settings.ts → changeDetector.ts → hooks.ts → … → settings.ts`.
- **Deletion grace window (`DELETION_GRACE_MS = 1700ms`, `changeDetector.ts:54-63, 330-360`).** Why `1700ms` instead of `500ms`? Because it **must exceed** chokidar's `awaitWriteFinish` delay (`1000 + 500ms`) so a delete-and-recreate's `add`/`change` event finishes stabilizing and cancels the pending `unlink` timer before the deletion fans out.
- **`ConfigChange` hook gate (`changeDetector.ts:292-301, 344-353`).** External edits and deletions execute `ConfigChange` hooks ([Chapter 13](13-the-hook-system.md)) *before* `fanOut(source)`. A blocking hook (`exit 2` or `decision: 'block'`) prevents the session from absorbing the on-disk change.
- **30-minute MDM polling (`startMdmPoll()`, `changeDetector.ts:381-418`).** Registry keys and macOS plists don't emit reliable file-watch events, so an `.unref()`'d interval refreshes MDM/HKCU every 30 minutes, compares `jsonStringify({ mdm, hkcu })`, updates the MDM cache, and calls `fanOut('policySettings')` only on diff.
- **Centralized cache reset in `fanOut()` (`changeDetector.ts:420-440`).** Previously, `useSettingsChange` and `applySettingsChange` each reset the settings cache defensively; profiling revealed **5 full `loadSettingsFromDisk` calls in 12ms** when remote managed settings resolved at startup. Resetting once in the single producer (`fanOut`) means **one notification = one disk reload**: the first subscriber pays the cache miss, and every subsequent subscriber (`AppState`, `loadPluginHooks`, `sandbox-adapter`, `useSettingsErrors`) hits cache.

#### Interactive vs. Headless State Propagation

Both UI modes funnel into the exact same [`applySettingsChange()`](../../utils/settings/applySettingsChange.ts) routine:

- **Interactive TUI ([`state/AppState.tsx:59-91`](../../state/AppState.tsx)):** `AppStateProvider` subscribes via `useSettingsChange` ([`hooks/useSettingsChange.ts`](../../hooks/useSettingsChange.ts)) and calls `applySettingsChange(source, store.setState)`. It also runs a mount-time `useEffect` (`AppState.tsx:60-68`) to close a startup race: if remote managed settings finished loading *before* React mounted and set `disableBypassPermissionsMode`, the mount check still tears down bypass mode.
- **Headless / SDK ([`cli/print.ts:517-532`](../../cli/print.ts)):** With no React tree, `print.ts` subscribes directly to `settingsChangeDetector.subscribe(source => { applySettingsChange(source, setAppState); ... })` and additionally syncs the denormalized `fastMode` field into `AppState`. When an IDE sends an `apply_flag_settings` control request (`cli/print.ts:3705-3743`), it routes through `settingsChangeDetector.notifyChange('flagSettings')` instead of calling `applySettingsChange()` directly—ensuring `fanOut()` flushes the cache *and* notifies sibling subscribers (`loadPluginHooks`, `sandbox-adapter`).

Inside `applySettingsChange()` (`utils/settings/applySettingsChange.ts:33-92`), every live update:
1. Reads fresh merged settings (`getInitialSettings()`), reloads permission rules (`loadAllPermissionRulesFromDisk()`), and refreshes the frozen hook snapshot (`updateHooksConfigSnapshot()`, [Chapter 13](13-the-hook-system.md)).
2. Re-syncs `toolPermissionContext`, re-strips overly broad Bash allow rules in ant builds (`process.env.USER_TYPE === 'ant'`, skipping `local-agent`), enforces `isBypassPermissionsModeDisabled()`, and reconciles plan/auto mode via `transitionPlanAutoMode()`.
3. Updates `effortValue` **only when `effortLevel` itself changed AND the new disk value is defined** (`applySettingsChange.ts:70-89`). Without both guards, unrelated settings churn (like dismissing a tip) would clobber a `--effort` CLI flag held in `AppState`, and a stale `prev.settings.effortLevel` after a suppressed internal write would wipe a session-scoped `/effort` value.
4. Triggers [`state/onChangeAppState.ts:156-170`](../../state/onChangeAppState.ts) when `newState.settings !== oldState.settings`: clears `apiKeyHelper`, AWS, and GCP credential caches and, if `settings.env` changed, calls `applyConfigEnvironmentVariables()`.

#### Two-Phase Environment Loading Across the Workspace Trust Boundary

Environment variables from settings are split into two strict phases in [`utils/managedEnv.ts`](../../utils/managedEnv.ts):

```ts
// utils/managedEnv.ts:124-178 (abbreviated)
export function applySafeConfigEnvironmentVariables(): void {
  // 1. Capture Claude Desktop spawn env once so settings.env can't clobber stdio/OTEL
  // 2. Apply ~/.claude.json env (filtered)
  // 3. Apply ALL env vars from trusted non-policy sources (userSettings, flagSettings),
  //    gated by isSettingSourceEnabled() so SDK settingSources: [] stays isolated
  // 4. Compute isRemoteManagedSettingsEligible() NOW — sees Bedrock/Vertex/base URL
  //    from userSettings/flagSettings before policySettings reads the remote cache
  isRemoteManagedSettingsEligible()
  // 5. Apply ALL env vars from policySettings (highest priority, filtered)
  // 6. Apply ONLY SAFE_ENV_VARS allowlisted keys from merged settings (project/local)
}
```

Before workspace trust is accepted, `entrypoints/init.ts:74` runs **only** `applySafeConfigEnvironmentVariables()`. Project-scoped sources (`projectSettings`, `localSettings`) can only set allowlisted keys in `SAFE_ENV_VARS` ([`utils/managedEnvConstants.ts:108-191`](../../utils/managedEnvConstants.ts))—blocking attacker-controlled redirects (`ANTHROPIC_BASE_URL`, `HTTP_PROXY`, `OTEL_EXPORTER_OTLP_ENDPOINT`), TLS bypasses (`NODE_TLS_REJECT_UNAUTHORIZED`, `NODE_EXTRA_CA_CERTS`), and credential hijacks. Only *after* trust is granted (or in non-interactive `-p` mode, where trust is documented as implicit) does `applyConfigEnvironmentVariables()` (`managedEnv.ts:187-199`) apply the full merged `settings.env` and rebuild CA cert, mTLS, and HTTP proxy agents.

Furthermore, *every* settings-sourced env object passes through three host-protection strip filters (`filterSettingsEnv`, `utils/managedEnv.ts:23-91`):
- `withoutSSHTunnelVars`: when `ANTHROPIC_UNIX_SOCKET` is set (`claude ssh`), strips tunnel/auth vars so the remote host's `~/.claude/settings.json` cannot break the forwarded auth socket.
- `withoutHostManagedProviderVars`: when `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST` is truthy, strips all provider/endpoint/model routing vars (`PROVIDER_MANAGED_ENV_VARS` + `VERTEX_REGION_CLAUDE_*`) so a user's CLI Bedrock config cannot redirect a host-managed session.
- `withoutCcdSpawnEnvKeys`: in Claude Desktop (`CLAUDE_CODE_ENTRYPOINT === 'claude-desktop'`), snapshots `Object.keys(process.env)` before the first settings apply and refuses to let settings overwrite any desktop-injected key (e.g., `OTEL_LOGS_EXPORTER=console` would corrupt the stdio JSON-RPC stream).

### Hidden Invariants & Failure Modes

> [!NOTE]
> **Additive-only env hot-reload (`state/onChangeAppState.ts:162-166`).** `applyConfigEnvironmentVariables()` uses `Object.assign(process.env, ...)`. Adding or modifying a key in `settings.env` takes effect immediately mid-session, but *removing* a key from `settings.json` does **not** delete it from `process.env` until the next process restart.

Notice also why `onChangeAppState` calling `applyConfigEnvironmentVariables()` unconditionally on `settings.env` change does **not** leak untrusted `projectSettings.env`: `settingsChangeDetector.initialize()` is deferred to `startDeferredPrefetches()` *after* the REPL mounts (`main.tsx:422`), and the interactive REPL only mounts after the workspace trust dialog has been accepted.

---

## 4. Enterprise Policy Services: Remote Managed Settings & Policy Limits

### The Problem

File-based `managed-settings.json` and OS MDM profiles require IT endpoint tooling. Cloud-managed organizations also want to push settings and feature kill-switches straight from Anthropic's control plane—without adding 200ms to every `claude -p` invocation, without breaking offline work, without pulling `auth.ts` into the `settings.ts` strongly connected component (SCC), and without turning a compromised org console into silent shell execution on developer laptops.

### The Real Implementation

Claude Code runs two parallel enterprise cloud services side by side: [`services/remoteManagedSettings/`](../../services/remoteManagedSettings/index.ts) (full `SettingsJson` policy payload) and [`services/policyLimits/`](../../services/policyLimits/index.ts) (org feature kill-switches).

#### Remote Managed Settings: Cache-First Boot, ETag Sync, and SCC Cycle Breaking

At startup, `entrypoints/init.ts:123-125` calls `initializeRemoteManagedSettingsLoadingPromise()`, creating a promise that other subsystems (like plugin hook loaders or telemetry initialization) can `await` via `waitForRemoteManagedSettingsToLoad()`. To avoid deadlocks in Agent SDK harnesses or tests that never enter `main.tsx`, that promise self-resolves after `LOADING_PROMISE_TIMEOUT_MS = 30_000` (`services/remoteManagedSettings/index.ts:66-99`).

In `main.tsx:957`, `void loadRemoteManagedSettings()` launches non-blockingly:

```ts
// services/remoteManagedSettings/index.ts:524-555 (condensed)
// Cache-first: unblock waiters immediately if ~/.claude/remote-settings.json exists
// (saves ~77ms fetch-wait on print-mode startup). Fetch still runs below.
if (getRemoteManagedSettingsSyncFromCache() && loadingCompleteResolve) {
  loadingCompleteResolve()
  loadingCompleteResolve = null
}

try {
  const settings = await fetchAndLoadRemoteManagedSettings()
  if (isRemoteManagedSettingsEligible()) {
    startBackgroundPolling() // 1 hour interval, .unref()
  }
  if (settings !== null) {
    settingsChangeDetector.notifyChange('policySettings')
  }
} finally {
  if (loadingCompleteResolve) {
    loadingCompleteResolve()
    loadingCompleteResolve = null
  }
}
```

Four design details make this service resilient in production:

1. **Eligibility pre-check without circular `getSettings()` (`syncCache.ts:49-112`).** Only first-party Anthropic API users (`getAPIProvider() === 'firstParty'` and `isFirstPartyAnthropicBaseUrl()`, excluding `CLAUDE_CODE_ENTRYPOINT === 'local-agent'` Cowork VMs) hit `/api/claude_code/settings`. Notably, `isRemoteManagedSettingsEligible()` checks **OAuth tokens before API keys** specifically to avoid spawning macOS's `security find-generic-password` (~20–50ms) for OAuth-only users (`syncCache.ts:70-74`). Enterprise/Team OAuth users with `CLAUDE_AI_INFERENCE_SCOPE`, externally-injected OAuth tokens carrying `subscriptionType === null` (letting the server decide via 204/404), and Console API-key users (called with `skipRetrievingKeyFromApiKeyHelper: true` to avoid re-entering `getSettings()`) are eligible.
2. **Breaking the `settings.ts → auth.ts → settings.ts` SCC (`syncCacheState.ts:1-96`).** `settings.ts` must read the remote cache synchronously, yet eligibility depends on `auth.ts`. Splitting `syncCacheState.ts` into a zero-auth leaf module with a tri-state `eligible: boolean | undefined` breaks the cycle. `applySafeConfigEnvironmentVariables()` computes eligibility once and mirrors it via `setEligibility()`. Better yet, the first time `getRemoteManagedSettingsSyncFromCache()` hydrates `~/.claude/remote-settings.json`, it calls `resetSettingsCache()` once (`syncCacheState.ts:74-93`)—fixing **gh-23085**, where an early pre-`init()` probe poisoned the merged settings cache while `eligible` was still `undefined`!
3. **Deterministic ETag caching and revocation cleanup (`index.ts:112-137, 273-306, 456-491`).** `computeChecksumFromSettings()` recursively sorts object keys and serializes with compact separators to match the backend's Python `json.dumps(settings, sort_keys=True, separators=(",", ":"))`, hashing to `sha256:<hex>` for `If-None-Match`.
   - `304 Not Modified`: reuses disk cache.
   - `204` / `404`: sets `{}` and **`unlink()`s `~/.claude/remote-settings.json`** so revoked org policies don't stick around forever.
   - `401` / `403` / missing auth: sets `skipRetry: true`.
   - Timeouts / network / 5xx: retries up to `DEFAULT_MAX_RETRIES = 5` with exponential backoff (`getRetryDelay()`), then **fails open** to stale disk cache (if present) or `null`.
   - Persistence writes with `open(path, 'w', 0o600)` + `handle.datasync()` (`index.ts:370-377`).
4. **Blocking security dialog for dangerous remote settings (`securityCheck.tsx` + `components/ManagedSettingsSecurityDialog/utils.ts`).** Before applying newly fetched remote settings, `extractDangerousSettings()` checks for any `DANGEROUS_SHELL_SETTINGS` (`apiKeyHelper`, `awsAuthRefresh`, `awsCredentialExport`, `gcpAuthRefresh`, `otelHeadersHelper`, `statusLine`), any env var *not* in `SAFE_ENV_VARS`, or any `hooks`. If dangerous fields were added or changed relative to the cached file in an interactive session, Claude Code renders a blocking `ManagedSettingsSecurityDialog`. Approving applies and caches them; rejecting calls `gracefulShutdownSync(1)` (**fail-closed** on explicit refusal). Non-interactive sessions skip the dialog (`securityCheck.tsx:34-36`).

#### Enterprise Lockdown Primitives in `SettingsSchema`

When enterprise admins want strict guardrails—whether delivered remotely, via MDM, or via `managed-settings.json`—four managed-only boolean/enum switches lock down lower layers:

- `allowManagedPermissionRulesOnly` (`utils/settings/types.ts:501-507`, read in `utils/permissions/permissionsLoader.ts:33`): ignores all user, project, local, and CLI permission rules.
- `allowManagedHooksOnly` (`types.ts:472-478`, read in `utils/hooks/hooksConfigSnapshot.ts:27`): runs only managed hooks; hides/skips user, project, local, and session hooks.
- `allowManagedMcpServersOnly` (`types.ts:509-516`, read in `services/mcp/config.ts:1487`): reads `allowedMcpServers` exclusively from `policySettings`.
- `strictPluginOnlyCustomization` (`types.ts:518-545`, enforced by [`utils/settings/pluginOnlyPolicy.ts`](../../utils/settings/pluginOnlyPolicy.ts)): locks `CUSTOMIZATION_SURFACES` (`['skills', 'agents', 'hooks', 'mcp']`)—either all four (`true`) or a named subset—so `~/.claude/*` and `.claude/*` definitions are skipped and only `ADMIN_TRUSTED_SOURCES` (`'plugin'`, `'policySettings'`, `'built-in'`, `'builtin'`, `'bundled'`) load, with plugins gated separately by `strictKnownMarketplaces`.

#### Policy Limits: Org Feature Kill-Switches and the HIPAA Exception

[`services/policyLimits/index.ts`](../../services/policyLimits/index.ts) mirrors remote managed settings—hitting `/api/claude_code/policy_limits`, caching to `~/.claude/policy-limits.json`, sending SHA-256 `If-None-Match` ETags, retrying 5×, unlinking on 404, and polling hourly with an `.unref()`'d timer—but carries a compact schema (`services/policyLimits/types.ts:8-12`):

```ts
{ restrictions: Record<string, { allowed: boolean }> }
```

Only *blocked* policies appear in the map; callers query synchronously via `isPolicyAllowed(policy)`. Across this snapshot, three org kill-switches are enforced:
- `'allow_remote_sessions'` (`main.tsx:3405`, `cli/print.ts:4991`, `utils/teleport.tsx:431`, `utils/background/remote/remoteSession.ts:53`, `RemoteTriggerTool.ts:60`, `commands/remote-env/`, `commands/remote-setup/`, `skills/bundled/scheduleRemoteAgents.ts`).
- `'allow_remote_control'` (`bridge/initReplBridge.ts:155`, `commands/bridge/bridge.tsx:474`, `entrypoints/cli.tsx:157`).
- `'allow_product_feedback'` (`components/FeedbackSurvey/useFeedbackSurvey.tsx`, `useMemorySurvey.tsx`, `commands/feedback/index.ts`).

The critical security invariant sits at [`services/policyLimits/index.ts:497-526`](../../services/policyLimits/index.ts):

```ts
// services/policyLimits/index.ts:502-526
const ESSENTIAL_TRAFFIC_DENY_ON_MISS = new Set(['allow_product_feedback'])

export function isPolicyAllowed(policy: string): boolean {
  const restrictions = getRestrictionsFromCache()
  if (!restrictions) {
    if (
      isEssentialTrafficOnly() &&
      ESSENTIAL_TRAFFIC_DENY_ON_MISS.has(policy)
    ) {
      return false
    }
    return true // fail open
  }
  const restriction = restrictions[policy]
  if (!restriction) {
    return true // unknown policy = allowed
  }
  return restriction.allowed
}
```

Normally `isPolicyAllowed()` fails open so transient API blips don't break developer workflows. For HIPAA / essential-traffic-only environments (`isEssentialTrafficOnly()`), however, `allow_product_feedback` **flips to fail-closed on cache miss**: a network timeout must never silently re-enable feedback prompts and leak protected data.

### Hidden Invariants & Failure Modes

> [!NOTE]
> **Subtle divergences between `remoteManagedSettings` and `policyLimits`:**
> 1. `isPolicyLimitsEligible()` (`services/policyLimits/index.ts:167-211`) checks API keys *before* OAuth and does **not** treat `subscriptionType === null` tokens as eligible or exempt `local-agent`.
> 2. `policyLimits` background polling updates `sessionCache` silently without emitting through `settingsChangeDetector`; feature gates read `isPolicyAllowed()` dynamically on demand.
> 3. Background **user-settings sync** (`services/settingsSync/index.ts`) is separate from enterprise remote managed settings and is compile-time gated behind `feature('UPLOAD_USER_SETTINGS')` (`main.tsx:963`) and `feature('DOWNLOAD_USER_SETTINGS')` (`cli/print.ts:511`).

---

## 5. Idempotent Startup Migrations (`migrations/` & `main.tsx`)

### The Problem

Over dozens of releases, fields migrate across stores (`autoUpdates` and `bypassPermissionsModeAccepted` moved from `~/.claude.json` into `~/.claude/settings.json`; MCP server approvals moved from `GlobalConfig.projects` into `.claude/settings.local.json`), deprecated model pins (`claude-sonnet-4-5-20250929`, legacy Opus IDs) must be rewritten to current aliases, and one-shot opt-in resets must fire once per machine.

Running 11 migrations unconditionally on every CLI boot used to acquire the `~/.claude.json` lock and re-read disk up to 11 times on startup (`utils/config.ts:574-577`). Yet skipping them unsafely—or running them out of order—would corrupt user preferences or re-trigger dismissed prompts.

### The Real Implementation

The true migration registry is `runMigrations()` in [`main.tsx:325-352`](../../main.tsx), invoked in Commander's `preAction` hook right after `init()` (`main.tsx:950`):

```ts
// main.tsx:325-352
const CURRENT_MIGRATION_VERSION = 11;
function runMigrations(): void {
  if (getGlobalConfig().migrationVersion !== CURRENT_MIGRATION_VERSION) {
    migrateAutoUpdatesToSettings();
    migrateBypassPermissionsAcceptedToSettings();
    migrateEnableAllProjectMcpServersToSettings();
    resetProToOpusDefault();
    migrateSonnet1mToSonnet45();
    migrateLegacyOpusToCurrent();
    migrateSonnet45ToSonnet46();
    migrateOpusToOpus1m();
    migrateReplBridgeEnabledToRemoteControlAtStartup();
    if (feature('TRANSCRIPT_CLASSIFIER')) {
      resetAutoModeOptInForDefaultOffer();
    }
    if ("external" === 'ant') {
      migrateFennecToOpus();
    }
    saveGlobalConfig(prev => prev.migrationVersion === CURRENT_MIGRATION_VERSION ? prev : {
      ...prev,
      migrationVersion: CURRENT_MIGRATION_VERSION
    });
  }
  // Async migration - fire and forget since it's non-blocking
  migrateChangelogFromConfig().catch(() => {});
}
```

*(Note: In this external-build snapshot, `process.env.USER_TYPE === 'ant'` at `main.tsx:340` is constant-folded to `"external" === 'ant'`, dead-coding `migrateFennecToOpus()`, while `resetAutoModeOptInForDefaultOffer()` is gated behind `feature('TRANSCRIPT_CLASSIFIER')`.)*

Because every migration in the block can re-run whenever `CURRENT_MIGRATION_VERSION` bumps (when migration #12 ships), **every single migration must be independently idempotent**. Across the 11 files in [`migrations/`](../../migrations/), four concrete idioms enforce idempotence and crash-safety:

1. **Write-target-first, strip-source-second (`migrateAutoUpdatesToSettings.ts`, `migrateBypassPermissionsAcceptedToSettings.ts`, `migrateEnableAllProjectMcpServersToSettings.ts`).**
   Each migration first writes into `userSettings` or `localSettings` via `updateSettingsForSource()`, and *only then* removes the legacy key from `GlobalConfig` / `ProjectConfig` via object destructuring. If the process crashes halfway, the next boot sees the legacy key still present and safely retries—merging arrays with `new Set([...existing, ...legacy])` (`migrateEnableAllProjectMcpServersToSettings.ts:64-69`) and respecting `existingSettings.enableAllProjectMcpServers === undefined` so existing user edits are never overwritten. `migrateAutoUpdatesToSettings.ts:18-23` also checks `autoUpdatesProtectedForNative !== true` so an automatic native-installer safeguard isn't misread as a user disabling updates.
2. **Source-scoped value rewrite (`migrateSonnet45ToSonnet46.ts:29-60`).**
   Reads `getSettingsForSource('userSettings')?.model`—deliberately *not* merged settings—so repo-level `projectSettings` or `localSettings` model pins are left intact. It rewrites only exact Sonnet 4.5 strings to `'sonnet'` / `'sonnet[1m]'` (so re-running is a no-op) and skips setting the toast timestamp when `config.numStartups <= 1` so brand-new installs don't see an upgrade banner.
3. **Cross-store one-shot guard (`resetAutoModeOptInForDefaultOffer.ts:25-50`).**
   Clears `skipAutoPermissionPrompt` in `userSettings` (by passing `{ skipAutoPermissionPrompt: undefined }`), but records its completion latch (`hasResetAutoModeOptInForDefaultOffer: true`) in `~/.claude.json` (`GlobalConfig`) rather than `settings.json`—ensuring a settings file reset never re-arms the migration. It also bails out unless `getAutoModeEnabledState() === 'enabled'` so `'opt-in'` users aren't locked out of reaching the dialog.
4. **Opportunistic read/write-time normalization (`utils/config.ts:912-989`).**
   Two legacy `GlobalConfig` cleanups live directly in `config.ts`: `migrateConfigFields()` translates removed `autoUpdaterStatus` into `installMethod` + `autoUpdates` on every load, and `removeProjectHistory()` strips deprecated per-project `history` blobs (moved to `history.jsonl`) on every `saveGlobalConfig()`.

Every migration wraps I/O in `try/catch` and logs errors rather than throwing, so a read-only `.claude/settings.local.json` cannot crash startup.

### Hidden Invariants & Failure Modes

> [!WARNING]
> **Global version latch vs. per-project migrations.**
> `CURRENT_MIGRATION_VERSION` is persisted globally in `~/.claude.json`, yet `migrateEnableAllProjectMcpServersToSettings()` operates only on `getCurrentProjectConfig()` (the current working repo). Once a user runs Claude Code in repo A and stamps `migrationVersion = 11` in `~/.claude.json`, opening a legacy repo B skips `runMigrations()` until `CURRENT_MIGRATION_VERSION` is bumped again. That is why `ProjectConfig` in `utils/config.ts:117-120` still retains the legacy `enabledMcpjsonServers` / `enableAllProjectMcpServers` fields for backward compatibility.

---

## Putting the Layer Together

### Startup & Live-Reload Dataflow

```mermaid
flowchart TD
  M0["main.tsx top-level: startMdmRawRead() + startKeychainPrefetch()"] --> E0["eagerLoadSettings(): --settings (content-hash tmp) & --setting-sources"]
  E0 --> P0["preAction: await ensureMdmSettingsLoaded() & keychain"]
  P0 --> I0["init(): enableConfigs() (fail-closed ~/.claude.json)"]
  I0 --> ENV1["applySafeConfigEnvironmentVariables(): user/flag env -> eligibility -> policy env -> SAFE_ENV_VARS"]
  ENV1 --> MIG["runMigrations(): CURRENT_MIGRATION_VERSION = 11"]
  MIG --> REM["Async fail-open: loadRemoteManagedSettings() & loadPolicyLimits()"]
  REM --> CACHE["settingsCache (parseFile / perSource / session)"]

  subgraph WATCH["Live Propagation (post-first-render)"]
    CHOK["chokidar (depth:0, 1700ms unlink grace, internalWrites echo filter)"] --> HOOK["ConfigChange hooks (blocking = abort)"]
    MDMP["30m MDM poll (.unref)"] --> FAN
    REMP["1h Remote poll / SDK apply_flag_settings"] --> FAN
    HOOK --> FAN["changeDetector.fanOut(): single resetSettingsCache() + emit"]
  end

  FAN --> INT["Interactive: AppStateProvider -> useSettingsChange -> applySettingsChange()"]
  FAN --> HDL["Headless: cli/print.ts subscribe -> applySettingsChange()"]
  INT --> ONC["onChangeAppState: clear auth caches + applyConfigEnvironmentVariables()"]
  HDL --> ONC
```

### Settings Precedence & Trust-Boundary Map

```text
Lowest Priority                                                Highest Priority
+---------+   +------+   +---------+   +-------+   +------+   +---------------+
| Plugin  |-->| User |-->| Project |-->| Local |-->| Flag |-->|    Policy     |
|  Base   |   |      |   | (repo!) |   |(gitig)|   |(CLI/ |   | (1st wins!)   |
+---------+   +------+   +---------+   +-------+   | SDK) |   +-------+-------+
                               |                   +------+           |
         Excluded from:        |                                      v
         - pre-trust unsafe env|                      1. Remote API / cache
         - bypass/auto opt-ins |                      2. Admin MDM (plist/HKLM)
         - autoMode rules      |                      3. managed-settings.json
                                                         + managed-settings.d/*
  Cross-source merge: objects deep-merge,             4. Windows HKCU (lowest)
  scalars last-wins, arrays concat+uniq.
```

---

## How This Snaps Into the Next Layer

With configuration precedence, trust boundaries, live propagation, and enterprise lockouts in place, **Chapter 15 — Model Context Protocol (MCP): Clients, Transports, Auth, and Tool Search** ([`15-model-context-protocol-mcp.md`](15-model-context-protocol-mcp.md)) plugs straight into four exact contracts built here, centered in [`services/mcp/config.ts`](../../services/mcp/config.ts):

1. **Enterprise MCP file location:** `getEnterpriseMcpFilePath()` (`services/mcp/config.ts:62-64`) joins `getManagedFilePath()` with `'managed-mcp.json'`, placing org-mandated MCP servers in the exact same admin-owned OS directory as `managed-settings.json`.
2. **Asymmetric allowlist vs. denylist enforcement:** `shouldAllowManagedMcpServersOnly()` (`services/mcp/config.ts:1485-1489`) reads `getSettingsForSource('policySettings')?.allowManagedMcpServersOnly === true`. When active, `getMcpAllowlistSettings()` (`services/mcp/config.ts:341-346`) restricts `allowedMcpServers` exclusively to `policySettings`, while `getMcpDenylistSettings()` (`services/mcp/config.ts:353-355`) still merges `deniedMcpServers` from all sources via `getInitialSettings()`—guaranteeing users can always deny additional servers even under enterprise lockdown.
3. **Plugin-only customization lockdown:** When `strictPluginOnlyCustomization` includes `'mcp'`, `isRestrictedToPluginOnly('mcp')` ([`utils/settings/pluginOnlyPolicy.ts:19-27`](../../utils/settings/pluginOnlyPolicy.ts)) gates out user and `.mcp.json` server definitions while preserving managed and plugin-provided servers.
4. **Cycle-free validation error aggregation:** Because `services/mcp/config.ts` imports `utils/settings/settings.ts`, `settings.ts` cannot import MCP config validation without forming a cycle. [`utils/settings/allErrors.ts`](../../utils/settings/allErrors.ts) sits above both as a leaf module, exposing `getSettingsWithAllErrors()` to merge `SettingsSchema` errors with `getMcpConfigsByScope(scope).errors` for `/doctor` and startup diagnostics.

---

## Reading Exercises & Code Checkpoints

1. **Trace the `--setting-sources` ordering bug yourself.**
   Inspect `getEnabledSettingSources()` in [`utils/settings/constants.ts:159-167`](../../utils/settings/constants.ts) and the loop in [`utils/settings/settings.ts:674-784`](../../utils/settings/settings.ts). Trace what array `getEnabledSettingSources()` returns for `--setting-sources local,user` vs. default startup, and verify with `rg` which enterprise policy flags protect themselves by calling `getSettingsForSource('policySettings')` directly:
   ```bash
   rg -n "getSettingsForSource\('policySettings'\)" utils/ services/
   ```
2. **Verify every caller of `isPolicyAllowed()`.**
   Run the following search to list every feature controlled by `services/policyLimits/` and check whether any other policy key besides `allow_product_feedback` is listed in `ESSENTIAL_TRAFFIC_DENY_ON_MISS`:
   ```bash
   rg -n "isPolicyAllowed\(" --glob '!book/**'
   ```
3. **Inspect the `GlobalConfig` auth-loss guard and corruption backup paths.**
   Read `wouldLoseAuthState()` and both callers inside `saveGlobalConfig()` and `saveCurrentProjectConfig()` in [`utils/config.ts:783-866, 1216-1224, 1672-1680`](../../utils/config.ts). Why does `saveGlobalConfig` guard *both* the locked path and the catch-block fallback, and what happens to `globalConfigCache` if `wouldLoseAuthState` returns `true`?
4. **Audit all subscribers to `settingsChangeDetector.subscribe`.**
   Locate every module that reacts to live settings reloads across interactive and headless runtimes, and verify that none of them call `resetSettingsCache()` themselves (preserving the single-producer invariant in `changeDetector.fanOut`):
   ```bash
   rg -n "settingsChangeDetector\.(subscribe|notifyChange)" --glob '!book/**'
   ```


---

<!-- chapters/15-model-context-protocol-mcp.md — https://reverseengineeringclaudecode.com/chapters/15-model-context-protocol-mcp -->

# Chapter 15 — Model Context Protocol (MCP): Clients, Transports, Auth, and Tool Search

> **Layer:** Layer 5 (Dynamic Capabilities: MCP, Skills, Plugins & LSP)
> **Prerequisites:** [Chapter 02](02-the-tool-contract.md), [Chapter 04](04-prompt-engineering-and-cache-boundaries.md), [Chapter 06](06-executing-tools.md), [Chapter 11](11-the-permission-engine.md), [Chapter 14](14-configuration-settings-and-enterprise-policy.md)
> **Primary Source Files:**
> - [services/mcp/config.ts](../../services/mcp/config.ts) — Multi-scope server resolution, enterprise allow/deny policy, content-signature deduplication, and atomic `.mcp.json` writes
> - [services/mcp/client.ts](../../services/mcp/client.ts) — Transport construction, memoized connections, timeout/401/session-expiry recovery, tool/prompt/resource adaptation, output budgeting, and URL elicitation retries
> - [services/mcp/auth.ts](../../services/mcp/auth.ts) — `ClaudeAuthProvider`, OAuth 2.1 + PKCE + CIMD, cross-process lockfile refresh, 403 step-up interception, and XAA orchestration ([services/mcp/xaa.ts](../../services/mcp/xaa.ts))
> - [services/mcp/useManageMCPConnections.ts](../../services/mcp/useManageMCPConnections.ts) — React lifecycle hook, two-phase startup, 16 ms state coalescing, backoff reconnects, `list_changed`, and channel push handlers
> - [services/mcp/elicitationHandler.ts](../../services/mcp/elicitationHandler.ts) — Server-initiated form/URL elicitations, hook interception, and completion notifications
> - [services/mcp/InProcessTransport.ts](../../services/mcp/InProcessTransport.ts) & [services/mcp/SdkControlTransport.ts](../../services/mcp/SdkControlTransport.ts) — Microtask-linked in-process transport and CLI↔SDK control-channel bridge
> - [services/mcp/mcpStringUtils.ts](../../services/mcp/mcpStringUtils.ts) & [services/mcp/normalization.ts](../../services/mcp/normalization.ts) — `mcp__server__tool` naming, character normalization, and permission-key extraction
> - [tools/MCPTool/MCPTool.ts](../../tools/MCPTool/MCPTool.ts) & [tools.ts](../../tools.ts) — Base MCP `Tool` template and cache-safe `assembleToolPool()` partitioning
> - [tools/ToolSearchTool/ToolSearchTool.ts](../../tools/ToolSearchTool/ToolSearchTool.ts), [tools/ToolSearchTool/prompt.ts](../../tools/ToolSearchTool/prompt.ts), & [utils/toolSearch.ts](../../utils/toolSearch.ts) — `shouldDefer` / `defer_loading: true`, `tool_reference` discovery, keyword ranking, and `deferred_tools_delta` cache stability

---

## Why This Layer Exists

Everything built in Layers 0 through 4 operates over a closed world of compiled-in tools (`Bash`, `Read`, `Edit`, `Grep`, `Agent`). Those tools share a single process, deterministic schemas, static permission rules, and a byte-stable prefix that lets Anthropic's backend cache the system prompt and tool array globally across sessions.

External capabilities shatter every one of those assumptions simultaneously:

1. **Heterogeneous transports and lifecycles.** An external server might be a local Docker container over `stdio`, a remote SaaS endpoint behind OAuth 2.1 Streamable HTTP, a VS Code extension over WebSocket, a browser controller running in-process to avoid a 325 MB fork, or a JavaScript callback inside a parent SDK host process. Connections stall, drop mid-tool-call, expire sessions, and rotate tokens across competing CLI processes.
2. **Untrusted schemas and outputs.** Third-party servers emit arbitrary Unicode tool names, 60 KB OpenAPI-generated descriptions, raw base64 audio/binary blobs, and server-initiated UI prompts (elicitations) that must be routed through hooks and user consent dialogs without hanging the loop.
3. **Context bloat and cache destruction.** Attach twenty corporate MCP servers (Slack, GitHub, Linear, Jira, Datadog, `claude.ai` connectors) and you easily inherit 200+ tools—tens of thousands of tokens of JSON Schema on turn 1. Worse, if servers finish handshaking asynchronously after turn 1—or sort alphabetically between built-in tools—every late connection invalidates the entire prompt cache.

Layer 5 solves all three problems without leaking transport mechanics into `query.ts`. To the turn engine, an MCP tool is just another `Tool<Input, Output, P>`—normalized, policy-filtered, partitioned behind built-ins, and lazily materialized via `ToolSearch`.

---

## 1. Configuration Resolution, Policy Gates, and Deduplication

### The Problem

MCP server definitions arrive from seven distinct scopes (`ConfigScopeSchema` in [services/mcp/types.ts:10-20](../../services/mcp/types.ts)): `local`, `user`, `project`, `dynamic` (CLI `--mcp-config` and plugins), `enterprise`, `claudeai`, and `managed`. Merging them by object key alone fails in three real-world ways:

- **Silent duplication across namespaces.** Plugin servers are keyed `plugin:<plugin>:<server>` ([utils/plugins/mcpPluginIntegration.ts:350](../../utils/plugins/mcpPluginIntegration.ts)) and `claude.ai` org connectors are keyed `claude.ai <DisplayName>` ([services/mcp/claudeai.ts:100](../../services/mcp/claudeai.ts)). Neither collides by key with a user's manual `slack` entry in `.mcp.json`, so both connect to `mcp.slack.com`—doubling processes and burning ~600 chars/turn of duplicate tool listings.
- **Rewritten proxy URLs.** In remote CCR sessions, `claude.ai` connectors arrive with URLs rewritten to `/v2/session_ingress/shttp/mcp/...` or `/v2/ccr-sessions/...` carrying the original vendor URL in `?mcp_url=...`. Naive URL comparison misses the duplicate.
- **Pre-trust code execution.** Both `.mcp.json` servers and dynamic `headersHelper` shell commands can come from an untrusted repository cloned off the internet.

### The Real Implementation

[services/mcp/config.ts](../../services/mcp/config.ts) resolves configurations in a strict pipeline inside `getClaudeCodeMcpConfigs()` (`config.ts:1071-1251`) and `getAllMcpConfigs()` (`config.ts:1258-1290`):

1. **Exclusive enterprise override.** If `managed-mcp.json` exists (`doesEnterpriseMcpConfigExist()`, `config.ts:1470-1477`), it takes *exclusive* control: user, project, local, plugin, and `claude.ai` servers are ignored completely. Even dynamic `--mcp-config` entries are rejected unless every server satisfies `areMcpConfigsAllowedWithEnterpriseMcpConfig()` (`config.ts:1494-1504`), which currently whitelists only `type === 'sdk' && name === 'claude-vscode'` so enterprise policies do not break the VS Code extension.
2. **Scope discovery and precedence.** Otherwise, unless `isRestrictedToPluginOnly('mcp')` locks out non-plugin scopes, `getMcpConfigsByScope()` loads `user` (`~/.claude.json`), `project` (`.mcp.json` walked from filesystem root down to `cwd` so nearer directories override parents, filtered through `getProjectMcpServerStatus(name) === 'approved'`), `local` (per-project config in `~/.claude.json`), and enabled plugins (`loadAllPluginsCacheOnly()` → `getPluginMcpServers()`). Merge order is `claudeai < plugin (dynamic) < user < approved project < local`.
3. **Policy evaluation (`isMcpServerAllowedByPolicy()`, `config.ts:417-508`).**
   - `deniedMcpServers` always merges across *all* setting sources (`getMcpDenylistSettings()`, so users can still deny servers for themselves even under managed policy) and takes absolute precedence.
   - `allowedMcpServers` reads exclusively from `policySettings` when `allowManagedMcpServersOnly: true`, else merged settings. An empty array `[]` blocks everything.
   - Matching is **mode-strict**: if the allowlist contains *any* `serverCommand` entry, every `stdio` server must match one by exact `[command, ...args]` array equality; if it contains *any* `serverUrl` entry, every remote server must match a wildcard pattern (`*` → `.*`). Only when no command/URL entries exist does matching fall back to `serverName`.
   - `filterMcpServersByPolicy()` (`config.ts:536-551`) explicitly exempts `type === 'sdk'` servers because they are host-managed callbacks with neither a subprocess command nor a network URL.
4. **Content-signature deduplication (`config.ts:182-310`).** `getMcpServerSignature()` normalizes each server to either `stdio:${JSON.stringify([command, ...args])}` or `url:${unwrapCcrProxyUrl(url)}`, deliberately ignoring `env` (plugins inject `CLAUDE_PLUGIN_ROOT`) and `headers`. `dedupPluginMcpServers()` and `dedupClaudeAiMcpServers()` drop duplicates where a manually configured server already covers the same signature, surfacing suppressed plugin duplicates as informational `mcp-server-suppressed-duplicate` entries in `/plugin`.

```ts
// services/mcp/config.ts:202-212
export function getMcpServerSignature(config: McpServerConfig): string | null {
  const cmd = getServerCommandArray(config)
  if (cmd) {
    return `stdio:${jsonStringify(cmd)}`
  }
  const url = getServerUrl(config)
  if (url) {
    return `url:${unwrapCcrProxyUrl(url)}`
  }
  return null
}
```

5. **Variable expansion & dynamic headers.** `parseMcpConfig()` expands `${VAR}` and `${VAR:-default}` across `command`, `args`, `env`, `url`, and `headers` ([services/mcp/envExpansion.ts:10-38](../../services/mcp/envExpansion.ts)), logging warnings for missing variables and Windows `npx` commands lacking a `cmd /c` wrapper. At connection time, [services/mcp/headersHelper.ts](../../services/mcp/headersHelper.ts) runs an optional `headersHelper` shell command (10 s timeout, passing `CLAUDE_CODE_MCP_SERVER_NAME` and `CLAUDE_CODE_MCP_SERVER_URL`) whose JSON object output overrides static `headers`.

### Hidden Invariants & Failure Modes

- **Disabled manual servers must never suppress twins.** Both `dedupPluginMcpServers` (caller at `config.ts:1188-1193`) and `dedupClaudeAiMcpServers` (`config.ts:290`) exclude disabled or policy-blocked servers from the dedup target map. Otherwise a disabled manual `slack` entry would suppress `claude.ai Slack` or a plugin twin, leaving *neither* running.
- **Trust gate on `headersHelper`.** For `project` and `local` scopes in interactive sessions, `getMcpHeadersFromHelper()` (`headersHelper.ts:42-57`) refuses to execute unless `checkHasTrustDialogAccepted()` is true, logging `tengu_mcp_headersHelper_missing_trust`.
- **Atomic `.mcp.json` mutation.** `writeMcpjsonFile()` (`config.ts:88-131`) reads existing file mode, writes to `.mcp.json.tmp.<pid>.<ts>`, calls `handle.datasync()`, restores permissions via `chmod`, and performs an atomic `rename()` without following symlinks.
- **Opt-in vs. opt-out disable state.** Normal servers default enabled and are recorded in `disabledMcpServers`. Under `feature('CHICAGO_MCP')`, the built-in Computer Use MCP server is marked `DEFAULT_DISABLED_BUILTIN` (`config.ts:1512-1536`), flipping polarity to opt-in via `enabledMcpServers`. Both `claude-in-chrome` and the Computer Use server name are reserved and blocked in `addMcpConfig()`.

---

## 2. The Eight Transports and Connection Resilience

### The Problem

Once configs are resolved, [services/mcp/client.ts](../../services/mcp/client.ts) has to establish and sustain JSON-RPC connections over eight distinct transport shapes—while neutralizing a surprising collection of runtime and MCP SDK pitfalls:

- Passing a single `AbortSignal.timeout()` into a transport's `requestInit` expires 60 seconds after startup and fails every future tool call permanently.
- Using `AbortSignal.timeout()` per request in Bun leaks ~2.4 KB of native memory per call until lazy GC runs after the full 60 s timer expires.
- Applying any request timeout to `GET` kills persistent SSE event streams after 60 s.
- Runtimes spreading a `Headers` instance drop `Accept: application/json, text/event-stream`, triggering HTTP `406` from strict Streamable HTTP servers.
- The MCP SDK's HTTP/SSE transports invoke `onerror` on broken streams and exhausted SSE retries *without* calling `onclose`—leaving pending `callTool()` promises hung forever.
- `StdioClientTransport.close()` only aborts stdin/stdout, leaving Docker-wrapped MCP servers running as orphaned containers.

### The Real Implementation

`connectToServer()` (`services/mcp/client.ts:595-1641`) constructs the transport for each `ScopedMcpServerConfig['type']`:

| Config `type` | Transport Class | Special Wiring & Auth |
|---|---|---|
| `stdio` (or omitted) | `StdioClientTransport` | `subprocessEnv()` + `serverRef.env`; `stderr: 'pipe'` (capped at 64 MB); honors `CLAUDE_CODE_SHELL_PREFIX` |
| `stdio` (`claude-in-chrome` or `CHICAGO_MCP`) | [InProcessTransport.ts](../../services/mcp/InProcessTransport.ts) (`createLinkedTransportPair()`) | Runs server in-process via `queueMicrotask()` to avoid spawning a ~325 MB subprocess (`client.ts:905-943`) |
| `sse` | `SSEClientTransport` | `ClaudeAuthProvider`; `fetch` wrapped with step-up + 60 s POST timeout; separate *untimed* `eventSourceInit.fetch` |
| `sse-ide` | `SSEClientTransport` | No OAuth; proxy dispatcher if configured; sends `ide_connected` notification |
| `http` | `StreamableHTTPClientTransport` | `ClaudeAuthProvider`; session-ingress bearer fallback *only* when `!hasOAuthTokens` (SDK merges `requestInit` *after* `authProvider`) |
| `ws` / `ws-ide` | [utils/mcpWebSocketTransport.ts](../../utils/mcpWebSocketTransport.ts) (`WebSocketTransport`) | Subprotocol `['mcp']`; dual runtime dispatch (`globalThis.WebSocket` on Bun vs. `ws` package on Node); `ws-ide` adds `X-Claude-Code-Ide-Authorization` |
| `claudeai-proxy` | `StreamableHTTPClientTransport` | Routes through `MCP_PROXY_URL` with `X-Mcp-Client-Session-Id` and `createClaudeAiProxyFetch()` |
| `sdk` | [SdkControlTransport.ts](../../services/mcp/SdkControlTransport.ts) (`SdkControlClientTransport`) | Handled separately in `setupSdkMcpClients()` (`client.ts:3262-3348`), multiplexing JSON-RPC over CLI↔SDK control messages |

#### Fetch Wrapping, In-Process Microtasks, and SDK Bridging

Every remote POST path passes through `wrapFetchWithTimeout()` (`client.ts:492-550`):

```ts
// services/mcp/client.ts:492-549 (condensed)
export function wrapFetchWithTimeout(baseFetch: FetchLike): FetchLike {
  return async (url: string | URL, init?: RequestInit) => {
    const method = (init?.method ?? 'GET').toUpperCase()
    if (method === 'GET') {
      return baseFetch(url, init) // long-lived SSE stream — never time out
    }
    const headers = new Headers(init?.headers)
    if (!headers.has('accept')) {
      headers.set('accept', MCP_STREAMABLE_HTTP_ACCEPT) // 'application/json, text/event-stream'
    }
    const controller = new AbortController()
    const timer = setTimeout(
      c => c.abort(new DOMException('The operation timed out.', 'TimeoutError')),
      MCP_REQUEST_TIMEOUT_MS, // 60_000 ms
      controller,
    )
    timer.unref?.()
    // ... forwards parentSignal abort, clears timer in try/catch, returns baseFetch(...)
  }
}
```

For first-party in-process servers (`claude-in-chrome` via `@ant/claude-for-chrome-mcp`, and Computer Use behind `feature('CHICAGO_MCP')`), [services/mcp/InProcessTransport.ts:11-63](../../services/mcp/InProcessTransport.ts) links two `InProcessTransport` instances where `send()` schedules `queueMicrotask(() => this.peer?.onmessage?.(message))`. The microtask hop is load-bearing: synchronous delivery would blow the JS call stack on request/response chains.

For Agent SDK hosts (`type: 'sdk'`), [services/mcp/SdkControlTransport.ts:60-136](../../services/mcp/SdkControlTransport.ts) provides a mirror pair: `SdkControlClientTransport` in the CLI process invokes `sendMcpMessage(serverName, message)` (which sends an NDJSON control request over stdout and awaits the response on stdin), while `SdkControlServerTransport` in the SDK process forwards incoming JSON-RPC frames to the in-process MCP server and returns responses via callback.

For `claudeai-proxy` connectors, `createClaudeAiProxyFetch()` (`client.ts:372-422`) attaches the `claude.ai` OAuth bearer token and retries once on `401` via `handleOAuth401Error(sentToken)`. Notice the subtle race it explicitly prevents: it returns `{ response, sentToken }` from `doRequest()` rather than re-reading `getClaudeAIOAuthTokens()` after the 401. Under 30+ concurrent connectors hitting a stale token simultaneously, another connector's refresh clears the memoize cache; re-reading after the request would pass the *new* token to `handleOAuth401Error()`, see no diff against keychain, and skip the retry—stranding the connector in the 15-minute `needs-auth` cache. It also re-checks `getClaudeAIOAuthTokens()?.accessToken !== sentToken` when `handleOAuth401Error` returns `false` due to `ELOCKED` lockfile contention.

#### Connection Drop Detection and Session Expiry Recovery

The MCP client declares `capabilities: { roots: {}, elicitation: {} }` (`client.ts:994-1000`) and races `client.connect(transport)` against `MCP_TIMEOUT` (default 30 s). Once connected, `client.ts` installs a defensive wrapper around `client.onerror` and `client.onclose`:

```ts
// services/mcp/client.ts:1227-1263
let consecutiveConnectionErrors = 0
const MAX_ERRORS_BEFORE_RECONNECT = 3
let hasTriggeredClose = false

const closeTransportAndRejectPending = (reason: string) => {
  if (hasTriggeredClose) return
  hasTriggeredClose = true
  logMCPDebug(name, `Closing transport (${reason})`)
  void client.close().catch(e => {
    logMCPDebug(name, `Error during close: ${errorMessage(e)}`)
  })
}
```

> [!WARNING]
> **Why `client.close()` instead of `client.onclose?.()`:** Calling `client.onclose?.()` directly would clear the memoization cache, but any in-flight `callTool()` promise would remain hung indefinitely. Calling `client.close()` flows through `transport.close()` → SDK `_onclose()`, which rejects all pending request handlers with `McpError -32000 "Connection closed"` *and* fires `client.onclose` to evict caches (`client.ts:1234-1247`).

Three error signatures trigger `closeTransportAndRejectPending()`:
1. **Session expiry (`isMcpSessionExpiredError`, `client.ts:193-206`):** requires *both* HTTP `404` (`error.code === 404`) and JSON-RPC error code `-32001` in the message body so generic web 404s never cause false reconnect storms.
2. **Exhausted SDK SSE retries:** `error.message.includes('Maximum reconnection attempts')` (`client.ts:1342`).
3. **Three consecutive terminal transport errors:** `ECONNRESET`, `ETIMEDOUT`, `EPIPE`, `EHOSTUNREACH`, `ECONNREFUSED`, `Body Timeout Error`, `terminated`, `SSE stream disconnected`, or `Failed to reconnect SSE stream`.

At the tool-call layer, `callMCPTool()` (`client.ts:3217-3231`) catches both a direct `404 / -32001` and the derived HTTP `-32000 "Connection closed"` rejection, clears the connection cache via `clearServerCache()`, and throws `McpSessionExpiredError`. The outer loop in `fetchToolsForClient()`'s `call()` wrapper (`client.ts:1859-1922`) retries once (`MAX_SESSION_RETRIES = 1`) via `ensureConnectedClient()`.

### Hidden Invariants & Failure Modes

- **Stdio escalation ladder (`client.ts:1426-1562`).** `cleanup()` registers with `registerCleanup()` (`utils/cleanupRegistry.ts`) for *all* transport types. For `stdio`, it explicitly sends `SIGINT`, polls `process.kill(pid, 0)` every 50 ms for 100 ms, escalates to `SIGTERM` for 400 ms, and finishes with `SIGKILL` under a 600 ms absolute failsafe.
- **Work-stealing concurrency split (`client.ts:2218-2403`).** `getMcpToolsCommandsAndResources()` partitions active servers into local (`stdio`/`sdk`, concurrency 3 via `MCP_SERVER_CONNECTION_BATCH_SIZE`) and remote (concurrency 20 via `MCP_REMOTE_SERVER_CONNECTION_BATCH_SIZE`) and runs both pools concurrently through `pMap`. A March 2026 scar note (`client.ts:2212-2217`) explains why `pMap` replaced fixed sequential batches: one slow server in batch *N* previously stalled all 20 slots of batch *N+1*.
- **Coupled cache eviction.** `connectToServer` is `lodash-es/memoize`d by `${name}-${jsonStringify(serverRef)}`, while `fetchToolsForClient`, `fetchResourcesForClient`, and `fetchCommandsForClient` use `memoizeWithLRU(..., 20)` keyed by `client.name`. Both `client.onclose` (`client.ts:1389-1396`) and `clearServerCache()` (`client.ts:1666-1672`) must evict all four caches together—otherwise a reconnected client serves stale tools from the dead connection. `reconnectMcpServerImpl()` (`client.ts:2152`) also calls `clearKeychainCache()` before reconnecting so tokens updated by a sibling process (like the VS Code extension host) take effect immediately.

---

## 3. OAuth 2.1, Cross-Process Refresh Locking, Step-Up Auth, and XAA

### The Problem

Remote `sse` and `http` MCP servers authenticate through OAuth 2.1, exposing five classic production traps:

1. **Multi-process token rotation races.** A developer runs three Claude Code terminals pointing at the same Linear or Slack MCP server. All three detect an expiring token at the same minute and race to consume a single-use refresh token—two fail with `invalid_grant` and wipe the third process's freshly saved credentials.
2. **The macOS Keychain 4 KB cliff.** Storing full OAuth authorization server metadata (~1.5–2 KB per server) in secure storage overflows `security -i`'s 4096-byte stdin line limit (~2013 bytes of JSON after hex encoding) as soon as two OAuth servers are connected, corrupting the entire credential store.
3. **Hot-path keychain CPU burn.** The MCP SDK invokes `authProvider.tokens()` inside `_commonHeaders` on *every* HTTP request; invalidating the keychain cache on each call spawns `security find-generic-password` 30–40 times/sec (measured at 7.2% of total CPU).
4. **RFC 6749 §6 step-up deadlocks.** When a server returns `403 insufficient_scope`, the SDK's default handler sees a `refresh_token`, refreshes (which RFC 6749 §6 forbids from elevating scope), retries with the same-scoped token, gets `403` again, and aborts—never triggering re-consent.
5. **Non-standard providers and startup 401 storms.** Slack returns HTTP `200` with `{"error":"invalid_refresh_token"}`, bypassing the SDK's `!response.ok` error parser. Meanwhile, 30 unauthenticated remote servers would execute 60+ HTTP round-trips on every startup (blocking print mode) without negative caching.

### The Real Implementation

[services/mcp/auth.ts](../../services/mcp/auth.ts) solves each of these inside `ClaudeAuthProvider` (implementing the SDK's `OAuthClientProvider`) and `performMCPOAuthFlow()`.

#### Keying, Discovery, and CIMD

Credentials live in `getSecureStorage()` under `mcpOAuth[serverKey]` where `getServerKey()` (`auth.ts:325-341`) hashes `{ type, url, headers }` into `${serverName}|${sha256.slice(0, 16)}`, preventing tokens from leaking across two servers that share a name.

`fetchAuthServerMetadata()` (`auth.ts:256-311`) resolves OAuth metadata in three tiers:
1. Explicit `oauth.authServerMetadataUrl` (enforcing `https://` at both Zod schema and runtime).
2. RFC 9728 Protected Resource Metadata (`/.well-known/oauth-protected-resource`) → RFC 8414 Authorization Server Metadata via `discoverOAuthServerInfo()`.
3. Legacy path-aware RFC 8414 fallback (`/.well-known/oauth-authorization-server/{path}`) when the MCP URL has a non-root path.

For client registration, `ClaudeAuthProvider.clientMetadataUrl` (`auth.ts:1445-1452`) implements **CIMD (SEP-991)**: when the authorization server advertises `client_id_metadata_document_supported: true`, the SDK uses `MCP_CLIENT_METADATA_URL` (or `MCP_OAUTH_CLIENT_METADATA_URL`) as `client_id` instead of Dynamic Client Registration.

#### Browser Callback Flow (`performMCPOAuthFlow`, `auth.ts:847-1342`)

Interactive auth binds a temporary HTTP server on `127.0.0.1` using `findAvailablePort()` ([services/mcp/oauthPort.ts:36-78](../../services/mcp/oauthPort.ts))—picking a random port in `49152–65535` on POSIX, `39152–49151` on Windows (where 49152+ is reserved), falling back to `3118`, or honoring `oauth.callbackPort` / `MCP_OAUTH_CALLBACK_PORT`. It generates a 32-byte `base64url` CSRF `state`, passes the URL to `onAuthorizationUrl` *before* calling `openBrowser()`, supports manual callback URL pasting (`options.onWaitingForCallback`) for SSH/headless users, sanitizes error pages with `xss()`, and calls `server.unref()` plus `timeoutId.unref()` (5 min timeout) so an unmounted UI never keeps the process alive.

#### Cross-Process Lockfile Token Refresh (`auth.ts:2090-2359`)

When `tokens()` sees `expiresIn <= 300s` and a `refreshToken` exists, it coalesces concurrent in-process callers on `this._refreshInProgress` and enters `refreshAuthorization()`:

```ts
// services/mcp/auth.ts:2138-2165
try {
  // Re-read tokens after acquiring lock — another process may have refreshed
  clearKeychainCache()
  const storage = getSecureStorage()
  const data = storage.read()
  const tokenData = data?.mcpOAuth?.[serverKey]
  if (tokenData) {
    const expiresIn = (tokenData.expiresAt - Date.now()) / 1000
    if (expiresIn > 300) {
      logMCPDebug(this.serverName, `Another process already refreshed tokens ...`)
      return {
        access_token: tokenData.accessToken,
        refresh_token: tokenData.refreshToken,
        expires_in: expiresIn,
        scope: tokenData.scope,
        token_type: 'Bearer',
      }
    }
    if (tokenData.refreshToken) {
      refreshToken = tokenData.refreshToken
    }
  }
  return await this._doRefresh(refreshToken)
} finally { ... }
```

The lockfile is `~/.claude/mcp-refresh-<sanitizedKey>.lock` (up to 5 retries with 1–2 s jitter on `ELOCKED`). Inside `_doRefresh()`, transient errors (`ServerError`, `TemporarilyUnavailableError`, `TooManyRequestsError`, timeouts) retry up to 3 times (`1s`, `2s`, `4s`). Even if the AS returns `InvalidGrantError`, `_doRefresh()` calls `clearKeychainCache()` and checks storage one last time—adopting a sibling process's winning token if `expiresIn > 300` before calling `invalidateCredentials('tokens')` (`auth.ts:2289-2325`).

#### Step-Up Scope Interception & Slack 200-Error Normalization

To break the RFC 6749 §6 refresh loop, both `sse` and `http` transports wrap their innermost fetch with `wrapFetchWithStepUpDetection()` (`auth.ts:1354-1374`):

```ts
// services/mcp/auth.ts:1354-1374
export function wrapFetchWithStepUpDetection(
  baseFetch: FetchLike,
  provider: ClaudeAuthProvider,
): FetchLike {
  return async (url, init) => {
    const response = await baseFetch(url, init)
    if (response.status === 403) {
      const wwwAuth = response.headers.get('WWW-Authenticate')
      if (wwwAuth?.includes('insufficient_scope')) {
        const match = wwwAuth.match(/scope=(?:"([^"]+)"|([^\s,]+))/)
        const scope = match?.[1] ?? match?.[2]
        if (scope) {
          provider.markStepUpPending(scope)
        }
      }
    }
    return response
  }
}
```

When `this._pendingStepUpScope` contains a scope missing from `tokenData.scope`, `tokens()` intentionally returns `refresh_token: undefined` (`auth.ts:1628-1690`). The SDK skips refresh, calls `redirectToAuthorization()`, and because the transport-attached provider has `handleRedirection = false`, it persists `existing.stepUpScope` (`auth.ts:1890-1900`) so the subsequent interactive `performMCPOAuthFlow()` requests the elevated scope immediately without an extra probe.

Meanwhile, `createAuthFetch()` pipes every OAuth `POST` response through `normalizeOAuthErrorBody()` (`auth.ts:147-190`), which peeks at HTTP `2xx` bodies matching `OAuthErrorResponseSchema` (and not `OAuthTokensSchema`), rewrites non-standard error codes (`invalid_refresh_token`, `expired_refresh_token`, `token_expired`) to `invalid_grant`, and returns a synthetic HTTP `400` so the SDK's `InvalidGrantError` path fires reliably.

#### Cross-App Access (XAA / SEP-990)

Behind `CLAUDE_CODE_ENABLE_XAA=1` and per-server `oauth.xaa: true`, [services/mcp/xaa.ts](../../services/mcp/xaa.ts) and [services/mcp/xaaIdpLogin.ts](../../services/mcp/xaaIdpLogin.ts) eliminate per-server browser consent screens for enterprise deployments:
1. A single OIDC browser login against the org's IdP (`settings.xaaIdp`) caches an `id_token` keyed by issuer.
2. `performCrossAppAccess()` exchanges `id_token` → ID-JAG via **RFC 8693 Token Exchange** at the IdP, then exchanges ID-JAG → `access_token` via **RFC 7523 `jwt-bearer` grant** at the MCP server's AS.
3. `ClaudeAuthProvider.tokens()` (`auth.ts:1585-1615`) silently triggers `xaaRefresh()` whenever a cached `id_token` exists and the access token is absent or expiring.

> [!IMPORTANT]
> **No silent downgrade on XAA (`auth.ts:864-876`).** If `oauth.xaa: true` is configured, `performMCPOAuthFlow()` never falls back to the standard consent flow—even if `CLAUDE_CODE_ENABLE_XAA` is unset. Falling back would silently bypass the enterprise IdP's authorization posture.

#### Needs-Auth Caching & `McpAuthTool`

To stop unauthenticated remote servers from burning startup latency on every turn, `client.ts:257-316` maintains a 15-minute `mcp-needs-auth-cache.json` (coalescing concurrent reads on `authCachePromise` and serializing read-modify-write updates through a module-level `writeChain`). `getMcpToolsCommandsAndResources()` (`client.ts:2307-2322`) skips connecting if the server is in that cache *or* `hasMcpDiscoveryButNoToken()` sees persisted OAuth discovery state with empty tokens (bypassed for XAA servers so silent re-auth stays reachable).

Rather than leaving the server invisible to the model, `needs-auth` servers receive a synthesized pseudo-tool from `createMcpAuthTool()` ([tools/McpAuthTool/McpAuthTool.ts:49-215](../../tools/McpAuthTool/McpAuthTool.ts)) named `mcp__<server>__authenticate`. When the model calls it, it launches `performMCPOAuthFlow(..., { skipBrowserOpen: true })`, races `onAuthorizationUrl` against silent completion (XAA), and returns the URL for the user to open. A `.then()` continuation waits in the background, calls `reconnectMcpServerImpl()`, and swaps the server's real tools into `AppState.mcp.tools`—automatically wiping the `authenticate` pseudo-tool via prefix replacement (`mcp__<server>__*`).

### Hidden Invariants & Failure Modes

- **Stripped discovery persistence (`auth.ts:2007-2035`).** `saveDiscoveryState()` writes *only* `{ authorizationServerUrl, resourceMetadataUrl }`—never `authorizationServerMetadata` or `resourceMetadata`—to stay well under macOS `security -i`'s 4096-byte stdin cap.
- **No `clearKeychainCache()` in `tokens()` (`auth.ts:1541-1549`).** `tokens()` uses `await storage.readAsync()` and relies on the keychain TTL; cache clearing is reserved for lock-protected refreshes, explicit reconnects, and `InvalidGrantError` recovery.
- **Mid-session 401 demotion.** If an active tool call hits HTTP 401 or `UnauthorizedError`, `callMCPTool()` throws `McpAuthError` (`client.ts:3198-3207`). [services/tools/toolExecution.ts:1601-1629](../../services/tools/toolExecution.ts) catches `McpAuthError` and transitions that entry in `AppState.mcp.clients` from `'connected'` to `'needs-auth'` so `/mcp` reflects the stale token immediately.

---

## 4. Live Connection Lifecycle, Notifications, and Elicitation

### The Problem

In interactive sessions, MCP connections are not a one-shot startup step. Servers connect asynchronously at wildly different speeds, drop over Wi-Fi sleep, change their tool lists at runtime, push inbound chat messages (channels), pause mid-tool-call to request human input (elicitations), and get added/removed live when the user edits `.mcp.json` or runs `/reload-plugins`.

### The Real Implementation

[services/mcp/MCPConnectionManager.tsx](../../services/mcp/MCPConnectionManager.tsx) mounts `useManageMCPConnections()` ([services/mcp/useManageMCPConnections.ts](../../services/mcp/useManageMCPConnections.ts)) and exposes `reconnectMcpServer` and `toggleMcpServer` via React context.

#### Two-Phase Startup & 16 ms State Coalescing

`useManageMCPConnections()` runs two coordinated effects keyed on `sessionId`, `authVersion`, `dynamicMcpConfig`, and `mcp.pluginReconnectKey`:

1. **Pending initialization + stale eviction (`useManageMCPConnections.ts:772-854`).** Seeds all local/plugin servers into `AppState.mcp.clients` as `'pending'` (or `'disabled'`) immediately so the UI renders status right away. Before adding new entries, it runs `excludeStalePluginClients()` ([services/mcp/utils.ts:185-224](../../services/mcp/utils.ts)), which compares `hashMcpConfig()` (SHA-256 of key-sorted config excluding `scope`) to detect edited `.mcp.json` servers across *all* scopes and removed servers in `'dynamic'` scope.
2. **Two-phase connection (`useManageMCPConnections.ts:858-1024`).** Kicks off `fetchClaudeAIMcpConfigsIfEligible()` *before* `getClaudeCodeMcpConfigs()` so the network call overlaps with `loadAllPluginsCacheOnly()`. Phase 1 starts connecting local/plugin servers immediately without waiting for Phase 2; Phase 2 awaits the memoized `claudeaiPromise`, policy-filters, deduplicates against manual servers, and starts connecting `claude.ai` proxies concurrently.
3. **16 ms batch window (`useManageMCPConnections.ts:207-308`).** Because 20+ servers complete handshakes milliseconds apart, `updateServer()` buffers incoming updates in `pendingUpdatesRef` and flushes them in one `setAppState()` call every `MCP_BATCH_FLUSH_MS = 16` ms (one terminal frame). Each flush replaces tools/commands/resources cleanly by server prefix (`mcp__<server>__`, plus `<server>:` for MCP skills via `commandBelongsToServer()`).

#### Automatic Backoff Reconnects & Server Notifications

Inside `onConnectionAttempt()` (`useManageMCPConnections.ts:310-763`), every newly `'connected'` server wires four classes of runtime handlers:

- **`client.onclose` backoff loop (`333-468`).** For remote transports (`http`, `sse`, `ws`, `ws-ide`, `sse-ide`, `claudeai-proxy`), clears server cache and retries up to `MAX_RECONNECT_ATTEMPTS = 5` with exponential backoff (`1s → 2s → 4s → 8s → 16s`, capped at `30s`), checking `isMcpServerDisabled(name)` before every attempt. Local `stdio` and `sdk` servers transition directly to `'failed'`.
- **`list_changed` notifications (`618-751`).** If the server advertises `capabilities.{tools,prompts,resources}.listChanged`, registers handlers for `ToolListChangedNotificationSchema`, `PromptListChangedNotificationSchema`, and `ResourceListChangedNotificationSchema` that evict the corresponding `fetch*ForClient` LRU entry and push fresh snapshots through `updateServer()`.
- **Channel push notifications (`473-614`, [services/mcp/channelNotification.ts](../../services/mcp/channelNotification.ts)).** Behind `feature('KAIROS') || feature('KAIROS_CHANNELS')` and runtime gate `tengu_harbor` (requiring `claude.ai` OAuth and org `channelsEnabled: true`), `gateChannelServer()` decides `'register'` vs. `'skip'`. Registered servers map `notifications/claude/channel` into `enqueue()` wrapped in `<channel>` XML tags (with strict identifier validation on `meta` keys to prevent XML attribute injection), and—if the server explicitly opts in via `capabilities.experimental['claude/channel/permission']`—route `notifications/claude/channel/permission` replies to `ChannelPermissionCallbacks`. On `'skip'`, it explicitly calls `removeNotificationHandler()` so a mid-session `/logout` demotes live handlers idempotently.

> [!NOTE]
> **Snapshot Absences Observed at Call Sites:** Two build-time-gated modules imported in [services/mcp/client.ts:117-121](../../services/mcp/client.ts) and [services/mcp/useManageMCPConnections.ts:22-31](../../services/mcp/useManageMCPConnections.ts) are absent from this checkout: `skills/mcpSkills.ts` (under `feature('MCP_SKILLS')`, observed calling `fetchMcpSkillsForClient(client)` and `.cache.delete(name)` when `resources/list_changed` fires) and `services/skillSearch/localSearch.ts` (under `feature('EXPERIMENTAL_SKILL_SEARCH')`, observed calling `clearSkillIndexCache()`). Similarly, `types/message.ts` and `@ant/claude-for-chrome-mcp` are referenced at call sites but absent from the snapshot.

#### Elicitation: Form, URL, Hooks, and Error `-32042` Retries

MCP Elicitation lets a server pause execution to ask the user for structured form data (`mode: 'form'`) or out-of-band browser action (`mode: 'url'`). Two subtle design details hold it together:

1. **Empty capability object (`client.ts:996-999`).** The handshake advertises `elicitation: {}` instead of `{ form: {}, url: {} }` because Spring AI's Java MCP SDK defines an empty `Elicitation` class that throws on unknown JSON properties.
2. **Bootstrap cancel handler (`client.ts:1188-1197`).** `connectToServer()` installs a placeholder `ElicitRequestSchema` handler returning `{ action: 'cancel' }` to cover the narrow window before `onConnectionAttempt()` calls `registerElicitationHandler()` ([services/mcp/elicitationHandler.ts:68-212](../../services/mcp/elicitationHandler.ts)).

Once registered, elicitations flow along two complementary paths:

- **Explicit request (`ElicitRequestSchema`):** Runs `runElicitationHooks()` first (hooks can programmatically `accept`, `decline`, or `cancel` without touching the UI); otherwise pushes an `ElicitationRequestEvent` onto `AppState.elicitation.queue`, awaits the dialog's `respond()` (or `extra.signal` abort), and filters the user's answer through `runElicitationResultHooks()` (which can mutate or block the response before returning it to the server).
- **Error-driven URL retry (`callMCPToolWithUrlElicitationRetry`, `client.ts:2813-3027`):** When a tool call fails with `McpError` code `ErrorCode.UrlElicitationRequired` (`-32042`), `client.ts` extracts `error.data.elicitations` (note: checks `error.code` rather than `instanceof UrlElicitationRequiredError` because the SDK constructs plain `McpError`s) and processes up to `MAX_URL_ELICITATION_RETRIES = 3` rounds. In headless/SDK mode, it delegates to `context.handleElicitation` (`structuredIO`); in interactive REPL mode, it uses a **two-phase waiting flow**: `respond({ action: 'accept' })` is intentionally a no-op (the user just opened the browser), while either `onWaitingDismiss('retry')` or the server's `ElicitationCompleteNotificationSchema` setting `completed: true` on the queue entry (`elicitationHandler.ts:175-207`) resolves the promise and retries the tool call.

### Hidden Invariants & Failure Modes

- **Three hazards defused during stale-server cleanup (`useManageMCPConnections.ts:791-812`).** Because React state updaters must be synchronous, disconnecting stale servers on `/reload-plugins` or `.mcp.json` edits runs fire-and-forget—after explicitly: (1) clearing any pending `reconnectTimersRef` timer (which holds the *old* config), (2) setting `s.client.onclose = undefined` (preventing the old closure's `reconnectWithBackoff` from racing the fresh connection), and (3) calling `clearServerCache()` *only* when `s.type === 'connected'` (for never-connected servers, `clearServerCache` invokes memoized `connectToServer`, which would spawn a server just to kill it).
- **Disk-first disable ordering (`useManageMCPConnections.ts:1093-1100`).** `toggleMcpServer()` writes `setMcpServerEnabled(serverName, false)` to disk *before* calling `clearServerCache()`. The `onclose` callback deliberately reads disk state via `isMcpServerDisabled()` rather than a stale React state closure; reversing those two lines spawns an immediate auto-reconnect loop for a server the user just disabled.

---

## 5. Adapting MCP Tools: Normalization, Permissions, Output Budgeting, and Cache Partitioning

### The Problem

Raw MCP tool definitions cannot be handed directly to the Anthropic Messages API or the permission engine:

- Server and tool names can contain dots, spaces, or slashes (`claude.ai Google Drive`, `org/search`), violating the API's `^[a-zA-Z0-9_-]{1,64}$` tool-name pattern.
- OpenAPI-generated MCP servers have been observed returning 15–60 KB `description` strings and massive JSON payloads or raw base64 audio/PDF attachments.
- In `CLAUDE_AGENT_SDK_MCP_NO_PREFIX` mode, SDK MCP servers expose unprefixed tool names (like `Write`) to override built-ins—which could accidentally match built-in permission rules if rule matching inspected `tool.name`.
- Sorting MCP tools alongside built-ins alphabetically inserts `mcp__*` between `Grep` and `Read`, shattering Anthropic's global tool-prefix prompt cache across every user.

### The Real Implementation

#### Naming & Permission Key Separation

[services/mcp/normalization.ts:17-23](../../services/mcp/normalization.ts) implements `normalizeNameForMCP()`: replaces any character outside `[a-zA-Z0-9_-]` with `_`, and for `claude.ai ` servers also collapses consecutive `_+` and trims leading/trailing underscores so they cannot collide with the `__` delimiter. ([services/mcp/claudeai.ts:93-111](../../services/mcp/claudeai.ts) additionally deduplicates post-normalization collisions by appending `(2)`, `(3)` suffixes.)

[services/mcp/mcpStringUtils.ts:19-67](../../services/mcp/mcpStringUtils.ts) builds and parses qualified names (`mcp__<server>__<tool>`) and defines the permission-key invariant:

```ts
// services/mcp/mcpStringUtils.ts:60-67
export function getToolNameForPermissionCheck(tool: {
  name: string
  mcpInfo?: { serverName: string; toolName: string }
}): string {
  return tool.mcpInfo
    ? buildMcpToolName(tool.mcpInfo.serverName, tool.mcpInfo.toolName)
    : tool.name
}
```

[utils/permissions/permissions.ts:240-269](../../utils/permissions/permissions.ts) uses `getToolNameForPermissionCheck(tool)` for *every* allow, deny, and ask rule match. Even when `CLAUDE_AGENT_SDK_MCP_NO_PREFIX` sets `tool.name = 'Write'`, permission evaluation checks `mcp__my_sdk_server__Write` via `tool.mcpInfo`. `toolMatchesRule()` also supports server-wide rules: a rule targeting `mcp__github` or `mcp__github__*` matches every tool whose parsed `mcpInfoFromString()` shares `serverName === 'github'`. Crucially, `filterToolsByDenyRules()` ([tools.ts:262-269](../../tools.ts)) runs this exact matcher *before* tools reach the model, so blanket-denied servers disappear from the prompt entirely.

#### Synthesizing `Tool` Objects via `MCPTool`

[tools/MCPTool/MCPTool.ts](../../tools/MCPTool/MCPTool.ts) defines the shared fail-closed template (`isMcp: true`, `inputSchema: z.object({}).passthrough()`, `maxResultSizeChars: 100_000`, `checkPermissions()` returning `'passthrough'`, plus shared Ink UI renderers). For each connected server, `fetchToolsForClient()` (`client.ts:1743-1998`) runs `tools/list`, sanitizes the payload via `recursivelySanitizeUnicode()`, and spreads `...MCPTool` with per-tool overrides:

- **Description & instruction caps:** Both `tool.prompt()` (`client.ts:1789-1794`) and `InitializeResult.instructions` (`client.ts:1160-1171`) truncate at `MAX_MCP_DESCRIPTION_LENGTH = 2048` chars.
- **Safety & scheduling annotations:** `isConcurrencySafe()` and `isReadOnly()` both delegate to `tool.annotations?.readOnlyHint ?? false` (fail-closed serial execution unless the server explicitly declares read-only); `isDestructive()` and `isOpenWorld()` read `destructiveHint` and `openWorldHint`; `toAutoClassifierInput()` encodes arguments as `k=v` pairs for Chapter 11's auto-mode classifier.
- **Discovery metadata:** `searchHint` reads `_meta['anthropic/searchHint']` and collapses `\s+` to a single space (preventing external servers from injecting fake tool lines via `\n` into deferred-tool listings!), while `alwaysLoad` checks `_meta['anthropic/alwaysLoad'] === true`.
- **Permission suggestions:** `checkPermissions()` returns `'passthrough'` with an `addRules` suggestion targeting the exact `fullyQualifiedName` in `localSettings` (`client.ts:1814-1832`).
- **Execution & progress:** `call()` attaches `_meta: { 'claudecode/toolUseId': toolUseId }`, streams `MCPProgress` events (`started` / `progress` / `completed` / `failed`), races `client.callTool()` against `MCP_TOOL_TIMEOUT` (default `100_000_000` ms ≈ 27.8 h, guarding against broken SSE streams where the SDK's own timeout fails to fire), and maps `isError: true` into `McpToolCallError` while preserving `_meta`.

MCP **prompts** (`prompts/list`) are adapted in `fetchCommandsForClient()` (`client.ts:2033-2107`) into `type: 'prompt'` `Command` objects named `mcp__<server>__<prompt>` (using `prompt.name`, not `prompt.title`, so spaces cannot break slash-command parsing). Whenever any connected server advertises `capabilities.resources`, `client.ts:2360-2364` injects the built-in `ListMcpResourcesTool` and `ReadMcpResourceTool` into the tool pool.

#### Output Transformation & Disk Spillover

`transformMCPResult()` and `processMCPResult()` (`client.ts:2478-2799`) protect the context window from rogue server payloads:
- `image` blocks and image resource blobs pass through `maybeResizeAndDownsampleImageBuffer()`.
- `audio` blocks and non-image binary `resource.blob`s are decoded and saved to disk via `persistBlobToTextBlock()`, returning a short file-path text block instead of raw base64.
- Text / `structuredContent` / `contentArray` outputs exceeding `getMaxMcpOutputTokens()` ([utils/mcpValidation.ts:16-47](../../utils/mcpValidation.ts): default `25,000` tokens, overridable via `MAX_MCP_OUTPUT_TOKENS` or GrowthBook `tengu_satin_quoll['mcp_tool']`) are persisted via `persistToolResult()` with a compact jq-friendly shape inferred by `inferCompactSchema()` (`{title: string, items: [{id: number, name: string}]}`) so the model can slice the file precisely. If `ENABLE_MCP_LARGE_OUTPUT_FILES` is falsy or the output contains images (which would lose compression if JSON-serialized), it falls back to `truncateMcpContentIfNeeded()`.

#### Partition-Sorting for Global Prompt Cache Stability

In [tools.ts:345-367](../../tools.ts) (and identically in [utils/toolPool.ts:55-79](../../utils/toolPool.ts) for `useMergedTools`), built-in tools and MCP tools are *never* sorted in one flat array:

```ts
// tools.ts:345-367
export function assembleToolPool(
  permissionContext: ToolPermissionContext,
  mcpTools: Tools,
): Tools {
  const builtInTools = getTools(permissionContext)
  const allowedMcpTools = filterToolsByDenyRules(mcpTools, permissionContext)

  const byName = (a: Tool, b: Tool) => a.name.localeCompare(b.name)
  return uniqBy(
    [...builtInTools].sort(byName).concat(allowedMcpTools.sort(byName)),
    'name',
  )
}
```

> [!IMPORTANT]
> **Why partition-sorting is load-bearing:** Anthropic's server-side `claude_code_system_cache_policy` places a global cache breakpoint immediately after the last prefix-matched built-in tool. Keeping built-ins as a contiguous sorted prefix means per-user MCP tools sit strictly *after* the global breakpoint, and `uniqBy(..., 'name')` guarantees built-ins win any name collision.

### Hidden Invariants & Failure Modes

- **Double-underscore parsing asymmetry (`mcpStringUtils.ts:14-31`).** `mcpInfoFromString()` splits on `__`, takes `parts[1]` as `serverName`, and rejoins `parts.slice(2)` with `__` as `toolName`. Tool names with `__` round-trip intact; server names containing `__` do not.
- **IDE server tool allowlist (`client.ts:568-573`).** `isIncludedMcpTool()` drops every tool prefixed `mcp__ide__` except `mcp__ide__executeCode` and `mcp__ide__getDiagnostics`.
- **Coordinator mode pruning (`utils/toolPool.ts:11-41`).** Under `feature('COORDINATOR_MODE')`, `applyCoordinatorToolFilter()` strips MCP tools from the coordinator except lightweight PR activity subscription suffixes (`subscribe_pr_activity`, `unsubscribe_pr_activity`).

---

## 6. Solving Tool-Schema Bloat Without Cache Busts: `ToolSearchTool` and Deferred Loading

### The Problem

Partition-sorting protects built-in caches, but two scaling cliffs remain when dozens of MCP servers are attached:
1. **Token bloat:** Sending 250 full JSON schemas on every turn consumes 25k–60k tokens before the user types a word—and degrades tool-selection accuracy.
2. **Cache-busting announcements:** Even if schemas are deferred, telling the model *which* deferred tools exist by prepending a synthetic `<available-deferred-tools>` message at index 0—or injecting server instructions into the system prompt—invalidates the *entire* conversation cache whenever an MCP server connects 2 seconds late or reconnects mid-session.

### The Real Implementation

Claude Code solves both problems through a four-part protocol spanning [tools/ToolSearchTool/prompt.ts](../../tools/ToolSearchTool/prompt.ts), [tools/ToolSearchTool/ToolSearchTool.ts](../../tools/ToolSearchTool/ToolSearchTool.ts), [utils/toolSearch.ts](../../utils/toolSearch.ts), [utils/attachments.ts](../../utils/attachments.ts), and [services/api/claude.ts](../../services/api/claude.ts).

#### 1. Deferral Policy and Mode Selection

`isDeferredTool(tool)` (`tools/ToolSearchTool/prompt.ts:62-108`) decides per tool in strict priority order:
1. `tool.alwaysLoad === true` → **never deferred** (lets MCP servers opt critical tools into turn 1 via `_meta['anthropic/alwaysLoad']`).
2. `tool.isMcp === true` → **always deferred**.
3. `ToolSearch` itself (plus `Agent` when `feature('FORK_SUBAGENT')` is enabled, and `Brief` / `SendUserFile` under `feature('KAIROS')` / `KAIROS_BRIEF`) → **never deferred**.
4. Built-ins setting `tool.shouldDefer === true` → **deferred**.

`getToolSearchMode()` (`utils/toolSearch.ts:172-198`) resolves `ENABLE_TOOL_SEARCH`:
- Unset (default), `true`, or `auto:0` → `'tst'` (always defer).
- `auto` or `auto:1-99` → `'tst-auto'` (defer only when deferred tool schemas exceed *N*% of the model's context window—default `10%`—measured via memoized `countToolDefinitionTokens()` with a `2.5` chars/token fallback).
- `false` or `auto:100` → `'standard'` (inline all tools).

Three runtime guards can still disable deferral for a specific call (`utils/toolSearch.ts:181-435`):
- `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` forces `'standard'` *and* strips `defer_loading` at `toolToAPISchema()` ([utils/api.ts:243](../../utils/api.ts)) for strict third-party gateways.
- Non-first-party `ANTHROPIC_BASE_URL` proxies disable tool search automatically *only when* `ENABLE_TOOL_SEARCH` is unset (`utils/toolSearch.ts:299-311`); setting `ENABLE_TOOL_SEARCH=true` or `auto` explicitly opts compatible proxies (LiteLLM, Cloudflare AI Gateway) back in.
- `modelSupportsToolReference(model)` rejects models matching GrowthBook `tengu_tool_search_unsupported_models` (default `['haiku']`), and `isToolSearchToolAvailable(tools)` disables deferral if `ToolSearch` was stripped by `disallowedTools`.

#### 2. Dynamic Wire Filtering & `defer_loading: true`

At API request assembly in [services/api/claude.ts:1120-1255](../../services/api/claude.ts), Claude Code does **not** send all 250 deferred tool definitions on turn 1—not even with `defer_loading: true`:

```ts
// services/api/claude.ts:1154-1168
if (useToolSearch) {
  const discoveredToolNames = extractDiscoveredToolNames(messages)

  filteredTools = tools.filter(tool => {
    // Always include non-deferred tools
    if (!deferredToolNames.has(tool.name)) return true
    // Always include ToolSearchTool (so it can discover more tools)
    if (toolMatchesName(tool, TOOL_SEARCH_TOOL_NAME)) return true
    // Only include deferred tools that have been discovered
    return discoveredToolNames.has(tool.name)
  })
}
```

Every tool in `filteredTools` is converted by `toolToAPISchema()` ([utils/api.ts:119-230](../../utils/api.ts)), which session-caches the immutable base schema (`name`, `description`, `input_schema`, `strict`, `eager_input_streaming`) keyed by `${tool.name}:${jsonStringify(inputJSONSchema)}` so mid-session GrowthBook flips (`tengu_tool_pear`, `tengu_fgts`) never mutate serialized schema bytes, and overlays `defer_loading: true` on every discovered deferred tool (`willDefer(t)` at `claude.ts:1208-1209`, which also defers LSP tools when `shouldDeferLspTool(t)` is true).

The request adds the provider-specific beta header (`advanced-tool-use` on 1P/Foundry; `tool-search-tool` on Vertex/Bedrock). On the server, Anthropic's API strips `defer_loading: true` definitions out of the top-of-prompt tool list and expands them inline *only* where a `tool_reference` content block appears inside a `ToolSearch` `tool_result` in message history.

That gives two simultaneous wins:
- **Zero prefix mutation on discovery:** Adding a newly discovered MCP tool to `filteredTools` with `defer_loading: true` never alters the cached top-of-prompt tool bytes. `claude.ts:1212-1214` even keeps global system-prompt caching active (`needsToolBasedCacheMarker = false`) whenever all MCP tools in `filteredTools` are deferred, and `PROMPT_CACHE_BREAK_DETECTION` (`claude.ts:1460-1467`) excludes `defer_loading: true` schemas from its cache-break hash.
- **Compaction survival (`utils/toolSearch.ts:545-592`):** Because compaction summarizes away earlier `tool_result` blocks containing `tool_reference`s, [services/compact/compact.ts](../../services/compact/compact.ts) and [services/compact/sessionMemoryCompact.ts](../../services/compact/sessionMemoryCompact.ts) call `extractDiscoveredToolNames()` before summarizing and persist the set onto `compactMetadata.preCompactDiscoveredTools` on the `compact_boundary` system message. `extractDiscoveredToolNames()` reads that field back on subsequent turns so the model keeps calling previously discovered tools without re-searching.

#### 3. Cache-Safe Announcements via `deferred_tools_delta`

How does the model know what names exist to search for?
- **Legacy path (`!isDeferredToolsDeltaEnabled()`):** [services/api/claude.ts:1330-1345](../../services/api/claude.ts) prepends an ephemeral `<available-deferred-tools>` user message at index 0 of `messagesForAPI`. Every time an MCP server connects or disconnects, index 0 changes and busts the entire conversation cache.
- **Delta attachment path (`USER_TYPE === 'ant'` or GrowthBook `tengu_glacier_2xr`):** `getDeferredToolsDeltaAttachment()` ([utils/attachments.ts:1455-1475](../../utils/attachments.ts)) calls `getDeferredToolsDelta()` ([utils/toolSearch.ts:646-706](../../utils/toolSearch.ts)), which reconstructs the already-announced set by scanning prior `deferred_tools_delta` attachments in `messages` and appends *only* newly added or disconnected tool names at the **tail** of the conversation as a `<system-reminder>` ([utils/messages.ts:4178-4193](../../utils/messages.ts)). Earlier turns stay byte-identical and cache-hot.

Notice the exact twin mechanism for MCP server instructions in [utils/mcpInstructionsDelta.ts](../../utils/mcpInstructionsDelta.ts) (gated by `USER_TYPE === 'ant'`, GrowthBook `tengu_basalt_3kr`, or `CLAUDE_CODE_MCP_INSTR_DELTA`): instead of rebuilding a `DANGEROUS_uncachedSystemPromptSection` every turn, `mcp_instructions_delta` appends `## <server>\n<instructions>` blocks (plus client-side blocks like Chrome instructions) only when servers connect or disconnect.

#### 4. `ToolSearchTool` Query Parsing, Ranking, and Pending-Server Hints

When the model invokes `ToolSearch` ([tools/ToolSearchTool/ToolSearchTool.ts](../../tools/ToolSearchTool/ToolSearchTool.ts), `isConcurrencySafe: true`, `isReadOnly: true`), `call()` handles three query paths:

1. **Direct selection (`select:A,B,C`, lines 363-406):** Splits comma-separated names, searching `deferredTools` first and falling back to already-loaded `tools` (selecting an already-loaded tool is a harmless no-op that avoids model retry churn).
2. **Fast paths (`lines 199-216`):** An exact bare tool name (common from subagents or post-compaction) returns immediately; a query starting with `mcp__` performs prefix matching up to `max_results` (default `5`).
3. **Weighted keyword search (`lines 218-302`):** Splits terms into `+required` (pre-filtered so *all* required terms must match name parts, `searchHint`, or description) and optional terms, pre-compiles `\b<term>\b` regexes once per query, splits tool names (`mcp__server__action` on `__`/`_`; built-ins on CamelCase/`_`), and scores each candidate:

```ts
// tools/ToolSearchTool/ToolSearchTool.ts:266-291 (abridged)
let score = 0
for (const term of allScoringTerms) {
  const pattern = termPatterns.get(term)!
  if (parsed.parts.includes(term)) {
    score += parsed.isMcp ? 12 : 10       // exact name part match
  } else if (parsed.parts.some(part => part.includes(term))) {
    score += parsed.isMcp ? 6 : 5         // partial name part match
  }
  if (parsed.full.includes(term) && score === 0) {
    score += 3                            // full-name substring fallback
  }
  if (hintNormalized && pattern.test(hintNormalized)) {
    score += 4                            // _meta['anthropic/searchHint']
  }
  if (pattern.test(descNormalized)) {
    score += 2                            // memoized tool.prompt() match
  }
}
```

`mapToolResultToToolResultBlockParam()` (`ToolSearchTool.ts:444-470`) returns `{ type: 'tool_reference', tool_name }` blocks for every match—causing the Anthropic API to expand their full JSON schemas into the model's context on the very next turn. On zero matches, `ToolSearchTool` checks `getAppState().mcp.clients` for `type === 'pending'` servers and appends `"Some MCP servers are still connecting: ..."` so the model knows to retry rather than giving up.

### Hidden Invariants & Failure Modes

- **Mid-conversation model switch sanitization (`claude.ts:1283-1296`).** If the user switches from Sonnet/Opus to Haiku mid-session, `useToolSearch` flips to `false`; `claude.ts` strips `tool_reference` blocks from prior user messages and `caller` fields from assistant `tool_use` blocks so Haiku does not reject the history with HTTP 400.
- **Pending-server latch (`claude.ts:1139-1148`).** Even when `deferredToolNames.size === 0`, `claude.ts` keeps `ToolSearch` enabled if `options.hasPendingMcpServers` is true—preventing turn 1 from stripping `ToolSearch` right before a slow MCP server finishes handshaking.
- **Undeferral is silent (`utils/toolSearch.ts:671-675`).** If a previously deferred tool transitions to non-deferred while remaining in the pool, `getDeferredToolsDelta()` deliberately omits it from `removedNames` so the model is never told a callable tool vanished.
- **Description cache invalidation (`ToolSearchTool.ts:55-100`).** `getToolDescriptionMemoized` caches `tool.prompt()` per tool name and wipes itself whenever the sorted CSV of deferred tool names changes.

---

## Putting the Layer Together

```mermaid
flowchart TD
    Cfg["config.ts: 7 Scopes + Enterprise Policy + Signature Dedup"] --> Mgr["useManageMCPConnections.ts: 2-Phase Connect + 16ms Batch"]
    Mgr --> Trans["client.ts: 8 Transports (stdio, HTTP, SSE, WS, InProcess, SDK, claude.ai)"]
    Trans <--> Auth["auth.ts: ClaudeAuthProvider (PKCE, CIMD, Lockfile Refresh, 403 Step-Up, XAA)"]
    Trans <--> Elicit["elicitationHandler.ts: Form/URL + Hooks + -32042 Retry"]
    Trans --> Adapt["fetchToolsForClient(): MCPTool + mcp__server__tool + 2048c Cap"]
    Adapt --> State["AppState.mcp (clients, tools, commands, resources)"]
    State --> Pool["tools.ts: assembleToolPool() [sortedBuiltIns | sortedMcp]"]
    Pool --> Gate["utils/toolSearch.ts: isDeferredTool() + extractDiscoveredToolNames()"]
    Gate --> Wire["services/api/claude.ts: non-deferred + ToolSearch + discovered(defer_loading:true)"]
    State --> Delta["utils/attachments.ts: deferred_tools_delta + mcp_instructions_delta"]
    Delta --> Wire
```

At the prompt-cache boundary, every mechanism in this chapter aligns to keep the prefix byte-frozen:

```text
+--------------------------------------------------------------------------+
| [Global Cache Prefix]  Static System Prompt + Sorted Built-in Tools      |
|                        (MCP tools excluded or marked defer_loading:true) |
+--------------------------------------------------------------------------+
| [Turn History...]      User msgs + <system-reminder> deferred_tools_delta|
|                        + <system-reminder> mcp_instructions_delta        |
|                        + ToolSearch tool_result [tool_reference blocks]  |
+--------------------------------------------------------------------------+
  ^ Late MCP connect appends a tail delta  -> 0% prefix cache invalidation
  ^ ToolSearch discovers mcp__slack__post  -> defer_loading:true stays out
                                              of top tool prefix
```

---

## How This Snaps Into the Next Layer

MCP is only the first dynamic capability in Layer 5; [Chapter 16](16-skills-plugins-output-styles-and-lsp.md) builds three sibling extension systems directly on top of the seams we just exposed:

- **Plugins bundling MCP servers:** [utils/plugins/mcpPluginIntegration.ts](../../utils/plugins/mcpPluginIntegration.ts) (`getPluginMcpServers()`, `loadPluginMcpServers()`) parses plugin `.mcp.json`, inline manifests, and `.mcpb` bundles, resolves `${CLAUDE_PLUGIN_ROOT}` and `${user_config.X}` variables, namespaces servers as `plugin:<plugin>:<server>` (`scope: 'dynamic'`), and feeds them directly into `services/mcp/config.ts:1147-1154`.
- **Zero-restart hot reload:** Running `/reload-plugins` calls `refreshActivePlugins()` ([utils/plugins/refresh.ts:72-136](../../utils/plugins/refresh.ts)), which clears plugin caches and increments `AppState.mcp.pluginReconnectKey`. That single counter re-fires `useManageMCPConnections.ts` to run `excludeStalePluginClients()`, tear down removed or edited plugin MCP servers cleanly, and connect newly enabled ones in the background.
- **Shared deferral & discovery hooks:** `LSPTool` ([tools.ts:224](../../tools.ts), gated by `ENABLE_LSP_TOOL`) plugs directly into `shouldDeferLspTool()` in [services/api/claude.ts:783](../../services/api/claude.ts) using the exact same `defer_loading: true` and `ToolSearch` machinery, while MCP `resources/list_changed` notifications already coordinate with `fetchMcpSkillsForClient` (`feature('MCP_SKILLS')`) and `clearSkillIndexCache` (`feature('EXPERIMENTAL_SKILL_SEARCH')`).

---

## Reading Exercises & Code Checkpoints

1. **Trace a permission rule collision in no-prefix SDK mode.**
   Run `rg -n "getToolNameForPermissionCheck|CLAUDE_AGENT_SDK_MCP_NO_PREFIX" services/mcp/ utils/permissions/` and trace what happens when an SDK MCP server named `custom` exposes a tool named `Write` while the user has a deny rule `Write` vs. `mcp__custom`. Why does `tools.ts:filterToolsByDenyRules()` automatically stay consistent with runtime permission checks?
2. **Verify every MCP cache-invalidation site.**
   Run `rg -n "fetchToolsForClient\.cache|connectToServer\.cache|clearKeychainCache" services/mcp/` and map each call site to the failure mode it prevents (broken stream, manual reconnect, cross-process OAuth refresh, `tools/list_changed`).
3. **Inspect all `defer_loading` and `tool_reference` escape hatches.**
   Run `rg -n "CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS|defer_loading|preCompactDiscoveredTools" utils/ services/api/ services/compact/` and verify how a tool discovered on turn 2 remains callable after turn 15 compaction *and* how the wire payload degrades safely if the user switches to Haiku or sets `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1`.
4. **Compare `deferred_tools_delta` vs. `mcp_instructions_delta` vs. `agent_listing_delta`.**
   Read [utils/toolSearch.ts:646-706](../../utils/toolSearch.ts), [utils/mcpInstructionsDelta.ts:55-130](../../utils/mcpInstructionsDelta.ts), and [utils/attachments.ts:1455-1510](../../utils/attachments.ts). Notice why all three use stateless history scanning over persisted attachment messages instead of an in-memory `Set`—what breaks on `/resume`, compaction, or subagent forks if you used a module-level `Set` instead?


---

<!-- chapters/16-skills-plugins-output-styles-and-lsp.md — https://reverseengineeringclaudecode.com/chapters/16-skills-plugins-output-styles-and-lsp -->

# Chapter 16 — Skills, Plugins, Output Styles, and LSP Intelligence

> **Layer:** Layer 5 (Dynamic Capabilities: MCP, Skills, Plugins & LSP)
> **Prerequisites:** [Chapter 03](03-command-and-message-contracts.md), [Chapter 04](04-prompt-engineering-and-cache-boundaries.md), [Chapter 13](13-the-hook-system.md), [Chapter 14](14-configuration-settings-and-enterprise-policy.md), [Chapter 15](15-model-context-protocol-mcp.md)
> **Primary Source Files:**
> - [skills/loadSkillsDir.ts](../../skills/loadSkillsDir.ts) — Multi-source Markdown skill discovery, `realpath` deduplication, dynamic & `paths`-scoped conditional activation
> - [skills/bundledSkills.ts](../../skills/bundledSkills.ts) — Programmatic bundled-skill registry and symlink-safe lazy file extraction
> - [tools/SkillTool/SkillTool.ts](../../tools/SkillTool/SkillTool.ts) & [tools/SkillTool/prompt.ts](../../tools/SkillTool/prompt.ts) — Skill execution (inline vs. forked subagent), `SAFE_SKILL_PROPERTIES` allowlist, and 1% listing budget
> - [utils/skills/skillChangeDetector.ts](../../utils/skills/skillChangeDetector.ts) — Debounced chokidar skill watching with Bun deadlock workaround
> - [plugins/builtinPlugins.ts](../../plugins/builtinPlugins.ts) & [utils/plugins/pluginLoader.ts](../../utils/plugins/pluginLoader.ts) — Built-in, `--plugin-dir`, and marketplace plugin loading, policy fail-closed guards, and cache-only startup
> - [utils/plugins/reconciler.ts](../../utils/plugins/reconciler.ts), [utils/plugins/refresh.ts](../../utils/plugins/refresh.ts), & [commands/reload-plugins/reload-plugins.ts](../../commands/reload-plugins/reload-plugins.ts) — Three-layer plugin materialization and live `/reload-plugins` hot-swapping
> - [outputStyles/loadOutputStylesDir.ts](../../outputStyles/loadOutputStylesDir.ts), [constants/outputStyles.ts](../../constants/outputStyles.ts), & [constants/prompts.ts](../../constants/prompts.ts) — Output style loading, plugin takeover (`force-for-plugin`), and system-prompt framing surgery
> - [services/lsp/manager.ts](../../services/lsp/manager.ts), [services/lsp/LSPServerManager.ts](../../services/lsp/LSPServerManager.ts), [services/lsp/LSPServerInstance.ts](../../services/lsp/LSPServerInstance.ts), [services/lsp/LSPClient.ts](../../services/lsp/LSPClient.ts), [services/lsp/passiveFeedback.ts](../../services/lsp/passiveFeedback.ts), [services/lsp/LSPDiagnosticRegistry.ts](../../services/lsp/LSPDiagnosticRegistry.ts), & [tools/LSPTool/LSPTool.ts](../../tools/LSPTool/LSPTool.ts) — Lazy LSP lifecycle, JSON-RPC resilience, active code-intelligence queries, and passive diagnostic attachments

## Why This Layer Exists

Chapter 15 gave the harness external RPC tools over MCP, solving how an agent reaches third-party APIs and databases. Yet an agent working in a real engineering organization still hits four walls that external tool schemas alone cannot solve:

1. **Reusable workflows without prompt bloat.** Putting every deploy playbook, PR review rubric, and migration checklist in `CLAUDE.md` burns context on every session and offers zero permission scoping, argument substitution, or subagent isolation. The harness needs *skills*—lazy-loaded Markdown playbooks that advertise a one-line description up front and expand only when invoked (or only after the agent touches matching files).
2. **Coordinated distribution and live reload.** Real capabilities rarely consist of a single prompt or a single MCP server. A team's "frontend toolkit" bundles skills, custom subagents, lifecycle hooks, an output style, an MCP server, and a language server. Users need to install, version, trust-check, and hot-swap that entire bundle via `/reload-plugins` without tearing down a running REPL.
3. **Behavioral reframing without forking prompts.** Sometimes the harness should teach (`Learning`), explain architectural trade-offs (`Explanatory`), or act as a non-coding domain specialist—which requires selectively stripping the software-engineering task instructions while preserving the prompt-cache boundary from Chapter 04.
4. **Compiler-grade code intelligence.** `GrepTool` and `GlobTool` match text; they cannot resolve overloaded symbols, walk call hierarchies, or report type errors right after an edit. The harness needs language servers managed lazily in the background, queried explicitly through `LSPTool` and harvested passively through compiler diagnostics.

This chapter dissects all four subsystems in dependency order: skills first, then the plugin container that packages skills alongside hooks/agents/MCP/LSP, then output styles, and finally the LSP engine.

---

## 1. Skills: Markdown Playbooks, Path-Scoped Triggers, and Inline vs. Forked Execution

### The Problem

A skill in Claude Code is represented as a `PromptCommand` ([Chapter 03](03-command-and-message-contracts.md))—unifying `/slash` commands invoked by a human and skills invoked proactively by the model through `SkillTool`. Making that abstraction survive real repositories forces the loader to solve five thorny problems simultaneously:

- **Discovery sprawl & symlink aliasing:** Skills arrive from enterprise policy directories, `~/.claude/skills`, every ancestor `.claude/skills` up to `$HOME`, `--add-dir` paths, legacy `.claude/commands` trees, compiled-in bundled skills, plugins, and MCP servers—often symlinked across dotfiles repos or containers with broken inode reporting.
- **Turn-1 token budgets:** Power users accumulate hundreds of skills. Dumping full skill bodies—or even verbose descriptions—into the system prompt bloats turn-1 cache creation and breaks prompt caches whenever a new skill activates mid-session.
- **Execution isolation vs. main-turn injection:** Some skills ("review this diff in a clean window") want a dedicated subagent (`context: fork`); others ("adopt these conventions and keep editing") must inject instructions, extra `allowedTools`, a `model` override, or an `effort` override directly into the current turn.
- **Untrusted inputs:** Skills can execute inline shell snippets (`` !`cmd` ``) and extract reference files to disk, creating command-injection and symlink-race surfaces if remote or multi-user inputs aren't fenced off.

### The Real Implementation

#### Multi-Source Discovery, Precedence, and `realpath` Deduplication

[skills/loadSkillsDir.ts](../../skills/loadSkillsDir.ts) loads disk-based skills inside the memoized `getSkillDirCommands(cwd)` (lines 638–804). Unlike legacy `/commands/` (which accepts both single `.md` files and `SKILL.md` directories), modern `/skills/` directories strictly enforce `skill-name/SKILL.md` (`loadSkillsFromSkillsDir`, lines 407–480).

Five independent sources run in parallel via `Promise.all` (lines 679–714), then concatenate in strict first-wins precedence order:

1. **Managed policy skills** (`<managed>/.claude/skills`, skipped if `CLAUDE_CODE_DISABLE_POLICY_SKILLS` is truthy).
2. **User skills** (`~/.claude/skills`), if `userSettings` is enabled and not locked by org plugin-only policy (`isRestrictedToPluginOnly('skills')`).
3. **Project skills** (`getProjectDirsUpToHome('skills', cwd)`), walking upward from `cwd`.
4. **Additional directories** (`--add-dir`), each checked at `<dir>/.claude/skills`.
5. **Legacy `/commands/`** (`loadSkillsFromCommandsDir`, tagged `loadedFrom: 'commands_DEPRECATED'`).

In `--bare` mode (`isBareMode()`, lines 658–675), auto-discovery is skipped completely; only explicit `--add-dir` directories load, while `isRestrictedToPluginOnly('skills')` still applies so `--bare` can never be used as a policy bypass.

Deduplication (`getFileIdentity`, lines 118–124 and 728–763) intentionally resolves canonical paths via `fs/promises.realpath()` instead of comparing `(dev, ino)` pairs—a production scar explicitly citing GitHub issue `#13893`, because virtual/container/NFS filesystems report `inode 0` and ExFAT loses inode precision.

Frontmatter is normalized by `parseSkillFrontmatterFields()` (lines 185–265), supporting `description`, `when_to_use`, `allowed-tools`, `argument-hint`, `arguments`, `model`, `effort`, `hooks` (validated with `HooksSchema()`), `disable-model-invocation`, `user-invocable`, `context: fork`, `agent`, `shell`, and `paths`. When the skill executes, `createSkillCommand()` builds `getPromptForCommand()` with three substitutions and one hard security boundary:

```ts
// skills/loadSkillsDir.ts:344-399
async getPromptForCommand(args, toolUseContext) {
  let finalContent = baseDir
    ? `Base directory for this skill: ${baseDir}\n\n${markdownContent}`
    : markdownContent

  finalContent = substituteArguments(finalContent, args, true, argumentNames)

  if (baseDir) {
    const skillDir =
      process.platform === 'win32' ? baseDir.replace(/\\/g, '/') : baseDir
    finalContent = finalContent.replace(/\$\{CLAUDE_SKILL_DIR\}/g, skillDir)
  }

  finalContent = finalContent.replace(/\$\{CLAUDE_SESSION_ID\}/g, getSessionId())

  // Security: MCP skills are remote and untrusted — never execute inline
  // shell commands (!`…` / ```! … ```) from their markdown body.
  if (loadedFrom !== 'mcp') {
    finalContent = await executeShellCommandsInPrompt(
      finalContent,
      {
        ...toolUseContext,
        getAppState() {
          const appState = toolUseContext.getAppState()
          return {
            ...appState,
            toolPermissionContext: {
              ...appState.toolPermissionContext,
              alwaysAllowRules: {
                ...appState.toolPermissionContext.alwaysAllowRules,
                command: allowedTools,
              },
            },
          }
        },
      },
      `/${skillName}`,
      shell,
    )
  }

  return [{ type: 'text', text: finalContent }]
}
```

Notice how `skills/loadSkillsDir.ts:1083-1086` also registers `createSkillCommand` and `parseSkillFrontmatterFields` into a zero-import leaf module, [skills/mcpSkillBuilders.ts](../../skills/mcpSkillBuilders.ts). That indirection breaks an import cycle (`client.ts → mcpSkills.ts → loadSkillsDir.ts → … → client.ts`) without using a variable dynamic `import(specifier)`, which fails at runtime inside Bun-bundled `$bunfs` single-file executables.

#### Bundled Skills and Symlink-Safe Lazy Extraction

Skills compiled directly into the CLI binary register at startup via `initBundledSkills()` ([skills/bundled/index.ts](../../skills/bundled/index.ts)) calling `registerBundledSkill()` ([skills/bundledSkills.ts](../../skills/bundledSkills.ts)). Core bundled skills (`update-config`, `keybindings`, `verify`, `debug`, `simplify`, `batch`, `remember`, `skillify`, `stuck`, `loremIpsum`) register unconditionally, while experimental or product-specific skills are dead-code-eliminated behind build-time `feature('...')` gates (`KAIROS` / `KAIROS_DREAM`, `REVIEW_ARTIFACT`, `AGENT_TRIGGERS` for `/loop`, `AGENT_TRIGGERS_REMOTE`, `BUILDING_CLAUDE_APPS`, `RUN_SKILL_GENERATOR`).

Bundled skills can embed companion reference files (`files?: Record<string, string>`). Rather than stuffing large docs into the prompt, `registerBundledSkill()` extracts them lazily on first invocation (memoizing the *promise* so concurrent callers share one write) into a per-process nonce directory (`getBundledSkillsRoot()`) and prepends `Base directory for this skill: <dir>` so the model can `Read`/`Grep` them on demand. The write path (`bundledSkills.ts:169-206`) is hardened against local `/tmp` symlink attacks: directories are created `0o700`, files open with `0o600` and `O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW` on POSIX (using string `'wx'` on Windows because numeric `O_EXCL` triggers `EINVAL` through libuv), and `EEXIST` intentionally fails rather than calling `unlink()`+retry because `unlink()` follows intermediate symlinks.

#### Dynamic Discovery & `paths`-Scoped Conditional Activation

Skills are not static for the lifetime of a session. Two dynamic mechanisms live at the bottom of [skills/loadSkillsDir.ts](../../skills/loadSkillsDir.ts) and are triggered whenever the agent operates on a file in [tools/FileReadTool/FileReadTool.ts](../../tools/FileReadTool/FileReadTool.ts) (lines 579–590), [tools/FileEditTool/FileEditTool.ts](../../tools/FileEditTool/FileEditTool.ts) (lines 408–422), or [tools/FileWriteTool/FileWriteTool.ts](../../tools/FileWriteTool/FileWriteTool.ts) (lines 234–245):

1. **Nested subdirectory discovery (`discoverSkillDirsForPaths` + `addSkillDirectories`, lines 861–975):** Walks up from `dirname(filePath)` strictly below `cwd` (checking `currentDir.startsWith(resolvedCwd + pathSep)` so `/project-backup` never false-matches `/project`). Both hits and misses are memoized in `dynamicSkillDirs` to avoid repeated `stat()` syscalls on every file read. Before loading a discovered `.claude/skills`, `isPathGitignored(currentDir, resolvedCwd)` blocks untrusted vendored trees such as `node_modules/pkg/.claude/skills`. Newly discovered directories are sorted deepest-first and merged shallower-to-deeper so skills closest to the touched file win.
2. **Conditional `paths` glob activation (`parseSkillPaths` + `activateConditionalSkillsForPaths`, lines 159–178 and 997–1058):** At initial load (`lines 771-790`), any skill with a non-empty `paths:` frontmatter (stripping trailing `/**`, and ignoring match-all `**`) is withheld from the unconditional list and parked in the `conditionalSkills` map. When the agent reads, writes, or edits a matching file, `activateConditionalSkillsForPaths()` evaluates the patterns with the `ignore` library (matching `CLAUDE.md` rule semantics):

```ts
// skills/loadSkillsDir.ts:1007-1041
for (const [name, skill] of conditionalSkills) {
  if (skill.type !== 'prompt' || !skill.paths || skill.paths.length === 0) {
    continue
  }

  const skillIgnore = ignore().add(skill.paths)
  for (const filePath of filePaths) {
    const relativePath = isAbsolute(filePath) ? relative(cwd, filePath) : filePath

    // ignore() throws on empty strings, paths escaping the base (../),
    // and absolute paths (Windows cross-drive relative() returns absolute).
    if (!relativePath || relativePath.startsWith('..') || isAbsolute(relativePath)) {
      continue
    }

    if (skillIgnore.ignores(relativePath)) {
      dynamicSkills.set(name, skill)
      conditionalSkills.delete(name)
      activatedConditionalSkillNames.add(name)
      activated.push(name)
      break
    }
  }
}
```

Recording the skill in `activatedConditionalSkillNames` ensures that once triggered, it survives cache invalidations during the same session. Both dynamic paths emit `skillsLoaded.emit()`, which [utils/skills/skillChangeDetector.ts](../../utils/skills/skillChangeDetector.ts) (lines 92–100) handles by calling `clearCommandMemoizationCaches()`—deliberately *not* `clearCommandsCache()`, because `clearCommandsCache()` calls `clearSkillCaches()` and would wipe the very dynamic skills just loaded.

#### Incremental Skill Listing & The 1% Context Budget

How does the model learn about skills without mutating the static system prompt and busting prompt caches every time a conditional skill activates? Through incremental `skill_listing` attachments in [utils/attachments.ts](../../utils/attachments.ts) (lines 2661–2751).

`getSkillListingAttachments()` collects `getSkillToolCommands(cwd)` plus MCP-provided skills (`getMcpSkillCommands`, gated by `feature('MCP_SKILLS')` in [commands.ts](../../commands.ts):547–559), diffs them against a per-agent `sentSkillNames` map, and emits *only the newly available delta*. On `--resume`, `conversationRecovery.ts` calls `suppressNextSkillListing()` so a restarted process doesn't re-inject the full ~600-token listing that is already in the restored transcript.

Formatting runs through `formatCommandsWithinBudget()` in [tools/SkillTool/prompt.ts](../../tools/SkillTool/prompt.ts) (lines 20–171):

- **Total budget:** `1%` of the model's context window in characters (`contextWindowTokens * 4 * 0.01`, fallback `8,000` chars, overridable via `SLASH_COMMAND_TOOL_CHAR_BUDGET`).
- **Per-entry cap:** `MAX_LISTING_DESC_CHARS = 250` so verbose `whenToUse` strings cannot waste turn-1 cache creation.
- **Bundled-skill protection:** If the full list exceeds budget, bundled skills (`source === 'bundled'`) are partitioned out and *never* truncated; remaining budget is divided evenly across user/project/plugin skills. If the per-skill share drops below `MIN_DESC_LENGTH = 20` characters, non-bundled skills degrade gracefully to names-only (`- skill-name`).

#### Inline Execution vs. Forked Subagent Execution

When the model calls `SkillTool` ([tools/SkillTool/SkillTool.ts](../../tools/SkillTool/SkillTool.ts)), permission evaluation (`checkPermissions`, lines 432–578) runs in strict order: `deny` rules → (remote canonical auto-grant, ant-only) → `allow` rules → `skillHasOnlySafeProperties()` → default `ask`.

> [!IMPORTANT]
> **`SAFE_SKILL_PROPERTIES` is a fail-closed allowlist (`SkillTool.ts:875-933`).** Skills that only declare benign metadata (`description`, `model`, `effort`, `paths`, `context`, `agent`, etc.) auto-allow without prompting. Notice what is deliberately *absent* from the allowlist: `allowedTools` and `hooks` (plus any future `PromptCommand` field not yet reviewed). Any skill granting extra tool permissions or registering lifecycle hooks forces an explicit user prompt.

After approval, `call()` branches on `command.context === 'fork'`:

1. **Inline execution (default, lines 634–840):** Calls `processPromptSlashCommand()` ([utils/processUserInput/processSlashCommand.tsx](../../utils/processUserInput/processSlashCommand.tsx):827–885), which registers any skill-scoped hooks via `registerSkillHooks()`, records the rendered body via `addInvokedSkill()` (so compaction in [Chapter 09](09-five-layer-compaction-pipeline.md) can re-inject active skills), and returns expanded user messages. `SkillTool` returns a brief tool result (`"Launching skill: <name>"`), attaches the expanded prompt as `newMessages` (tagged with `sourceToolUseID`), and returns a `contextModifier` that mutates the *subsequent* turn's execution context:

```ts
// tools/SkillTool/SkillTool.ts:767-839 (condensed)
return {
  data: { success: true, commandName, allowedTools: allowedTools.length > 0 ? allowedTools : undefined, model },
  newMessages,
  contextModifier(ctx) {
    let modifiedContext = ctx
    if (allowedTools.length > 0) {
      const previousGetAppState = modifiedContext.getAppState
      modifiedContext = {
        ...modifiedContext,
        getAppState() {
          const appState = previousGetAppState()
          return {
            ...appState,
            toolPermissionContext: {
              ...appState.toolPermissionContext,
              alwaysAllowRules: {
                ...appState.toolPermissionContext.alwaysAllowRules,
                command: [...new Set([...(appState.toolPermissionContext.alwaysAllowRules.command || []), ...allowedTools])],
              },
            },
          }
        },
      }
    }
    // Carry [1m] suffix over — otherwise a skill with `model: opus` on an
    // opus[1m] session drops the effective window to 200K and trips autocompact.
    if (model) {
      modifiedContext = {
        ...modifiedContext,
        options: {
          ...modifiedContext.options,
          mainLoopModel: resolveSkillModelOverride(model, ctx.options.mainLoopModel),
        },
      }
    }
    if (effort !== undefined) {
      const previousGetAppState = modifiedContext.getAppState
      modifiedContext = {
        ...modifiedContext,
        getAppState() { return { ...previousGetAppState(), effortValue: effort } },
      }
    }
    return modifiedContext
  },
}
```

2. **Forked subagent execution (`executeForkedSkill`, lines 122–289):** Calls `prepareForkedCommandContext()` ([utils/forkedAgent.ts](../../utils/forkedAgent.ts):191–232) to expand the prompt, wrap `allowedTools` via `createGetAppStateWithAllowedTools()`, and resolve `command.agent ?? 'general-purpose'`. It then runs `runAgent({ isAsync: false, querySource: 'agent:custom', override: { agentId } })` synchronously inside the tool call, forwards intermediate `tool_use`/`tool_result` blocks as `skill_progress` updates, extracts the final assistant text with `extractResultText()`, zeros `agentMessages.length = 0` to release memory, and clears `clearInvokedSkillsForAgent(agentId)` in `finally`. The main conversation receives only the synthesized summary string—keeping the parent context window clean.

### Hidden Invariants & Failure Modes

- **Bun `fs.watch()` deadlock (`utils/skills/skillChangeDetector.ts:51-62`):** Live-reloading edited skills via chokidar sets `USE_POLLING = typeof Bun !== 'undefined'` with a 2-second stat interval (`POLLING_INTERVAL_MS = 2000`) and a 300ms batch debounce (`RELOAD_DEBOUNCE_MS = 300`). Under Bun, native `FSWatcher` churn across deep skill trees triggers a `PathWatcherManager` `__ulock_wait2` deadlock (`oven-sh/bun#27469`, `#26385`). Debouncing also collapses mass git-checkout edits into a single `ConfigChange` hook invocation (`paths[0]`) and cache sweep.
- **Preserving `[1m]` model windows:** Calling `resolveSkillModelOverride()` instead of directly assigning `command.model` stops a skill authored with `model: opus` from silently downgrading an `opus[1m]` session to 200K tokens and triggering an immediate autocompact.
- **Snapshot absence (`services/skillSearch/`):** Behind `feature('EXPERIMENTAL_SKILL_SEARCH')`, five call sites ([tools/SkillTool/SkillTool.ts](../../tools/SkillTool/SkillTool.ts):108–115, [utils/attachments.ts](../../utils/attachments.ts):95–101, [commands.ts](../../commands.ts):96–100, [query.ts](../../query.ts):67, and [constants/prompts.ts](../../constants/prompts.ts):95–96) conditionally `require()` modules under `services/skillSearch/` (`featureCheck`, `prefetch`, `localSearch`, `remoteSkillState`, `remoteSkillLoader`, `telemetry`, `signals`). **This entire directory is absent from the snapshot.** From the call sites we can observe its contract: when enabled, `getSkillListingAttachments()` shrinks the static listing to bundled+MCP skills (`filterToBundledAndMcp`, capped at 30) while dynamic discovery surfaces the long tail; `SkillTool` intercepts `_canonical_<slug>` names (additionally gated on `process.env.USER_TYPE === 'ant'`) to load remote declarative `SKILL.md` files directly without `!` shell expansion; and `clearCommandMemoizationCaches()` calls `clearSkillIndexCache()` to bust the outer search index cache.

---

## 2. Plugins: Packaging, Trust Boundaries, Caching, and `/reload-plugins` Hot-Swapping

### The Problem

Once teams want to ship a cohesive package—say, a Kubernetes plugin with three skills, a specialized `k8s-debugger` subagent, a `PreToolUse` safety hook, an MCP server, and a YAML language server—standalone `.claude/` directories break down. You need versioning, marketplaces, dependency checks, enterprise allowlists/blocklists, fast startup that never stalls on `git clone`, and a way to apply newly installed or edited plugins without restarting the terminal session.

### The Real Implementation

#### The Three-Layer Plugin Architecture

As documented at the top of [utils/plugins/refresh.ts](../../utils/plugins/refresh.ts) (lines 4–7), the plugin subsystem separates *desired state*, *disk materialization*, and *in-memory activation* into three explicit layers:

- **Layer 1 — Intent (Settings):** `enabledPlugins`, `extraKnownMarketplaces`, and enterprise `policySettings` (`strictKnownMarketplaces`, `blockedMarketplaces`, force-enabled/disabled plugins) merged via Chapter 14's settings cascade.
- **Layer 2 — Materialization (`~/.claude/plugins/`):** [utils/plugins/reconciler.ts](../../utils/plugins/reconciler.ts) diffs declared marketplace intent against `known_marketplaces.json` (`diffMarketplaces`, lines 50–83) and runs `reconcileMarketplaces()` (lines 114–234)—idempotent and strictly additive (never deletes). Relative local marketplace paths are normalized against `findCanonicalGitRoot()` (lines 237–250) so git worktree sessions don't overwrite the user-global `known_marketplaces.json` with ephemeral worktree paths that break once the worktree is deleted.
- **Layer 3 — Active Components (`AppState` + `STATE.registeredHooks`):** Loaded by `loadAllPlugins()` / `loadAllPluginsCacheOnly()` ([utils/plugins/pluginLoader.ts](../../utils/plugins/pluginLoader.ts)) and swapped live by `refreshActivePlugins()` ([utils/plugins/refresh.ts](../../utils/plugins/refresh.ts)).

#### Manifest Anatomy, Sources, and Component Wiring

A plugin root optionally contains `.claude-plugin/plugin.json` validated against `PluginManifestSchema` ([utils/plugins/schemas.ts](../../utils/plugins/schemas.ts)); if absent, `loadPluginManifest()` synthesizes a minimal manifest from the directory name (`pluginLoader.ts:1147-1160`). `createPluginFromPath()` (`pluginLoader.ts:1348-1770`) probes standard directories in parallel (`commands/`, `skills/`, `agents/`, `output-styles/`, `hooks/hooks.json`, `settings.json`) and merges explicit manifest overrides:

| Component | Default Location / Manifest Field | Loader & Namespacing |
|---|---|---|
| Commands & Skills | `commands/`, `skills/`, `manifest.{commands,skills}` | [loadPluginCommands.ts](../../utils/plugins/loadPluginCommands.ts) — `pluginName[:sub]:cmdName` |
| Subagents | `agents/`, `manifest.agents` | [loadPluginAgents.ts](../../utils/plugins/loadPluginAgents.ts) — `agentType = pluginName[:sub]:agentName` |
| Hooks | `hooks/hooks.json`, `manifest.hooks` | [loadPluginHooks.ts](../../utils/plugins/loadPluginHooks.ts) — deduped by `realpath()`, registered in `STATE.registeredHooks` |
| Output Styles | `output-styles/`, `manifest.outputStyles` | [loadPluginOutputStyles.ts](../../utils/plugins/loadPluginOutputStyles.ts) — `${pluginName}:${baseStyleName}` |
| MCP Servers | `.mcp.json`, `manifest.mcpServers` (JSON, inline, or `.mcpb`/`.dxt`) | [mcpPluginIntegration.ts](../../utils/plugins/mcpPluginIntegration.ts) — supports `manifest.channels` + MCPB config dialogs |
| LSP Servers | `.lsp.json`, `manifest.lspServers` | [lspPluginIntegration.ts](../../utils/plugins/lspPluginIntegration.ts) — scoped as `plugin:${pluginName}:${serverName}` |
| Settings | `settings.json`, `manifest.settings` | [pluginLoader.ts](../../utils/plugins/pluginLoader.ts):1776–1849 — allowlist-filtered via `SettingsSchema().pick({ agent: true }).strip()` |

Plugins also support templated variables: `${CLAUDE_PLUGIN_ROOT}`, `${CLAUDE_PLUGIN_DATA}`, and `${user_config.KEY}` declared in `manifest.userConfig` ([schemas.ts](../../utils/plugins/schemas.ts):632–654). Option keys must match `/^[A-Za-z_]\w*$/` because they also export as `CLAUDE_PLUGIN_OPTION_<KEY>` env vars to hooks. Non-sensitive values persist in `settings.json`; `sensitive: true` values live in secure storage (macOS keychain or `.credentials.json`, explicitly warning plugin authors to keep secret counts small because they share the ~2 KB keychain entry with OAuth tokens — `INC-3028`) and are *excluded* from skill and agent Markdown substitution so secrets do not leak into LLM prompts.

Three plugin sources merge in `mergePluginSources()` (`pluginLoader.ts:3009-3064`):

1. **Session plugins (`--plugin-dir` / SDK inline):** Override installed marketplace plugins with the same name so authors can iterate locally—*unless* that plugin name is locked by enterprise `policySettings.enabledPlugins` (whether force-enabled *or* force-disabled), in which case the `--plugin-dir` copy is dropped with a visible error.
2. **Marketplace plugins (`name@marketplace`):** Installed from git, GitHub, URL, npm, or local directory marketplaces.
3. **Built-in plugins (`name@builtin`, [plugins/builtinPlugins.ts](../../plugins/builtinPlugins.ts)):** Compiled into the CLI, toggleable in `/plugin`, and intentionally tagging their skills with `source: 'bundled'` rather than `'builtin'` (lines 145–150) because `Command.source === 'builtin'` means hardcoded CLI commands (`/help`, `/clear`) and would drop them from `SkillTool`'s listing and truncation exemption.

After merging, `verifyAndDemote()` ([utils/plugins/dependencyResolver.ts](../../utils/plugins/dependencyResolver.ts)) performs an `apt`-style fixed-point presence check (no topological load order needed), demoting plugins with unsatisfied dependencies session-locally without rewriting user settings. Cross-marketplace dependencies are blocked by default unless explicitly permitted on the *root* marketplace's `allowCrossMarketplaceDependenciesOn` list (no transitive trust).

#### Trust Boundaries, Caching, and the Startup Split

Because marketplace plugins execute hooks, MCP servers, and LSP binaries, the loader enforces multiple defense-in-depth gates:

- **Official-name & homograph defense ([utils/plugins/schemas.ts](../../utils/plugins/schemas.ts):19–157):** `ALLOWED_OFFICIAL_MARKETPLACE_NAMES` reserves 8 official Anthropic marketplace names; `isBlockedOfficialName()` rejects non-ASCII characters (`NON_ASCII_PATTERN`, blocking Cyrillic lookalikes) and `BLOCKED_OFFICIAL_NAME_PATTERN` impersonations; `validateOfficialNameSource()` enforces that reserved names originate exclusively from `github.com/anthropics/`.
- **Enterprise policy fail-closed guard ([utils/plugins/pluginLoader.ts](../../utils/plugins/pluginLoader.ts):1920–1995):** If `strictKnownMarketplaces` (even `[]`, meaning deny-all) or non-empty `blockedMarketplaces` is active, and `loadKnownMarketplacesConfigSafe()` cannot resolve a plugin's marketplace (missing entry or corrupt JSON), the plugin is blocked with `marketplace-blocked-by-policy`. Without this guard, falling back to `getPluginByIdCacheOnly()` (which performs an unvalidated raw cast) would silently fail open. Similarly, `isPluginBlockedByPolicy()` ([utils/plugins/pluginPolicy.ts](../../utils/plugins/pluginPolicy.ts)) enforces org-disabled plugins across install, enable, and UI paths, while `detectAndUninstallDelistedPlugins()` ([utils/plugins/pluginBlocklist.ts](../../utils/plugins/pluginBlocklist.ts)) auto-uninstalls plugins removed from their marketplace catalog (noting the removal of remote `security.json` polling after `#25447` generated ~29.5M GitHub requests/week).
- **Versioned, seed, and ZIP caches:** Materialized plugins live at `~/.claude/plugins/cache/{marketplace}/{plugin}/{version}/` (stripping `.git` and sanitizing version segments against path traversal). Read-only container/BYOC environments can populate `probeSeedCache()` (`pluginLoader.ts:195-238`), and headless Filestore setups can enable `CLAUDE_CODE_PLUGIN_USE_ZIP_CACHE=1` + `CLAUDE_CODE_PLUGIN_CACHE_DIR` ([utils/plugins/zipCache.ts](../../utils/plugins/zipCache.ts)) to store plugins as `.zip` archives extracted into a session-local temp directory. Orphaned cache versions receive a `.orphaned_at` timestamp and are garbage-collected after 7 days (`cleanupOrphanedPluginVersionsInBackground`, [utils/plugins/cacheUtils.ts](../../utils/plugins/cacheUtils.ts):74–116)—skipped in ZIP mode so empty-dir pruning doesn't wipe `.zip` files.
- **Cache-only vs. full loading (`pluginLoader.ts:3096-3146`):** Interactive startup calls `loadAllPluginsCacheOnly()`, reading `installed_plugins.json` without ever blocking on network git clones; explicit refresh paths (and headless `CLAUDE_CODE_SYNC_PLUGIN_INSTALL=1`) call `loadAllPlugins()`. Crucially, `loadAllPlugins()` writes its resolved promise into `loadAllPluginsCacheOnly.cache` (line 3106) so downstream cache-only consumers immediately see newly cloned plugins.

#### Hot-Swapping Mid-Session: `/reload-plugins`

Running `/reload-plugins` ([commands/reload-plugins/reload-plugins.ts](../../commands/reload-plugins/reload-plugins.ts)) first re-downloads user settings if running in remote mode (`feature('DOWNLOAD_USER_SETTINGS')` + `CLAUDE_CODE_REMOTE`, manually firing `settingsChangeDetector.notifyChange('userSettings')` because internal writes suppress the watcher), then calls `refreshActivePlugins(context.setAppState)`:

```ts
// utils/plugins/refresh.ts:72-155 (condensed)
export async function refreshActivePlugins(
  setAppState: SetAppState,
): Promise<RefreshActivePluginsResult> {
  clearAllCaches()
  clearPluginCacheExclusions()

  // Sequence full load BEFORE cache-only consumers (#23693).
  // loadAllPlugins() warms loadAllPluginsCacheOnly's memoize cache.
  const pluginResult = await loadAllPlugins()
  const [pluginCommands, agentDefinitions] = await Promise.all([
    getPluginCommands(),
    getAgentDefinitionsWithOverrides(getOriginalCwd()),
  ])

  const { enabled, disabled, errors } = pluginResult

  // Eagerly warm lazy mcpServers / lspServers cache slots
  const [mcpCounts, lspCounts] = await Promise.all([
    Promise.all(enabled.map(async p => {
      if (p.mcpServers) return Object.keys(p.mcpServers).length
      const servers = await loadPluginMcpServers(p, errors)
      if (servers) p.mcpServers = servers
      return servers ? Object.keys(servers).length : 0
    })),
    Promise.all(enabled.map(async p => {
      if (p.lspServers) return Object.keys(p.lspServers).length
      const servers = await loadPluginLspServers(p, errors)
      if (servers) p.lspServers = servers
      return servers ? Object.keys(servers).length : 0
    })),
  ])

  setAppState(prev => ({
    ...prev,
    plugins: {
      ...prev.plugins,
      enabled, disabled,
      commands: pluginCommands,
      errors: mergePluginErrors(prev.plugins.errors, errors),
      needsRefresh: false,
    },
    agentDefinitions,
    mcp: { ...prev.mcp, pluginReconnectKey: prev.mcp.pluginReconnectKey + 1 },
  }))

  reinitializeLspServerManager() // Fixes #15521; clears stale LSP config too
  await loadPluginHooks()        // Atomic clear + register into STATE.registeredHooks
  // ...
}
```

Every single step in `refreshActivePlugins()` encodes a real production fix:

1. `clearAllCaches()` ([utils/plugins/cacheUtils.ts](../../utils/plugins/cacheUtils.ts):26–50) clears ten memoized caches across plugins, commands, agents, output styles, skill prompts, and `sentSkillNames`—leaving nothing stale.
2. Sequencing `await loadAllPlugins()` before `getPluginCommands()` and `getAgentDefinitionsWithOverrides()` fixed `#23693`: racing them in one `Promise.all` caused cache-only consumers to read `installed_plugins.json` before `loadAllPlugins()` finished cloning, emitting spurious `plugin-cache-miss` errors.
3. Incrementing `mcp.pluginReconnectKey` wakes `useManageMCPConnections` ([Chapter 15](15-model-context-protocol-mcp.md)) to connect newly enabled plugin MCP servers and tear down disabled ones.
4. `reinitializeLspServerManager()` runs unconditionally so both adding the first LSP plugin (fixing `#15521`) and removing the last LSP plugin take effect cleanly.
5. `loadPluginHooks()` ([utils/plugins/loadPluginHooks.ts](../../utils/plugins/loadPluginHooks.ts):91–157) performs `clearRegisteredPluginHooks()` and `registerHookCallbacks()` as an atomic pair. Previously, clearing hooks inside `clearPluginHookCache()` wiped `STATE.registeredHooks` during `/plugin` UI operations, silently killing plugin `Stop` hooks (`gh-29767`). Meanwhile, `clearAllPluginCaches()` fires `pruneRemovedPluginHooks()` (lines 179–207) so *uninstalled* plugins stop firing hooks immediately (`gh-36995`), re-reading `getRegisteredHooks()` *after* its `await` so it never clobbers a concurrent hot reload.

### Hidden Invariants & Failure Modes

- **Four-field policy hash for background hook reload (`loadPluginHooks.ts:217-287`):** `setupPluginHookHotReload()` subscribes to `policySettings` changes and hashes *four* fields—`enabledPlugins`, `extraKnownMarketplaces`, `strictKnownMarketplaces`, and `blockedMarketplaces`. Hashing only `enabledPlugins` previously skipped reloads when remote managed settings updated only marketplace allow/blocklists, leaving a poisoned memoize cache (`#23085`, `#23152`).
- **Startup settings cache short-circuit (`pluginLoader.ts:3281-3295`):** `cachePluginSettings()` only calls `resetSettingsCache()` when enabled plugins actually contribute allowlisted settings keys (`agent`); skipping the reset in the common empty case saves ~17ms of redundant settings re-parsing on startup.

---

## 3. Output Styles: Re-Framing the System Prompt Across the Cache Boundary

### The Problem

Skills govern *a task*; output styles govern *the agent's entire persona and pedagogical contract* across every turn of a session. Changing that framing naively—either by rewriting the whole system prompt or by dumping style text unconditionally at the top—either breaks Claude Code's carefully engineered tool-use/safety guardrails or shatters the cross-org global prompt cache ([Chapter 04](04-prompt-engineering-and-cache-boundaries.md)).

### The Real Implementation

Output styles are Markdown files with optional frontmatter (`name`, `description`, `keep-coding-instructions`, and—for plugins only—`force-for-plugin`) collected from five tiers in [constants/outputStyles.ts](../../constants/outputStyles.ts):

1. **Built-in styles** (`OUTPUT_STYLE_CONFIG`, lines 41–135): `default` (`null`), `Explanatory` (injects `Insight` callout boxes before/after coding), and `Learning` (pauses to insert `TODO(human)` markers and request 2–10 line user contributions on design decisions). Both built-in non-default styles explicitly set `keepCodingInstructions: true`.
2. **Plugin styles** ([utils/plugins/loadPluginOutputStyles.ts](../../utils/plugins/loadPluginOutputStyles.ts)): loaded from `output-styles/` or `manifest.outputStyles`, namespaced `${pluginName}:${baseStyleName}`.
3. **User, project, and managed styles** ([outputStyles/loadOutputStylesDir.ts](../../outputStyles/loadOutputStylesDir.ts)): loaded via `loadMarkdownFilesForSubdir('output-styles', cwd)` from `~/.claude/output-styles`, `.claude/output-styles`, and `<managed>/.claude/output-styles`.

When `getOutputStyleConfig()` (`constants/outputStyles.ts:181-211`) resolves the active style, any enabled plugin style with `forceForPlugin === true` wins unconditionally over `settings.outputStyle` (first forced style wins with a warning if multiple plugins compete).

The resolved `OutputStyleConfig | null` then performs three surgical edits inside `getSystemPrompt()` in [constants/prompts.ts](../../constants/prompts.ts):

```ts
// constants/prompts.ts:151-184, 505-576 (condensed)
function getOutputStyleSection(outputStyleConfig: OutputStyleConfig | null): string | null {
  if (outputStyleConfig === null) return null
  return `# Output Style: ${outputStyleConfig.name}\n${outputStyleConfig.prompt}`
}

function getSimpleIntroSection(outputStyleConfig: OutputStyleConfig | null): string {
  return `\nYou are an interactive agent that helps users ${
    outputStyleConfig !== null
      ? 'according to your "Output Style" below, which describes how you should respond to user queries.'
      : 'with software engineering tasks.'
  } Use the instructions below and the tools available to you to assist the user.\n...`
}

// Inside getSystemPrompt():
const dynamicSections = [
  // ...
  systemPromptSection('output_style', () => getOutputStyleSection(outputStyleConfig)),
  // ...
]

return [
  // --- Static content (cacheable) ---
  getSimpleIntroSection(outputStyleConfig),
  getSimpleSystemSection(),
  outputStyleConfig === null || outputStyleConfig.keepCodingInstructions === true
    ? getSimpleDoingTasksSection()
    : null,
  getActionsSection(),
  getUsingYourToolsSection(enabledTools),
  getSimpleToneAndStyleSection(),
  getOutputEfficiencySection(),
  // === BOUNDARY MARKER - DO NOT MOVE OR REMOVE ===
  ...(shouldUseGlobalCacheScope() ? [SYSTEM_PROMPT_DYNAMIC_BOUNDARY] : []),
  // --- Dynamic content (registry-managed) ---
  ...resolvedDynamicSections,
].filter(s => s !== null)
```

Look closely at how this preserves the architecture of Chapter 04:
- **Static prefix minimalism:** The custom style's arbitrary prompt text is placed *below* `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` inside a session-cached `systemPromptSection('output_style', ...)`. Above the boundary, only two coarse switches change: the one-sentence intro clause and the presence/absence of `getSimpleDoingTasksSection()`. Thus every user running any custom non-coding output style still shares the exact same static prefix cache key!
- **Coding-instructions gate:** Setting `keep-coding-instructions: false` (or omitting it on a custom style) drops `getSimpleDoingTasksSection()` entirely, letting an output style repurpose the harness for writing, research, or ops workflows without fighting software-engineering instructions, while retaining core tool, permission, and safety rules (`getSimpleSystemSection`, `getActionsSection`, `getUsingYourToolsSection`).

### Hidden Invariants & Failure Modes

- **Comment vs. code precedence inversion (`constants/outputStyles.ts:158-159`):** The inline comment claims lowest-to-highest priority is `built-in, plugin, managed, user, project`, but the actual array is `const styleGroups = [pluginStyles, userStyles, projectStyles, managedStyles]`. Because later entries overwrite earlier ones, `managedStyles` (`policySettings`) actually has the *highest* precedence—matching enterprise expectations in Chapter 14 even though the comment says otherwise.
- **Plugin styles always drop coding instructions:** [loadOutputStylesDir.ts](../../outputStyles/loadOutputStylesDir.ts) (lines 53–62) parses `keep-coding-instructions` and warns on `force-for-plugin`, whereas [loadPluginOutputStyles.ts](../../utils/plugins/loadPluginOutputStyles.ts) (lines 64–78) parses `force-for-plugin` but *never* reads `keep-coding-instructions`. Consequently, plugin-provided output styles always leave `keepCodingInstructions` `undefined`, omitting `getSimpleDoingTasksSection()`.

---

## 4. LSP Intelligence: Lazy Language Servers, `LSPTool`, and Passive Compiler Feedback

### The Problem

Running language servers (`typescript-language-server`, `pyright`, `gopls`, `rust-analyzer`) inside a CLI agent creates four operational hazards:

1. **Cold-start & memory tax:** Spawning heavy language servers eagerly at CLI startup ruins interactive startup latency and wastes gigabytes of RAM when the user never touches files of that language (or runs headless `claude -p`).
2. **Startup race with plugins:** Language servers in Claude Code come *exclusively* from plugins ([services/lsp/config.ts](../../services/lsp/config.ts):10–11). If LSP initializes before plugin marketplaces finish reconciling, it caches zero servers permanently unless explicitly reinitialized.
3. **Hostile real-world server quirks:** Servers crash mid-session, reject requests with JSON-RPC `-32801` (`ContentModified`) while indexing, send reverse `workspace/configuration` requests even when the client advertises `configuration: false`, and require deprecated `rootUri`/`rootPath` fields alongside `workspaceFolders`.
4. **Diagnostic spam:** Every keystroke or save triggers asynchronous `textDocument/publishDiagnostics` bursts across dozens of files. Injecting unfiltered diagnostics into every turn would flood the context window with repetitive warnings.

### The Real Implementation

#### Plugin-Only Configuration and Generation-Guarded Singleton Lifecycle

[services/lsp/config.ts](../../services/lsp/config.ts) loads LSP configurations solely from enabled plugins via `getPluginLspServers()` ([utils/plugins/lspPluginIntegration.ts](../../utils/plugins/lspPluginIntegration.ts)), reading `.lsp.json` and `manifest.lspServers`. Relative config file paths pass through `validatePathWithinPlugin()` to block `..` traversal; command, args, env, and `workspaceFolder` expand `${CLAUDE_PLUGIN_ROOT}`, `${CLAUDE_PLUGIN_DATA}`, `${user_config.KEY}`, and `${ENV_VAR}`; and server names are scoped as `plugin:${plugin.name}:${serverName}` so plugins cannot collide.

[services/lsp/manager.ts](../../services/lsp/manager.ts) wraps the singleton `LSPServerManager` behind a four-state lifecycle (`'not-started' | 'pending' | 'success' | 'failed'`) guarded by a monotonic `initializationGeneration` counter (lines 35, 173–207, 287). `initializeLspServerManager()` returns immediately in `--bare` mode, creates the manager synchronously, and starts async config loading without blocking startup. When `/reload-plugins` calls `reinitializeLspServerManager()` (lines 226–253), it fires a best-effort `shutdown()` on the old instance, bumps `initializationGeneration` so any in-flight startup promise from the prior generation silently drops its result, and kicks off a fresh config parse—fixing `#15521`.

#### Lazy Startup, Protocol Scars, and Crash Recovery

`LSPServerManager.initialize()` ([services/lsp/LSPServerManager.ts](../../services/lsp/LSPServerManager.ts):71–148) never spawns a child process. It only validates each server's `command` and `extensionToLanguage` map, builds a lowercase `extensionMap` (e.g., `.ts → ['plugin:typescript-lsp:tsserver']`), instantiates an idle `LSPServerInstance`, and pre-registers a reverse `workspace/configuration` handler returning `params.items.map(() => null)` so servers like TypeScript don't stall waiting for a reply.

Actual process spawning is deferred until `ensureServerStarted(filePath)` is called by `LSPTool` or a file edit. Inside [services/lsp/LSPServerInstance.ts](../../services/lsp/LSPServerInstance.ts) (lines 106–125):
- `LSPClient.js` is lazy-`require()`d inside `createLSPServerInstance()` so `vscode-jsonrpc` (~129 KB) stays off the cold-start import graph whenever no LSP plugins are configured.
- `createLSPClient(name, onCrash)` wires an `onCrash` callback that transitions `state = 'error'` and increments `crashRecoveryCount` on unexpected non-zero exits—avoiding a zombie `'running'` state where `ensureServerStarted` would never restart the server. Restart attempts cap at `config.maxRestarts ?? 3` (`lines 142-150`).
- Inside [services/lsp/LSPClient.ts](../../services/lsp/LSPClient.ts), `start()` explicitly awaits a `'spawn'` vs. `'error'` race (lines 115–131) *before* attaching `StreamMessageReader`/`StreamMessageWriter` so a missing binary (`ENOENT`) fails cleanly instead of causing unhandled stream-write rejections. Notification and request handlers registered while the server was still stopped queue in `pendingHandlers` / `pendingRequestHandlers` (lines 64–71) and attach immediately after `connection.listen()` (lines 228–244).
- `initialize()` sends `workspaceFolders` (LSP 3.16+, needed by Pyright and gopls), deprecated `rootPath` and `rootUri` (needed by `typescript-language-server` for `goToDefinition`), and `initializationOptions ?? {}` (needed by `vue-language-server`).
- `sendRequest()` transparently retries transient `-32801` (`ContentModified`) errors during initial project indexing:

```ts
// services/lsp/LSPServerInstance.ts:367-402 (condensed)
for (let attempt = 0; attempt <= MAX_RETRIES_FOR_TRANSIENT_ERRORS; attempt++) {
  try {
    return await client.sendRequest(method, params)
  } catch (error) {
    lastAttemptError = error as Error
    // Duck-type instead of instanceof: multiple vscode-jsonrpc versions
    // (8.2.0 vs 8.2.1) may coexist in the dependency tree.
    const errorCode = (error as { code?: number }).code
    const isContentModifiedError =
      typeof errorCode === 'number' && errorCode === LSP_ERROR_CONTENT_MODIFIED

    if (isContentModifiedError && attempt < MAX_RETRIES_FOR_TRANSIENT_ERRORS) {
      const delay = RETRY_BASE_DELAY_MS * Math.pow(2, attempt) // 500, 1000, 2000ms
      await sleep(delay)
      continue
    }
    break
  }
}
```

#### Active Queries: `LSPTool`

[tools/LSPTool/LSPTool.ts](../../tools/LSPTool/LSPTool.ts) exposes 9 read-only, concurrency-safe operations: `goToDefinition`, `findReferences`, `hover`, `documentSymbol`, `workspaceSymbol`, `goToImplementation`, `prepareCallHierarchy`, `incomingCalls`, and `outgoingCalls`. Key design properties:

- **Deferred & self-gating:** Declares `shouldDefer: true` (discovered on demand via `ToolSearchTool` from [Chapter 15](15-model-context-protocol-mcp.md)) and `isEnabled: () => isLspConnected()` (requiring at least one configured server not in `'error'` state).
- **1-based to 0-based translation:** Accepts editor-friendly 1-based `line`/`character` inputs and converts to 0-based LSP positions in `getMethodAndParams()` (lines 432–436).
- **Lazy `didOpen` & safety guards:** Before dispatching a request, `call()` waits if initialization is still `'pending'`, checks `manager.isFileOpen(absolutePath)`, and opens unopened files with a 10 MB ceiling (`MAX_LSP_FILE_SIZE_BYTES = 10_000_000`, lines 261–278). `validateInput()` skips `stat()` on UNC paths (`\\...` / `//...`, lines 170–173) to prevent Windows NTLM credential leaks.
- **Two-step call hierarchy & gitignore filtering:** `incomingCalls` and `outgoingCalls` automatically chain `textDocument/prepareCallHierarchy` into `callHierarchy/{incoming,outgoing}Calls` using `callItems[0]` (lines 302–334). Location-returning operations filter out gitignored hits via batched `git check-ignore` calls (50 paths per batch, lines 556–611).

#### Passive Compiler Feedback Loop

Even if the model never calls `LSPTool`, language servers act as a passive compiler oracle whenever the agent modifies code:

1. **Edit/Write sync:** Right after writing to disk, [tools/FileEditTool/FileEditTool.ts](../../tools/FileEditTool/FileEditTool.ts) (lines 494–514) and [tools/FileWriteTool/FileWriteTool.ts](../../tools/FileWriteTool/FileWriteTool.ts) (lines 309–326) fire `lspManager.changeFile()` (`textDocument/didChange`, auto-falling back to `didOpen` if not yet opened) and `lspManager.saveFile()` (`textDocument/didSave`—explicitly required to trigger diagnostics in TypeScript's language server).
2. **Notification capture:** Upon manager initialization, `registerLSPNotificationHandlers()` ([services/lsp/passiveFeedback.ts](../../services/lsp/passiveFeedback.ts):125–328) attaches a `textDocument/publishDiagnostics` listener to every server instance (queued via `pendingHandlers` until spawn). Each notification normalizes severity (`1→Error`, `2→Warning`, `3→Info`, `4→Hint`), drops empty diagnostic arrays, and stores the batch via `registerPendingLSPDiagnostic()`—tracking per-server consecutive handler failures and warning after 3+.
3. **Deduplication, severity sorting, and volume caps:** [services/lsp/LSPDiagnosticRegistry.ts](../../services/lsp/LSPDiagnosticRegistry.ts) buffers notifications in `pendingDiagnostics` and maintains a 500-file `LRUCache<string, Set<string>>` (`deliveredDiagnostics`) keyed by JSON-serialized `(message, severity, range, source, code)` for cross-turn deduplication. When `checkForLSPDiagnostics()` runs (lines 193–338), it deduplicates within-batch and against prior turns, sorts each file's diagnostics by severity (`Error` first), and enforces hard caps of `MAX_DIAGNOSTICS_PER_FILE = 10` and `MAX_TOTAL_DIAGNOSTICS = 30`.
4. **Attachment delivery:** On the next turn, `getLSPDiagnosticAttachments()` ([utils/attachments.ts](../../utils/attachments.ts):2885–2935)—gated on the agent possessing `BashTool` so read-only subagents aren't distracted by build errors they can't act on—drains `checkForLSPDiagnostics()`, emits `{ type: 'diagnostics', files, isNew: true }`, and clears `pendingDiagnostics`.

### Hidden Invariants & Failure Modes

- **Snapshot absence (`services/lsp/types.ts`):** `services/lsp/types.ts` is absent from this checkout. Its exported types—`LspServerConfig`, `ScopedLspServerConfig` (adds `scope: 'dynamic'` and `source: string`), and `LspServerState` (`'stopped' | 'starting' | 'running' | 'stopping' | 'error'`)—are observed directly across [utils/plugins/schemas.ts](../../utils/plugins/schemas.ts) (`LspServerConfigSchema`), [utils/plugins/lspPluginIntegration.ts](../../utils/plugins/lspPluginIntegration.ts), and [services/lsp/LSPServerInstance.ts](../../services/lsp/LSPServerInstance.ts).
- **Unimplemented config fields fail loudly:** `createLSPServerInstance()` (`LSPServerInstance.ts:95-104`) explicitly throws if a plugin sets `restartOnCrash` or `shutdownTimeout`, even though `LspServerConfigSchema` still accepts them.
- **File-close lifecycle gap:** `LSPServerManager.closeFile()` (`LSPServerManager.ts:377-400`) carries an explicit `TODO` noting it is not yet wired into compaction, so `openedFiles` retains every opened URI until server shutdown.

> [!WARNING]
> **Verified URI-key mismatch in diagnostic cache invalidation.** Look at [services/lsp/passiveFeedback.ts](../../services/lsp/passiveFeedback.ts):50–52: `formatDiagnosticsForAttachment()` converts `file:///abs/path` to `/abs/path` via `fileURLToPath()`, so `deliveredDiagnostics` in `LSPDiagnosticRegistry.ts:292` keys entries by *plain filesystem path* (`/abs/path`). However, [tools/FileEditTool/FileEditTool.ts](../../tools/FileEditTool/FileEditTool.ts):497 and [tools/FileWriteTool/FileWriteTool.ts](../../tools/FileWriteTool/FileWriteTool.ts):311 call ``clearDeliveredDiagnosticsForFile(`file://${absoluteFilePath}`)``. Because `deliveredDiagnostics.has('file:///abs/path')` misses `/abs/path`, editing a file without shifting an existing diagnostic's exact message and line range will *not* clear its cross-turn dedup entry until the diagnostic changes or ages out of the 500-file LRU.

---

## Putting the Layer Together

Notice how all four dynamic capabilities converge onto the same core harness contracts established in Layers 1–4—never creating parallel agent loops:

```mermaid
flowchart TD
    subgraph Sources["Layer 5 Sources & Materialization"]
        S1["Disk & Bundled Skills (loadSkillsDir / bundledSkills)"]
        S2["Plugins: Built-in, --plugin-dir, Marketplace (reconciler.ts + pluginLoader.ts)"]
        S3["Output Style Markdown (loadOutputStylesDir / built-ins)"]
    end

    subgraph HotSwap["Live Reload & Dynamic Triggers"]
        R1["/reload-plugins (refreshActivePlugins)"]
        R2["FileRead / FileEdit / FileWrite (skill discovery + LSP didChange/didSave)"]
        R3["skillChangeDetector (chokidar, Bun stat polling)"]
    end

    subgraph Runtime["Harness Integration Surfaces"]
        C1["Command Registry + SkillTool (inline newMessages/contextModifier OR forked runAgent)"]
        C2["System Prompt (static intro + keepCodingInstructions / BOUNDARY / output_style)"]
        C3["Hooks & MCP (STATE.registeredHooks + mcp.pluginReconnectKey)"]
        C4["LSPServerManager Lazy (LSPTool queries + LSPDiagnosticRegistry queue)"]
        C5["Turn Attachments (1% budgeted skill_listing + capped diagnostics)"]
    end

    S1 --> C1
    S2 -->|"commands & skills"| C1
    S2 -->|"output-styles (force-for-plugin)"| S3
    S2 -->|"hooks & mcpServers"| C3
    S2 -->|"lspServers (.lsp.json)"| C4
    S3 --> C2
    R1 -->|"clearAllCaches + loadAllPlugins + reinit LSP + swap hooks"| S2
    R1 --> C3
    R1 --> C4
    R2 -->|"paths glob & nested dirs"| S1
    R2 -->|"didChange / didSave"| C4
    R3 -->|"debounced 300ms"| S1
    C1 -->|"delta via sentSkillNames"| C5
    C4 -->|"publishDiagnostics (max 10/file, 30 total)"| C5
```

---

## How This Snaps Into the Next Layer

Every dynamic capability in Layer 5 shares one lifecycle constraint: work is either **turn-scoped** (inline skills, output styles, diagnostic attachments), **synchronously blocking a tool call** (forked skills calling `runAgent({ isAsync: false })` inside `SkillTool`), or **session-scoped infrastructure** owned by a singleton manager (MCP connections and lazy LSP child processes).

What is still missing is a first-class runtime for *user- and model-visible background work* that outlives a single turn—such as a long-running build server promoted from `BashTool`, an asynchronous subagent, a remote agent, a teammate, an MCP monitor, a background memory dream, or a scheduled cron job driven by the bundled `/loop` skill ([skills/bundled/loop.ts](../../skills/bundled/loop.ts)). In [Chapter 17](17-background-task-runtime.md), we cross into Layer 6 at [Task.ts](../../Task.ts) (`TaskStateBase` and its 7 `TaskType` variants) and [tasks.ts](../../tasks.ts), where background execution gets unified identity, disk-backed byte-offset output tailing, completion notifications, and clean cancellation.

---

## Reading Exercises & Code Checkpoints

1. **Audit the `SkillTool` permission allowlist:** Inspect `SAFE_SKILL_PROPERTIES` in [tools/SkillTool/SkillTool.ts](../../tools/SkillTool/SkillTool.ts) (lines 875–933) and compare it against the fields returned by `createSkillCommand()` in [skills/loadSkillsDir.ts](../../skills/loadSkillsDir.ts) (lines 317–345). Which frontmatter fields force a user permission prompt, and what happens if a skill sets `allowed-tools: []` (an empty array)?
2. **Trace the `/reload-plugins` cache-invalidation blast radius:** Run:
   ```sh
   rg -n "clearPluginCache|clearAllCaches|clearCommandMemoizationCaches" utils/plugins/ commands.ts utils/skills/
   ```
   Verify why `skillChangeDetector.ts` calls `clearCommandMemoizationCaches()` on `onDynamicSkillsLoaded` whereas `scheduleReload()` calls `clearSkillCaches()` + `clearCommandsCache()`.
3. **Verify the snapshot-absent `services/skillSearch/` boundary:** Run:
   ```sh
   rg -n "EXPERIMENTAL_SKILL_SEARCH" --glob '*.ts' --glob '*.tsx'
   ```
   Trace how every `require()` of `services/skillSearch/*` is protected by `feature('EXPERIMENTAL_SKILL_SEARCH')` for Bun dead-code elimination, and check how `utils/attachments.ts:2692-2697` explains why `feature()` must appear *before* optional chaining.
4. **Confirm the LSP diagnostic URI-key mismatch:** Read [services/lsp/passiveFeedback.ts](../../services/lsp/passiveFeedback.ts) (lines 43–61), [services/lsp/LSPDiagnosticRegistry.ts](../../services/lsp/LSPDiagnosticRegistry.ts) (lines 290–300 and 372–379), and [tools/FileEditTool/FileEditTool.ts](../../tools/FileEditTool/FileEditTool.ts) (lines 493–514). Trace the exact string passed to `deliveredDiagnostics.set(...)` versus `clearDeliveredDiagnosticsForFile(...)` for `/tmp/app.ts` on macOS/Linux.


---

<!-- chapters/17-background-task-runtime.md — https://reverseengineeringclaudecode.com/chapters/17-background-task-runtime -->

# Chapter 17 — The Background Task Runtime: Unified State, Disk-Backed Output, Notifications, and Proactive Scheduling

> **Layer:** Layer 6 (Concurrency, Tasks, Subagents & Swarms)
> **Prerequisites:** [Chapter 01](01-atoms-types-stores-and-primitives.md), [Chapter 02](02-the-tool-contract.md), [Chapter 06](06-executing-tools.md), [Chapter 12](12-shell-execution-sandboxing-and-workspace-tools.md), [Chapter 16](16-skills-plugins-output-styles-and-lsp.md)
> **Primary Source Files:**
> - [Task.ts](../../Task.ts) — `TaskType` union, `TaskStatus`, `TaskStateBase`, polymorphic `Task` kill interface, and symlink-resistant `generateTaskId()`
> - [tasks.ts](../../tasks.ts) & [tasks/types.ts](../../tasks/types.ts) — Task registry (`getAllTasks`, `getTaskByType`), `TaskState` discriminated union, and `isBackgroundTask()`
> - [tasks/stopTask.ts](../../tasks/stopTask.ts) & [tools/TaskStopTool/TaskStopTool.ts](../../tools/TaskStopTool/TaskStopTool.ts) — Unified cancellation, notification suppression asymmetry, and SDK termination bookends
> - [tasks/LocalShellTask/LocalShellTask.tsx](../../tasks/LocalShellTask/LocalShellTask.tsx), [tasks/LocalShellTask/guards.ts](../../tasks/LocalShellTask/guards.ts), & [tasks/LocalShellTask/killShellTasks.ts](../../tasks/LocalShellTask/killShellTasks.ts) — Background/foreground shell promotion, interactive-prompt stall watchdog, and subagent orphan reaping
> - [tasks/LocalAgentTask/LocalAgentTask.tsx](../../tasks/LocalAgentTask/LocalAgentTask.tsx) & [tasks/LocalMainSessionTask.ts](../../tasks/LocalMainSessionTask.ts) — Local subagent tasks, `Ctrl+B` main-session backgrounding, panel retention, and transcript symlinks
> - [tasks/RemoteAgentTask/RemoteAgentTask.tsx](../../tasks/RemoteAgentTask/RemoteAgentTask.tsx) — Cloud session polling, `--resume` sidecar recovery, `STABLE_IDLE_POLLS` debouncing, and remote review/ultraplan completion
> - [tasks/InProcessTeammateTask/InProcessTeammateTask.tsx](../../tasks/InProcessTeammateTask/InProcessTeammateTask.tsx), [tasks/InProcessTeammateTask/types.ts](../../tasks/InProcessTeammateTask/types.ts), & [tasks/DreamTask/DreamTask.ts](../../tasks/DreamTask/DreamTask.ts) — Teammate task state with `TEAMMATE_MESSAGES_UI_CAP` and UI-only auto-dream lock rollback
> - [utils/task/framework.ts](../../utils/task/framework.ts), [utils/task/diskOutput.ts](../../utils/task/diskOutput.ts), [utils/task/TaskOutput.ts](../../utils/task/TaskOutput.ts), [utils/ShellCommand.ts](../../utils/ShellCommand.ts), & [tools/TaskOutputTool/TaskOutputTool.tsx](../../tools/TaskOutputTool/TaskOutputTool.tsx) — TOCTOU-safe offset polling, `O_NOFOLLOW` disk queues, file-vs-pipe capture, and 5 GB size watchdog
> - [utils/messageQueueManager.ts](../../utils/messageQueueManager.ts), [utils/queueProcessor.ts](../../utils/queueProcessor.ts), [utils/sdkEventQueue.ts](../../utils/sdkEventQueue.ts), & [query.ts](../../query.ts) — Priority command queue, `<task-notification>` delivery, `agentId` scoping, and SDK event bookends
> - [utils/cron.ts](../../utils/cron.ts), [utils/cronTasks.ts](../../utils/cronTasks.ts), [utils/cronTasksLock.ts](../../utils/cronTasksLock.ts), [utils/cronScheduler.ts](../../utils/cronScheduler.ts), [utils/cronJitterConfig.ts](../../utils/cronJitterConfig.ts), [hooks/useScheduledTasks.ts](../../hooks/useScheduledTasks.ts), [tools/ScheduleCronTool/CronCreateTool.ts](../../tools/ScheduleCronTool/CronCreateTool.ts), & [tools/SleepTool/prompt.ts](../../tools/SleepTool/prompt.ts) — Local cron scheduling, deterministic anti-herd jitter, `O_EXCL` lease locks, missed-task prompt-injection defense, and proactive `SleepTool` wakeups

## Why This Layer Exists

Up through Layer 5, the agent executes synchronously inside one turn at a time: the model emits tool calls, `StreamingToolExecutor` runs them ([Chapter 06](06-executing-tools.md)), and the turn waits until every tool resolves. Real engineering sessions immediately break that synchronous mold:

- A user launches a 20-minute integration test suite or dev server in `BashTool` and presses `Ctrl+B` to keep working.
- A coordinator fans out five subagents in parallel and wants to review results as each finishes rather than blocking on the slowest one.
- A `/ultrareview` or `/ultraplan` teleports work to a remote cloud session that outlives the local CLI process and must reconnect on `--resume`.
- A user asks the agent to "check CI every 5 minutes" or "remind me at 3pm", or runs an autonomous loop that sleeps between check-ins without burning tokens on "still waiting" turns.

> [!NOTE]
> **Two different "task" concepts live in this repository.** This chapter dissects the **background execution runtime**—live processes, agents, remote sessions, and dreams stored in `AppState.tasks` ([Task.ts](../../Task.ts), `tasks/`, `utils/task/`). It is completely separate from the user-facing **persistent task checklist / team work board** stored as JSON files under `utils/tasks.ts` and mutated by `TaskCreateTool`, `TaskUpdateTool`, `TaskGetTool`, and `TaskListTool` (covered with swarms in [Chapter 19](19-agent-teams-swarms-and-coordinator-mode.md)).

Turning a single-turn REPL into a concurrent task runtime introduces four brutal systems problems:

1. **One registry across seven execution backends—including nested subagents.** Every background job needs a stable ID, footer pill, kill switch, and GC lifecycle, even when spawned by a subagent whose `setAppState` callback was deliberately stubbed to a no-op.
2. **Gigabytes of output without gigabytes of RAM or disk.** A stuck shell loop once wrote 768 GB to disk; a swarm session that mirrored full transcripts into `AppState` hit 36.8 GB RSS; and sandboxed shells share `/tmp` with the host process, creating symlink-clobber attack vectors.
3. **Asynchronous wakeups without duplicate delivery, zombie state, or cross-agent leakage.** Completion events arrive from OS exit handlers, remote HTTP pollers, and timers while the main loop may be idle, mid-tool-call, or running inside a subagent.
4. **Time-driven wakeups at fleet scale.** Naive local cron triggers `:00` thundering herds against inference servers, double-fires whenever two terminals open the same repository, leaks memory across multi-day sessions, and turns missed one-shot prompts into self-inflicted prompt injections.

---

## 1. The Unified Task State Contract & `setAppStateForTasks`

### The Problem

Earlier iterations of Claude Code grew separate ad-hoc subsystems for background shells, async agents (`asyncAgentUtils.ts`), and remote sessions (`BackgroundRemoteSession`), each with its own state slice, polling loop, and cancellation path. Worse, once subagents were given isolated contexts (`createSubagentContext()` in [utils/forkedAgent.ts](../../utils/forkedAgent.ts)) with a no-op `setAppState` so child turns couldn't mutate parent UI state, any background shell spawned *inside* a subagent vanished into the void—never registered in `AppState.tasks`, never visible in the UI, and never killed when the subagent exited (`PPID=1` zombies).

### The Real Implementation

#### `TaskType`, `TaskStateBase`, and Symlink-Resistant IDs

[Task.ts](../../Task.ts) defines the single base record stored under `AppState.tasks: Record<string, TaskState>`. Every background execution backend shares one 7-member `TaskType` union, one 5-state lifecycle (`pending | running | completed | failed | killed`), and one `TaskStateBase` header:

```ts
// Task.ts:6-29, 45-57
export type TaskType =
  | 'local_bash'
  | 'local_agent'
  | 'remote_agent'
  | 'in_process_teammate'
  | 'local_workflow'
  | 'monitor_mcp'
  | 'dream'

export type TaskStatus =
  | 'pending'
  | 'running'
  | 'completed'
  | 'failed'
  | 'killed'

export function isTerminalTaskStatus(status: TaskStatus): boolean {
  return status === 'completed' || status === 'failed' || status === 'killed'
}

export type TaskStateBase = {
  id: string
  type: TaskType
  status: TaskStatus
  description: string
  toolUseId?: string
  startTime: number
  endTime?: number
  totalPausedMs?: number
  outputFile: string
  outputOffset: number
  notified: boolean
}
```

Task IDs are generated by `generateTaskId(type)` ([Task.ts](../../Task.ts):79-106): a 1-character type prefix (`b` for `local_bash`, `a` for `local_agent`, `r` for `remote_agent`, `t` for `in_process_teammate`, `w` for `local_workflow`, `m` for `monitor_mcp`, `d` for `dream`; [tasks/LocalMainSessionTask.ts](../../tasks/LocalMainSessionTask.ts):75-82 uses `s` for backgrounded main sessions) followed by 8 random characters from a lowercase alphanumeric alphabet (`0-9a-z`). That alphabet is intentionally case-insensitive-safe (for macOS/Windows filesystems) and yields $36^8 \approx 2.8 \times 10^{12}$ IDs—high enough that a sandboxed process cannot pre-plant symlinks by guessing upcoming task output filenames.

Notice what the polymorphic `Task` interface in [Task.ts](../../Task.ts):69-76 actually contains:

```ts
// Task.ts:69-76
// What getTaskByType dispatches for: kill. spawn/render were never
// called polymorphically (removed in #22546). All six kill implementations
// use only setAppState — getAppState/abortController were dead weight.
export type Task = {
  name: string
  type: TaskType
  kill(taskId: string, setAppState: SetAppState): Promise<void>
}
```

That comment is classic reverse-engineering gold: the team originally built a heavier polymorphic `Task` contract (`spawn`, `render`, `kill(taskId, getAppState, setAppState, abortController)`), discovered in production that every spawner and renderer is called directly by concrete type, and ruthlessly pruned the shared interface down to the single operation that truly needs dynamic dispatch by `task.type`: `kill()`.

[tasks.ts](../../tasks.ts) registers implementations in `getAllTasks()` and resolves them via `getTaskByType(type)`. Two entries are dead-code-eliminated behind build-time `feature()` flags via conditional `require()`:

- `LocalWorkflowTask` behind `feature('WORKFLOW_SCRIPTS')` ([tasks.ts](../../tasks.ts):9-11)
- `MonitorMcpTask` behind `feature('MONITOR_TOOL')` ([tasks.ts](../../tasks.ts):12-14)

> [!NOTE]
> **Snapshot absence:** Both `tasks/LocalWorkflowTask/LocalWorkflowTask.ts` and `tasks/MonitorMcpTask/MonitorMcpTask.ts` are **absent from this source snapshot**. Their contracts are observed at call sites in [tasks.ts](../../tasks.ts), [tasks/types.ts](../../tasks/types.ts):8-29, [tasks/pillLabel.ts](../../tasks/pillLabel.ts):57-60, [utils/task/sdkProgress.ts](../../utils/task/sdkProgress.ts):8, [tools/AgentTool/runAgent.ts](../../tools/AgentTool/runAgent.ts):849-857 (`killMonitorMcpTasksForAgent`), and [components/tasks/BackgroundTasksDialog.tsx](../../components/tasks/BackgroundTasksDialog.tsx):18-119. Similarly, note that `InProcessTeammateTask` implements `Task` in [tasks/InProcessTeammateTask/InProcessTeammateTask.tsx](../../tasks/InProcessTeammateTask/InProcessTeammateTask.tsx):24-30, but is intentionally **not** in `getAllTasks()`—teammates are stopped via swarm shutdown/kill helpers rather than `TaskStopTool`.

#### The Five Present Backends and Their Load-Bearing Quirks

[tasks/types.ts](../../tasks/types.ts):12-46 unites all seven concrete state types into `TaskState` and defines `isBackgroundTask(task)`: a task appears in the background indicator ([tasks/pillLabel.ts](../../tasks/pillLabel.ts)) only when `status` is `'running'` or `'pending'` **and** `'isBackgrounded' in task ? task.isBackgrounded !== false : true`. That `isBackgrounded` flag lets shells and subagents register in `AppState.tasks` while still running in the foreground, then seamlessly promote to background tasks in place when `Ctrl+B` or an auto-background timer fires—without re-registering or emitting duplicate `task_started` SDK events.

Each concrete task implementation carries production-hardened behaviors tailored to its execution model:

1. **`LocalShellTask` (`type: 'local_bash'`)** — [LocalShellTask.tsx](../../tasks/LocalShellTask/LocalShellTask.tsx), [guards.ts](../../tasks/LocalShellTask/guards.ts), [killShellTasks.ts](../../tasks/LocalShellTask/killShellTasks.ts).
   - **Module-graph hygiene:** `guards.ts` and `killShellTasks.ts` were extracted out of `LocalShellTask.tsx` so headless consumers (`stopTask.ts` via `cli/print.ts`, and `runAgent.ts`) can type-check and kill shell tasks without pulling React/Ink into their bundle.
   - **Foreground → background promotion:** `registerForeground()` inserts a task with `isBackgrounded: false`. When `Ctrl+B` runs `backgroundAll()` (lines 390-410) or an auto-background timer fires `backgroundExistingForegroundTask()` (lines 420-474), it calls `shellCommand.background(taskId)`, flips `isBackgrounded: true` in place, starts the stall watchdog, and attaches the exit handler. If the command finishes in the foreground instead, `unregisterForeground()` removes it silently.
   - **Interactive-prompt stall watchdog:** `startStallWatchdog()` (lines 46-104) polls `stat(outputPath)` every 5 seconds (disabled for `kind === 'monitor'`). If the file stops growing for 45 seconds (`STALL_THRESHOLD_MS`), it reads the last 1 KB (`STALL_TAIL_BYTES`) and tests the final line against `PROMPT_PATTERNS` (`(y/n)`, `[y/n]`, `(yes/no)`, `Press any key/Enter`, `Continue?`, `Overwrite?`, or `Do you/Are you sure...?`). Merely slow commands (`git log -S`, long builds) stay silent; a matching prompt emits a **one-shot, statusless** `<task-notification>` telling the model to kill and re-run with piped input or a non-interactive flag.
   - **Subagent orphan reaping:** `LocalShellTaskState.agentId` records which subagent spawned the shell. When that subagent finishes, `runAgent.ts`'s `finally` block calls `killShellTasksForAgent()` ([killShellTasks.ts](../../tasks/LocalShellTask/killShellTasks.ts):53-76), killing every running shell with that `agentId` ("prevents 10-day `fake-logs.sh` zombies") and purging any queued notifications addressed to the dead agent via `dequeueAllMatching(cmd => cmd.agentId === agentId)`.

2. **`LocalAgentTask` (`type: 'local_agent'`) & `LocalMainSessionTask` (`agentType: 'main-session'`)** — [LocalAgentTask.tsx](../../tasks/LocalAgentTask/LocalAgentTask.tsx), [LocalMainSessionTask.ts](../../tasks/LocalMainSessionTask.ts).
   - **Promise-based background signal:** `registerAgentForeground()` (lines 526-614) creates a `backgroundSignal` `Promise<void>` stored in a module-level `backgroundSignalResolvers` map. Pressing `Ctrl+B` (`backgroundAgentTask`) or hitting `autoBackgroundMs` flips `isBackgrounded: true` and resolves the promise, letting `AgentTool` detach the child turn into the background without aborting it.
   - **UI retention vs. eviction grace period:** `LocalAgentTaskState` distinguishes `retain: boolean` ("the UI is holding this task open in a transcript viewer, blocking GC") from `viewingAgentTaskId` ("what I am currently looking at") and tracks `evictAfter?: number`. Terminal transitions (`completeAgentTask`, `failAgentTask`, `killAsyncAgent`) set `evictAfter = task.retain ? undefined : Date.now() + PANEL_GRACE_MS` (30 seconds), keeping finished workers visible in the coordinator panel briefly before GC.
   - **Accurate token accounting:** `ProgressTracker` (lines 41-96) stores `latestInputTokens` (overwritten per assistant message because Anthropic API `input_tokens` + cache tokens are cumulative per turn) separately from `cumulativeOutputTokens` (summed per turn), preventing quadratic double-counting in UI progress displays.
   - **Backgrounding the main session (`LocalMainSessionTask.ts`):** Double-`Ctrl+B` backgrounds the active foreground query by spawning an independent `query()` loop under `type: 'local_agent'`, `agentType: 'main-session'`, with an `s`-prefixed ID. Crucially, `registerMainSessionTask()` symlinks its `.output` file to an **isolated per-task transcript** (`getAgentTranscriptPath(asAgentId(taskId))`), *not* the main session transcript, and runs inside `runWithAgentContext` (`AsyncLocalStorage`)—so if the user runs `/clear` in the foreground, the background query neither corrupts the fresh session transcript nor loses its invoked skills ([LocalMainSessionTask.ts](../../tasks/LocalMainSessionTask.ts):102-110, 364-375).

3. **`RemoteAgentTask` (`type: 'remote_agent'`)** — [RemoteAgentTask.tsx](../../tasks/RemoteAgentTask/RemoteAgentTask.tsx).
   - Tracks cloud sessions (`remoteTaskType`: `'remote-agent' | 'ultraplan' | 'ultrareview' | 'autofix-pr' | 'background-pr'`) and persists lightweight sidecar metadata via `writeRemoteAgentMetadata()`. On `--resume`, `restoreRemoteAgentTasks()` (lines 477-532) fetches live CCR status for each entry: **only HTTP 404** (`Session not found:`) or `'archived'` deletes the sidecar, while 401/network errors skip recovery so the user can `/login` without losing an in-flight cloud job.
   - Its 1-second poller (`startRemoteSessionPolling`, lines 538-799) guards against four subtle distributed races:
     - *Transient idle between turns:* Remote agents flip to `'idle'` between every tool turn, so `STABLE_IDLE_POLLS = 5` consecutive idle polls with zero log growth are required before declaring completion.
     - *Bughunter vs. prompt-mode discrimination:* Remote code review runs either as a `SessionStart` hook (`run_hunt.sh`) where the session stays `"idle"` the entire time, or as assistant prompt turns. Checking `hasSessionStartHook` prevents `stableIdle` from prematurely completing a bughunter run between heartbeat echoes; only `<remote-review>` or the 30-minute `REMOTE_REVIEW_TIMEOUT_MS` (measured from `pollStartedAt`, not `spawnedAt`, so `--resume` doesn't instantly time out!) completes it.
     - *Tag-only delta scanning:* Scanning only `response.newEvents` keeps polling $O(\text{new})$, and `extractReviewTagFromLog()` refuses to fall back to untagged assistant prose so early `"I'm analyzing the diff..."` text never triggers premature completion.
     - *Kill race guard:* If `stopTask` marks the task `'killed'` while `pollRemoteSessionEvents()` is in flight, `raceTerminated` aborts the poller before it can overwrite status or fire notifications (lines 689-720).

4. **`InProcessTeammateTask` (`type: 'in_process_teammate'`)** — [types.ts](../../tasks/InProcessTeammateTask/types.ts), [InProcessTeammateTask.tsx](../../tasks/InProcessTeammateTask/InProcessTeammateTask.tsx).
   - Stores plain-data `TeammateIdentity` (mirroring `AsyncLocalStorage`'s `TeammateContext`), two distinct `AbortController`s (`abortController` kills the whole teammate; `currentWorkAbortController` aborts only its current turn), `isIdle`, `pendingUserMessages`, and a capped UI transcript mirror:

```ts
// tasks/InProcessTeammateTask/types.ts:89-101
// BQ analysis (round 9, 2026-03-20) showed ~20MB RSS per agent at 500+ turn
// sessions and ~125MB per concurrent agent in swarm bursts. Whale session
// 9a990de8 launched 292 agents in 2 minutes and reached 36.8GB. The dominant
// cost is this array holding a second full copy of every message.
export const TEAMMATE_MESSAGES_UI_CAP = 50
```

   Every `appendCappedMessage()` call slices to the most recent 50 messages in `AppState`, leaving the authoritative history in the runner's local array and on disk.

5. **`DreamTask` (`type: 'dream'`)** — [DreamTask.ts](../../tasks/DreamTask/DreamTask.ts).
   - Surfaces auto-dream memory consolidation ([Chapter 10](10-memory-systems-claudemd-auto-memory-and-dream.md)) in the footer pill without changing the dream agent itself. Because dream has no model-facing notification path (it's UI-only), `completeDreamTask()` and `failDreamTask()` immediately set `notified: true` so GC can evict the entry. Its `DreamTaskState` stashes `priorMtime` so `DreamTask.kill()` can call `rollbackConsolidationLock(priorMtime)` (lines 136-156), allowing the next session to retry consolidation rather than waiting out the lock window.

#### Why `setAppStateForTasks` Exists

Look at `createSubagentContext()` in [utils/forkedAgent.ts](../../utils/forkedAgent.ts):408-422:

```ts
// utils/forkedAgent.ts:408-422
    // AppState access
    getAppState,
    setAppState: overrides?.shareSetAppState
      ? parentContext.setAppState
      : () => {},
    // Task registration/kill must always reach the root store, even when
    // setAppState is a no-op — otherwise async agents' background bash tasks
    // are never registered and never killed (PPID=1 zombie).
    setAppStateForTasks:
      parentContext.setAppStateForTasks ?? parentContext.setAppState,
    // Async subagents whose setAppState is a no-op need local denial tracking
    // so the denial counter actually accumulates across retries.
    localDenialTracking: overrides?.shareSetAppState
      ? parentContext.localDenialTracking
      : createDenialTrackingState(),
```

`ToolUseContext` ([Tool.ts](../../Tool.ts):183-192) carries **two** store setters on purpose:

- `setAppState` mutates UI and turn-scoped state; async subagents and in-process teammates receive a no-op `() => {}` so they cannot flip the user's permission mode, stomp foreground dialogs, or mutate parent UI flags.
- `setAppStateForTasks` is always threaded to the **root** `AppState` store across arbitrary subagent nesting depth (`parentContext.setAppStateForTasks ?? parentContext.setAppState`). Every task-infrastructure call site—[BashTool.tsx](../../tools/BashTool/BashTool.tsx):651, [PowerShellTool.tsx](../../tools/PowerShellTool/PowerShellTool.tsx):460, [AgentTool.tsx](../../tools/AgentTool/AgentTool.tsx):259, [runAgent.ts](../../tools/AgentTool/runAgent.ts):338, [resumeAgent.ts](../../tools/AgentTool/resumeAgent.ts):60, [SendMessageTool.ts](../../tools/SendMessageTool/SendMessageTool.ts):813, [autoDream.ts](../../services/autoDream/autoDream.ts):201, and [utils/attachments.ts](../../utils/attachments.ts):1093—writes through `toolUseContext.setAppStateForTasks ?? toolUseContext.setAppState`.

> [!IMPORTANT]
> **Invariant:** Session-scoped infrastructure (background tasks, session hooks, `todos` cleanup) must always route through `setAppStateForTasks ?? setAppState`. Routing a background spawn through `setAppState` works on the main thread during manual testing and silently leaks `PPID=1` orphan processes whenever invoked from an async subagent or teammate.

### Hidden Invariants & Failure Modes

- **Reference-equality no-op suppression:** `updateTaskState()` ([utils/task/framework.ts](../../utils/task/framework.ts):48-72) checks `if (updated === task) return prev`. Roughly 18 React components subscribe to `s.tasks` (REPL, Spinner, PromptInput, task pills); without this guard, a 1-second remote poller returning an unchanged spread would force a full terminal re-render every second while idle ([RemoteAgentTask.tsx](../../tasks/RemoteAgentTask/RemoteAgentTask.tsx):699-707).
- **Resume replacement preservation:** When a background agent is resumed in place (`resumeAgentBackground`), `registerTask()` ([utils/task/framework.ts](../../utils/task/framework.ts):77-117) detects `existing !== undefined`, carries forward UI-owned fields (`retain`, `startTime`, `messages`, `diskLoaded`, `pendingMessages`) so the user's open transcript viewer doesn't reset or reorder, and skips emitting a duplicate `task_started` SDK event.
- **No side effects inside state updaters:** Functions like `backgroundTask()` ([LocalShellTask.tsx](../../tasks/LocalShellTask/LocalShellTask.tsx):342-358) and `unregisterAgentForeground()` ([LocalAgentTask.tsx](../../tasks/LocalAgentTask/LocalAgentTask.tsx):668-681) capture `cleanupFn = task.unregisterCleanup` inside the `setAppState` updater and invoke `cleanupFn?.()` *after* `setAppState` returns, keeping updaters pure.

---

## 2. Disk-Backed Output, Byte Offsets, and Bounded Memory

### The Problem

Background commands and agents can run for hours and produce megabytes—or gigabytes—of output. Holding stdout in JS strings crashes the process with OOM, while polling full output files every second wastes disk bandwidth. Even writing to disk introduces four nasty failure modes observed in production:

1. **Cross-session clobbering (`inc-4586`):** Two Claude sessions in the same repository used to share one `tasks/` directory; startup cleanup in Session B unlinked Session A's in-flight `.output` files, leaving Session A's writer holding a live unlinked inode while `getStdout()` read `ENOENT` and silently returned empty output.
2. **`/clear` path drift:** `/clear` calls `regenerateSessionId()`. If `getTaskOutputDir()` re-read `getSessionId()` dynamically, background bash tasks that survive `/clear` would suddenly point at a different directory from the live fd.
3. **Sandbox symlink attacks:** A sandboxed command running inside the workspace can inspect temp directories; if the host opens `<taskId>.output` without `O_NOFOLLOW`, an attacker could pre-create a symlink pointing to `~/.ssh/authorized_keys` or `~/.bashrc` and trick the unsandboxed host process into writing there.
4. **Runaway disk fill ("768GB incident"):** When a bash command writes directly to a file descriptor (bypassing JavaScript), JS-side output caps never see the bytes—a tight `yes` or broken append loop can fill the entire disk once the foreground timeout is lifted by backgrounding.

### The Real Implementation

#### Path Freezing, Symlink Hardening, and Zero-Retention Write Queues

[utils/task/diskOutput.ts](../../utils/task/diskOutput.ts) resolves all four hazards:

- **Session-scoped, first-call-frozen output directory (lines 49-74):** `getTaskOutputDir()` memoizes `join(getProjectTempDir(), getSessionId(), 'tasks')` on first call. Putting it under the project temp dir guarantees `checkReadableInternalPath` auto-allows `ReadTool` without permission prompts; embedding `getSessionId()` isolates concurrent sessions; freezing on first call ensures background bash tasks survive `/clear`. Every task's file path is deterministically `${getTaskOutputDir()}/${taskId}.output`.
- **Symlink-safe file creation (lines 21, 400-451):** `initTaskOutput()` opens the file with `O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW` on POSIX (and `'wx'` on Windows because numeric `O_EXCL` produces `EINVAL` through libuv). For `LocalAgentTask` and `LocalMainSessionTask`, `initTaskOutputAsSymlink(taskId, transcriptPath)` intentionally points `<taskId>.output` directly at the agent's JSONL sidechain transcript—so `Read` on `outputFile` reads live agent progress without duplicating bytes on disk.
- **Flat-array, GC-conscious `DiskTaskOutput` queue (lines 97-231):** For tasks that push text from JS (`RemoteAgentTask`, pipe-mode hooks, spilled buffers), `DiskTaskOutput` avoids chained `.then()` promises (which retain every chunk closure until the whole chain settles). Instead, it pushes strings into `#queue: string[]`, caps total writes at `MAX_TASK_OUTPUT_BYTES = 5 * 1024 * 1024 * 1024` (5 GB), and drains in a single loop with `O_NOFOLLOW` and a single transient-error retry (`EMFILE` / Windows `EPERM`):

```ts
// utils/task/diskOutput.ts:178-205
  #writeAllChunks(): Promise<void> {
    // This code is extremely precise.
    // You **must not** add an await here!! That will cause memory to balloon as the queue grows.
    // It's okay to add an `await` to the caller of this method (e.g. #drainAllChunks) because that won't cause Buffer[] to be kept alive in memory.
    return this.#fileHandle!.appendFile(
      // This variable needs to get GC'd ASAP.
      this.#queueToBuffers(),
    )
  }

  /** Keep this in a separate method so that GC doesn't keep it alive for any longer than it should. */
  #queueToBuffers(): Buffer {
    // Use .splice to in-place mutate the array, informing the GC it can free it.
    const queue = this.#queue.splice(0, this.#queue.length)

    let totalLength = 0
    for (const str of queue) {
      totalLength += Buffer.byteLength(str, 'utf8')
    }

    const buffer = Buffer.allocUnsafe(totalLength)
    let offset = 0
    for (const str of queue) {
      offset += buffer.write(str, offset, 'utf8')
    }

    return buffer
  }
```

Putting `#queueToBuffers()` in a separate non-`async` frame and returning `appendFile(...)` without `await` keeps the temporary `Buffer` off any suspended async stack frame—so the GC can reclaim it the instant libuv finishes the write.

#### Dual-Mode `TaskOutput` and the 5 GB Disk Size Watchdog

[utils/task/TaskOutput.ts](../../utils/task/TaskOutput.ts) and [utils/ShellCommand.ts](../../utils/ShellCommand.ts) split shell capture into two completely different data paths:

1. **File mode (`stdoutToFile = true`, used by `BashTool`):** Both `stdio[1]` and `stdio[2]` are bound directly to the `.output` file descriptor at `spawn()` time. Zero bytes flow through Node/Bun streams.
   - *Live UI progress:* Rather than polling every running command unconditionally, `TaskOutput` maintains a static `#registry` and `#activePolling` map driven by React component mount/unmount (`TaskOutput.startPolling(taskId)` / `stopPolling(taskId)`, lines 81-103). One shared `.unref()`'d 1-second timer runs non-async `#tick()`, reading only the last 4 KB (`PROGRESS_TAIL_BYTES = 4096`) via `tailFile()`, slicing the last 5 and 100 lines, and computing a monotone extrapolated line count `Math.max(prevLines, Math.round((bytesTotal / bytesRead) * lineCount))`. Even when the file is empty (`git log -S`), `#tick()` still invokes `onProgress` so the tool generator wakes up and checks backgrounding timers.
   - *Disk-fill watchdog:* As soon as `ShellCommandImpl.background(taskId)` lifts the foreground timeout ([ShellCommand.ts](../../utils/ShellCommand.ts):239-261, 349-366), it starts `#startSizeWatchdog()`, which `stat()`s the output file every 5 seconds and `treeKill(..., 'SIGKILL')`s the entire process tree if size exceeds `MAX_TASK_OUTPUT_BYTES` (5 GB).
   - *Foreground cleanup:* If a command completes *without* being backgrounded and its entire output fits inside `getMaxOutputLength()` (`outputFileRedundant === true`), `#handleExit()` deletes the `.output` file automatically; if larger, it returns `outputFilePath` so `toolResultStorage.ts` ([Chapter 06](06-executing-tools.md)) handles `<persisted-output>` spill. If the file disappeared mid-run (`ENOENT`), `#readStdoutFromFile()` returns a loud diagnostic string instead of silent empty output ([TaskOutput.ts](../../utils/task/TaskOutput.ts):313-325).

2. **Pipe mode (`stdoutToFile = false`, used by hooks):** `StreamWrapper` ([ShellCommand.ts](../../utils/ShellCommand.ts):66-104) pipes UTF-8 chunks into `TaskOutput.#writeBuffered()`, buffering up to `DEFAULT_MAX_MEMORY` (8 MB) in RAM. For progress extraction, `#updateProgress()` deliberately copies extracted lines with `Buffer.from(line).toString()` (line 230) so short slices do not pin giant parent chunks in V8/JSC memory. If memory exceeds 8 MB—or the command is backgrounded—`#spillToDisk()` flushes both buffers into `DiskTaskOutput` and streams subsequent chunks directly to disk.

#### Incremental Byte-Offset Polling Without TOCTOU Zombification

To inspect task progress without re-reading multi-gigabyte files, [utils/task/diskOutput.ts](../../utils/task/diskOutput.ts):304-357 provides two bounded readers (both capped at `DEFAULT_MAX_READ_BYTES = 8 MB`):

- `getTaskOutputDelta(taskId, fromOffset, maxBytes)` calls `readFileRange()` starting at `task.outputOffset` and returns `{ content, newOffset: fromOffset + bytesRead }`.
- `getTaskOutput(taskId, maxBytes)` calls `tailFile()` and prepends `[NKB of earlier output omitted]` if the file exceeded 8 MB.

On every turn's attachment pass, `getUnifiedTaskAttachments()` ([utils/attachments.ts](../../utils/attachments.ts):3439-3462) invokes `generateTaskAttachments()` and `applyTaskOffsetsAndEvictions()` ([utils/task/framework.ts](../../utils/task/framework.ts):158-249). Look closely at the TOCTOU scar encoded directly into `applyTaskOffsetsAndEvictions()`:

```ts
// utils/task/framework.ts:213-249
export function applyTaskOffsetsAndEvictions(
  setAppState: SetAppState,
  updatedTaskOffsets: Record<string, number>,
  evictedTaskIds: string[],
): void {
  const offsetIds = Object.keys(updatedTaskOffsets)
  if (offsetIds.length === 0 && evictedTaskIds.length === 0) {
    return
  }
  setAppState(prev => {
    let changed = false
    const newTasks = { ...prev.tasks }
    for (const id of offsetIds) {
      const fresh = newTasks[id]
      // Re-check status on fresh state — task may have completed during the
      // await. If it's no longer running, the offset update is moot.
      if (fresh?.status === 'running') {
        newTasks[id] = { ...fresh, outputOffset: updatedTaskOffsets[id]! }
        changed = true
      }
    }
    for (const id of evictedTaskIds) {
      const fresh = newTasks[id]
      // Re-check terminal+notified on fresh state (TOCTOU: resume may have
      // replaced the task during the generateTaskAttachments await)
      if (!fresh || !isTerminalTaskStatus(fresh.status) || !fresh.notified) {
        continue
      }
      if ('retain' in fresh && (fresh.evictAfter ?? Infinity) > Date.now()) {
        continue
      }
      delete newTasks[id]
      changed = true
    }
    return changed ? { ...prev, tasks: newTasks } : prev
  })
}
```

Because `generateTaskAttachments()` `await`s `getTaskOutputDelta()` on disk, the `AppState` snapshot it started with can go stale mid-flight: a task may finish and transition to `'completed'`, or a completed agent may be resumed back to `'running'`. Returning **only** a narrow offset patch (`Record<string, number>`) and a candidate eviction list—then re-checking `fresh.status`, `fresh.notified`, and `fresh.evictAfter` inside the `setAppState(prev => ...)` updater—guarantees that an offset update never clobbers a completion transition (which would turn the task into an eternal `'running'` zombie) and an eviction never deletes a freshly resumed agent.

> [!NOTE]
> **Why `TaskOutputTool` is deprecated:** [tools/TaskOutputTool/TaskOutputTool.tsx](../../tools/TaskOutputTool/TaskOutputTool.tsx) (keeping aliases `AgentOutputTool` and `BashOutputTool`) still supports `block: true/false` polling (sleeping 100 ms per check up to 600 s), extracts clean `agentTask.result` text instead of raw symlinked JSONL for `local_agent`, and tail-truncates output through `formatTaskOutput()` ([utils/task/outputFormatting.ts](../../utils/task/outputFormatting.ts): `TASK_MAX_OUTPUT_LENGTH`, default 32,000 chars, upper cap 160,000 chars). However, its prompt now explicitly tells the model to prefer `ReadTool` directly on the task's `outputFile` path—avoiding blocking poll loops inside a turn—and `TaskOutputTool.isEnabled()` disables it in internal `ant` builds (compiled in this snapshot as `return "external" !== 'ant'`, line 164).

### Hidden Invariants & Failure Modes

- **`evictTaskOutput()` vs. `cleanupTaskOutput()`:** When a task finishes, every task backend calls `evictTaskOutput(taskId)` ([diskOutput.ts](../../utils/task/diskOutput.ts):288-298), which flushes pending writes and drops the `DiskTaskOutput` object from the in-memory `outputs` map **without unlinking the `.output` file**. The file intentionally remains on disk so the model can `Read` it after receiving the `<task-notification>`.
- **`'exit'` vs. `'close'` on child processes:** `ShellCommandImpl.#createResultPromise()` ([ShellCommand.ts](../../utils/ShellCommand.ts):269-273) listens for `'exit'`, never `'close'`. Node's `'close'` waits until all stdio fds close, meaning a command that spawns a detached daemon (`sleep 30 &`) would hang forever.
- **Teardown ordering in `ShellCommandImpl.cleanup()`:** `cleanup()` ([ShellCommand.ts](../../utils/ShellCommand.ts):368-381) calls `#cleanupListeners()` *before* nulling `#abortSignal`. Because `kill()` schedules `#handleExit()` on the microtask queue, nulling `#abortSignal` first would crash `#handleExit()` when it calls `removeEventListener` on `null`.

---

## 3. Asynchronous Notification Delivery, Cancellation, and SDK Bookends

### The Problem

Persisting output to disk solves *where* bytes live, not *when* the model learns a task finished. A naive polling framework that generates inline attachments for completed tasks races against exit callbacks, delivering the same completion twice (once as an attachment, once as a new turn). Meanwhile, in-process subagents share the same process-global command queue as the coordinator: without explicit routing, a worker's background shell completion leaks directly into the coordinator's prompt context.

### The Real Implementation

#### Atomic `notified` Check-and-Set and the `<task-notification>` Envelope

Look at [utils/task/framework.ts](../../utils/task/framework.ts):199-202: `generateTaskAttachments()` deliberately leaves `attachments` empty for completed tasks. Instead, each concrete task type owns its own completion notification (`enqueueShellNotification`, `enqueueAgentNotification`, `enqueueRemoteNotification`, `enqueueMainSessionNotification`) following one strict protocol:

1. **Atomic test-and-set on `task.notified`:** Inside `updateTaskState()`, check `if (task.notified) return task`; otherwise set `shouldEnqueue = true` and flip `notified: true`. If `TaskStopTool`, `TaskOutputTool`, or `markTaskNotified()` already claimed the bit, the completion handler exits silently.
2. **Invalidate prompt speculation:** Call `abortSpeculation(setAppState)` so any pre-computed speculative response built against stale background-task state is discarded while preserving the suggestion text.
3. **Enqueue structured XML:** Push a `<task-notification>` block containing `<task-id>`, optional `<tool-use-id>`, `<output-file>`, `<status>`, `<summary>`, and (for agents) `<result>`, `<usage>`, and `<worktree>` via `enqueuePendingNotification({ value, mode: 'task-notification', priority, agentId })`.

#### The Unified Priority Command Queue and Dual Drain Paths

All user inputs, task notifications, cron fires, and proactive ticks converge in a single module-level queue in [utils/messageQueueManager.ts](../../utils/messageQueueManager.ts) (exposed to React via `useSyncExternalStore` with frozen snapshots). Every `QueuedCommand` ([types/textInputTypes.ts](../../types/textInputTypes.ts):277-358) carries a priority—`'now' (0) > 'next' (1) > 'later' (2)`—plus `mode`, optional `isMeta`, optional `workload`, and optional `agentId`:

- `enqueue()` (user input) defaults to `'next'`.
- `enqueuePendingNotification()` (task completions) defaults to `'later'` so background noise never starves human typing—except `LocalShellTask` completions when `feature('MONITOR_TOOL')` is enabled and stall-watchdog alerts, which pass `priority: 'next'`.
- `'task-notification'` is in `NON_EDITABLE_MODES` ([messageQueueManager.ts](../../utils/messageQueueManager.ts):343-361); `isQueuedCommandEditable()` rejects both non-editable modes and `isMeta: true` items so raw XML never gets pulled into the user's editable prompt buffer on `UP`/`ESC` (`popAllEditable()`).

Items leave the queue through **two** distinct drain points depending on whether a turn is currently running:

1. **Mid-turn drain inside `query()` ([query.ts](../../query.ts):1566-1643):** After tools execute on each loop iteration, `query()` snapshots qualifying queue entries, converts `'prompt'` and `'task-notification'` entries into `queued_command` attachments via `getQueuedCommandAttachments()` ([utils/attachments.ts](../../utils/attachments.ts):1044-1083), yields them before the next model round-trip, and calls `removeFromQueue(consumedCommands)`:

```ts
// query.ts:1566-1578
    const sleepRan = toolUseBlocks.some(b => b.name === SLEEP_TOOL_NAME)
    const isMainThread =
      querySource.startsWith('repl_main_thread') || querySource === 'sdk'
    const currentAgentId = toolUseContext.agentId
    const queuedCommandsSnapshot = getCommandsByMaxPriority(
      sleepRan ? 'later' : 'next',
    ).filter(cmd => {
      if (isSlashCommand(cmd)) return false
      if (isMainThread) return cmd.agentId === undefined
      // Subagents only drain task-notifications addressed to them — never
      // user prompts, even if someone stamps an agentId on one.
      return cmd.mode === 'task-notification' && cmd.agentId === currentAgentId
    })
```

   Two critical invariants jump off those 13 lines:
   - **Agent isolation:** When PR `#18453` unified the command queue, subagent notifications briefly leaked into the coordinator. Filtering by `cmd.agentId === undefined` on the main thread and `cmd.mode === 'task-notification' && cmd.agentId === currentAgentId` inside subagents restores strict isolation—and guarantees subagents can never consume human prompts.
   - **Post-sleep priority upgrade:** Normally, mid-turn draining only pulls `'now'` and `'next'` items, leaving `'later'` notifications for between turns. If `Sleep` ran in that tool round (`sleepRan`), the threshold widens to `'later'` so the notification that woke `SleepTool` is consumed immediately instead of remaining in the queue and causing the next `Sleep` call to wake in 0 ms in an infinite loop ([utils/attachments.ts](../../utils/attachments.ts):1052-1056).

2. **Between-turn drain (when the main loop is idle):**
   - **Interactive REPL ([utils/queueProcessor.ts](../../utils/queueProcessor.ts):52-87):** `processQueueIfReady()` peeks **with** the `cmd.agentId === undefined` filter—because an unfiltered `peek()` landing on a subagent notification would set `targetMode`, fail to match any main-thread item, return `processed: false`, and stall queued human prompts permanently. It drains slash commands and bash-mode commands singly, and batches consecutive same-mode items (never mixing `'prompt'` and `'task-notification'`). For UI cleanliness in fullscreen non-verbose mode, [utils/collapseBackgroundBashNotifications.ts](../../utils/collapseBackgroundBashNotifications.ts) folds consecutive completed bash notifications (matched via `BACKGROUND_BASH_SUMMARY_PREFIX` + `<status>completed</status>`) into one synthetic `"N background commands completed"` line while leaving failures, kills, agents, and monitors expanded.
   - **Headless / SDK streaming mode ([cli/print.ts](../../cli/print.ts):1934-2094):** `drainCommandQueue()` processes `'task-notification'` singly, parses `<task-id>`, `<tool-use-id>`, `<output-file>`, `<status>`, `<summary>`, and `<usage>` out of the XML, emits a structured `task_notification` SDK system event, and then **falls through to `ask()`** so the model still reacts to the result. Critically, lines 2063-2092 only emit the SDK event when **`statusMatch` is present**—preventing statusless progress pings (such as `LocalShellTask`'s stall watchdog or monitor stream events) from falling through to `'completed'` and falsely closing the task in IDE/SDK panels!

#### Unified Cancellation (`stopTask.ts`) and SDK Bookend Symmetry

Both `TaskStopTool` ([tools/TaskStopTool/TaskStopTool.ts](../../tools/TaskStopTool/TaskStopTool.ts), which keeps the deprecated `KillShell` alias and `shell_id` parameter for transcript/SDK backwards compatibility) and the SDK `stop_task` control request delegate to `stopTask()` in [tasks/stopTask.ts](../../tasks/stopTask.ts):

```ts
// tasks/stopTask.ts:57-96
  const taskImpl = getTaskByType(task.type)
  if (!taskImpl) {
    throw new StopTaskError(
      `Unsupported task type: ${task.type}`,
      'unsupported_type',
    )
  }

  await taskImpl.kill(taskId, setAppState)

  // Bash: suppress the "exit code 137" notification (noise). Agent tasks: don't
  // suppress — the AbortError catch sends a notification carrying
  // extractPartialResult(agentMessages), which is the payload not noise.
  if (isLocalShellTask(task)) {
    let suppressed = false
    setAppState(prev => {
      const prevTask = prev.tasks[taskId]
      if (!prevTask || prevTask.notified) {
        return prev
      }
      suppressed = true
      return {
        ...prev,
        tasks: {
          ...prev.tasks,
          [taskId]: { ...prevTask, notified: true },
        },
      }
    })
    // Suppressing the XML notification also suppresses print.ts's parsed
    // task_notification SDK event — emit it directly so SDK consumers see
    // the task close.
    if (suppressed) {
      emitTaskTerminatedSdk(taskId, 'stopped', {
        toolUseId: task.toolUseId,
        summary: task.description,
      })
    }
  }
```

Every `registerTask()` emits a `task_started` event into [utils/sdkEventQueue.ts](../../utils/sdkEventQueue.ts) (a 1,000-entry bounded queue that no-ops in interactive TUI mode when `!getIsNonInteractiveSession()`). Normally, `cli/print.ts` closes that bookend by parsing the `<task-notification>` XML. Whenever a termination path suppresses that XML notification—killing a `local_bash` task in `stopTask()`, killing a `remote_agent` in `RemoteAgentTask.kill()`, foregrounding a `LocalMainSessionTask` before completion, or aborting mid-stream—that path **must** call `emitTaskTerminatedSdk()` directly so IDE/SDK consumers don't display a spinner forever. Conversely, `stopTask()` intentionally leaves `local_agent` un-suppressed so the aborted agent's `catch (AbortError)` can still deliver its partial results.

### Hidden Invariants & Failure Modes

- **Eager vs. lazy task eviction:** `evictTerminalTask()` ([utils/task/framework.ts](../../utils/task/framework.ts):125-144) allows components (`CoordinatorAgentStatus`, `inProcessRunner`) to free finished tasks immediately without waiting for the next `query()` turn, while `generateTaskAttachments()` acts as a lazy GC safety net. Both enforce the exact same triple guard: `isTerminalTaskStatus(task.status) && task.notified && (!('retain' in task) || (task.evictAfter ?? Infinity) <= Date.now())`.
- **`STOPPED_DISPLAY_MS = 3_000` vs. `PANEL_GRACE_MS = 30_000`:** Killed tasks linger briefly for visual confirmation before eviction; retained agent transcripts cannot be evicted at all until the user closes the transcript view (`retain: false` and `evictAfter` stamped).
- **Double-emit danger:** Never emit both a `<status>`-bearing XML `<task-notification>` *and* a direct `emitTaskTerminatedSdk()` on the same exit path—`cli/print.ts` will emit a second `task_notification` event for the same `task_id`.

---

## 4. Scheduled Cron Tasks and Proactive `SleepTool` Wakeups

### The Problem

Background shells and subagents only run *after* a human turn kicks them off. Many real workflows are time-driven: checking a PR every 10 minutes, waking up at 9am to run a smoke test, or polling an external system while idle. Implementing local scheduling naively breaks at scale in five predictable ways:

1. **Global `:00` thundering herds:** If 50,000 sessions schedule `0 * * * *` ("hourly") or `0 9 * * *` ("9am"), every client fires on the exact same second and hammers the inference backend.
2. **Duplicate fires across terminals:** Opening two Claude sessions in the same repository causes both to read `.claude/scheduled_tasks.json` and execute every cron job twice.
3. **Unbounded multi-day memory accumulation:** After cron shipped (`#19931`), p99 session uptime jumped from 61 minutes to 53 hours, allowing slow Tier-1 heap leaks to compound indefinitely.
4. **Daemon restart catch-up storms:** If a daemon child despawns while idle and re-anchors recurring crons from a 10-day-old `createdAt`, every recurring task fires immediately on every spawn.
5. **Self-inflicted prompt injection on missed one-shots:** If the user closed their laptop and missed a one-shot task, dumping its raw multi-line prompt directly into the next startup turn can trick the model into executing stale side effects without confirmation—or breaking out of a naive Markdown code fence using triple backticks.

### The Real Implementation

#### Feature Gates, Killswitches, and Dual Storage

The cron subsystem (`CronCreateTool`, `CronDeleteTool`, `CronListTool` under [tools/ScheduleCronTool/](../../tools/ScheduleCronTool/)) is gated by `isKairosCronEnabled()` in [tools/ScheduleCronTool/prompt.ts](../../tools/ScheduleCronTool/prompt.ts):36-62:

- **Build-time gate:** `feature('AGENT_TRIGGERS')` (intentionally decoupled from `feature('KAIROS')` with zero imports into `src/assistant/`).
- **Local killswitch:** `CLAUDE_CODE_DISABLE_CRON` overrides everything.
- **Runtime fleet killswitch:** GrowthBook `tengu_kairos_cron` (5-minute refresh, **default `true`** so Bedrock/Vertex/Foundry and `DISABLE_TELEMETRY` users who disable GrowthBook keep `/loop` working—citing GH `#31759`). A narrower `tengu_kairos_cron_durable` flag (also default `true`) forces `effectiveDurable = false` at `CronCreateTool.call()` without changing the tool's Zod schema mid-session.

Tasks live in one of two stores managed by [utils/cronTasks.ts](../../utils/cronTasks.ts):

- **Session-only (`durable: false`, default in `CronCreateTool`):** Held purely in `bootstrap/state.ts` process memory (`addSessionCronTask` / `getSessionCronTasks` / `removeSessionCronTasks`). Never touches disk, dies with the process, and does not require a file lock. Teammates are **forbidden** from creating `durable: true` crons ([CronCreateTool.ts](../../tools/ScheduleCronTool/CronCreateTool.ts):105-114) because teammates don't survive session restarts and would leave orphaned `agentId` targets; `CronListTool` and `CronDeleteTool` also scope teammates strictly to `task.agentId === ctx.agentId`.
- **Durable (`durable: true`):** Persisted to `<project>/.claude/scheduled_tasks.json` (total combined cap `MAX_JOBS = 50`). Invalid entries are silently skipped on read so one malformed manual edit never bricks the scheduler. Writing an empty task list writes `{ "tasks": [] }` instead of unlinking so `chokidar` sees a clean change event.

#### 5-Field Local Cron Parser and Asymmetric Deterministic Jitter

[utils/cron.ts](../../utils/cron.ts) implements a compact 5-field local-timezone cron parser (`minute hour dayOfMonth month dayOfWeek`, supporting `*`, `N`, `*/S`, `N-M`, `N-M/S`, comma lists, and `7` as Sunday alias). `computeNextCronRun()` walks forward bounded at 366 days using standard vixie-cron semantics: when both `dayOfMonth` and `dayOfWeek` are constrained, matching **either** fires (OR semantics); spring-forward DST gaps skip fixed-hour matches; and `formatLocalTime()` constructs `new Date(2000, 0, 1, hour, minute)` (January 1, never a DST transition) so displaying `2:30am` doesn't roll to `3:30am` on spring-forward day.

To eliminate thundering herds, [utils/cronTasks.ts](../../utils/cronTasks.ts):348-445 applies **asymmetric, deterministic jitter** derived by parsing the 8-hex-character `taskId` prefix as a `uint32` fraction `jitterFrac(taskId) ∈ [0, 1)` (stable across restarts, uniform across the fleet):

```ts
// utils/cronTasks.ts:381-445 (condensed)
export function jitteredNextCronRunMs(
  cron: string,
  fromMs: number,
  taskId: string,
  cfg: CronJitterConfig = DEFAULT_CRON_JITTER_CONFIG,
): number | null {
  const t1 = nextCronRunMs(cron, fromMs)
  if (t1 === null) return null
  const t2 = nextCronRunMs(cron, t1)
  if (t2 === null) return t1
  const jitter = Math.min(
    jitterFrac(taskId) * cfg.recurringFrac * (t2 - t1), // default: up to 10% of period
    cfg.recurringCapMs,                                 // capped at 15 min
  )
  return t1 + jitter
}

export function oneShotJitteredNextCronRunMs(
  cron: string,
  fromMs: number,
  taskId: string,
  cfg: CronJitterConfig = DEFAULT_CRON_JITTER_CONFIG,
): number | null {
  const t1 = nextCronRunMs(cron, fromMs)
  if (t1 === null) return null
  // Local minutes (not UTC!): in India (UTC+5:30), local :00 is UTC :30.
  if (new Date(t1).getMinutes() % cfg.oneShotMinuteMod !== 0) return t1
  const lead =
    cfg.oneShotFloorMs +
    jitterFrac(taskId) * (cfg.oneShotMaxMs - cfg.oneShotFloorMs) // default: 0..90s early
  return Math.max(t1 - lead, fromMs)
}
```

Notice the engineering elegance of that asymmetry:

- **Recurring jobs jitter *forward*** by up to 10% of their inter-fire interval (capped at 15 min), spreading hourly `0 * * * *` jobs across `[:00, :06)` while only shifting per-minute jobs by a few seconds.
- **One-shot jobs jitter *backward*** (up to 90 s early by default) whenever their computed **local** minute hits `minute % 30 === 0` (`:00` or `:30`, where humans round)—because firing "remind me at 3pm" 40 seconds *early* feels crisp, whereas firing it 4 minutes *late* breaks the user's expectation. Clamping to `Math.max(t1 - lead, fromMs)` prevents firing before creation time.
- **Live incident lever:** [utils/cronJitterConfig.ts](../../utils/cronJitterConfig.ts) pulls `tengu_kairos_cron_config` from GrowthBook on a 60-second refresh and validates it with an all-or-nothing Zod schema (`oneShotFloorMs <= oneShotMaxMs`, hard upper bounds of 30 minutes / 30 days). During a `:00` load spike, ops can push `{ oneShotMinuteMod: 15, oneShotMaxMs: 300000, oneShotFloorMs: 30000 }` to force every client off the mark within 60 seconds without shipping a build. `cronJitterConfig.ts` is deliberately split from `cronScheduler.ts` so the public Agent SDK bundle (`sdk.mjs`) never pulls in `growthbook.ts` and its transitive dependency graph.
- **7-day auto-expiry:** `DEFAULT_CRON_JITTER_CONFIG.recurringMaxAgeMs` defaults to 7 days (`isRecurringTaskAged()`). Aged recurring tasks fire one final time and then auto-delete—unless stamped `permanent: true` (an internal escape hatch not exposed to `CronCreateTool`, reserved for assistant mode's built-in catch-up/morning-checkin/dream tasks).
- **Behavioral defense-in-depth:** `buildCronCreatePrompt()` ([tools/ScheduleCronTool/prompt.ts](../../tools/ScheduleCronTool/prompt.ts):103-110) also instructs the model to pick off-minutes (`57 8 * * *` or `7 * * * *`) whenever the user's request is approximate, layering prompt-level spreading on top of scheduler-level jitter.

#### Multi-Session `O_EXCL` Lease Lock and the Scheduler Core

To guarantee only one Claude process per repository fires durable `.claude/scheduled_tasks.json` tasks, [utils/cronTasksLock.ts](../../utils/cronTasksLock.ts) implements an atomic lease lock at `.claude/scheduled_tasks.lock` storing `{ sessionId, pid, acquiredAt }`:

- Creation uses `writeFile(path, body, { flag: 'wx' })` (`O_EXCL`).
- If the file exists and `existing.sessionId === sessionId`, re-acquisition is idempotent—and after `--resume` (same `sessionId`, new `process.pid`), it refreshes the PID so peer sessions don't mistake it for a dead owner.
- If another live PID holds the lock (`isProcessRunning(existing.pid)`), `tryAcquireSchedulerLock()` returns `false`; passive sessions stay quiet and re-probe every `LOCK_PROBE_INTERVAL_MS = 5000` ms to take over automatically if the owner crashes.
- If the lock is corrupt or the PID is dead, the prober unlinks it and retries `wx` once—so concurrent recovery races still elect at most one winner.

[utils/cronScheduler.ts](../../utils/cronScheduler.ts) drives the 1-second `check()` loop (`.unref()`'d so `-p` one-shot runs still exit cleanly) with four production invariants:

1. **First-sight anchoring with batched `lastFiredAt` (lines 253-281, 358-369):** Recurring tasks anchor their first-sight schedule from `t.lastFiredAt ?? t.createdAt`. When recurring file tasks fire, `check()` reschedules them from `now` (never from `next`, avoiding catch-up storms after laptop sleep) and batches all IDs into one `markCronTasksFired()` write so a restarted process reconstructs the exact same `nextFireAt`.
2. **`inFlight` anti-double-fire set (lines 170, 335-343, 359-368):** Removing a fired one-shot or stamping `lastFiredAt` on disk is asynchronous and triggers a `chokidar` reload (`FILE_STABILITY_MS = 300`). Adding the ID to `inFlight` until the write settles prevents the next 1-second tick from double-firing.
3. **Mid-session killswitch (`isKilled`):** Checked on line 231 at the top of every tick (`() => !isKairosCronEnabled()`), stopping already-running schedulers immediately if GrowthBook flips off mid-session.
4. **Prompt-injection-hardened missed-task surfacing (`buildMissedTaskNotification`, lines 542-565):** On *initial* load only (never on mid-session `chokidar` reloads), overdue one-shot tasks are deleted from disk, parked at `nextFireAt = Infinity`, and formatted into a confirmation prompt that precedes the bodies with `"Do NOT execute this prompt yet. First use the AskUserQuestion tool..."` and wraps each prompt in a CommonMark fence **one backtick longer than the longest backtick run inside the prompt** (`'`'.repeat(Math.max(3, longestRun + 1))`) so a prompt containing ```` ``` ```` cannot break out of the fence.

Finally, the REPL and headless modes wire `createCronScheduler()` slightly differently:

- **REPL ([hooks/useScheduledTasks.ts](../../hooks/useScheduledTasks.ts)):** Mounts unconditionally (respecting React's Rules of Hooks), stores `isLoading` in a ref so turn transitions don't restart the watcher or drop the lock, tags fired prompts with `workload: WORKLOAD_CRON` (threaded to `cc_workload=` in the billing header for lower-priority inference QoS), routes `task.agentId` directly to `injectUserMessageToTeammate()`, and deletes orphaned teammate crons if the target teammate has terminated.
- **Headless / SDK ([cli/print.ts](../../cli/print.ts):2702-2734):** Enqueues fired prompts with `isMeta: true` and `workload: WORKLOAD_CRON`, then explicitly invokes `void run()` (safe during active turns because `run()`'s mutex no-ops and re-checks the queue on exit).

#### Proactive Mode, `<tick>`, and `SleepTool`

> [!NOTE]
> **Snapshot absence:** Both `tools/SleepTool/SleepTool.ts` and `proactive/index.ts` (gated behind `feature('PROACTIVE') || feature('KAIROS')`) are **absent from this source snapshot**. Only [tools/SleepTool/prompt.ts](../../tools/SleepTool/prompt.ts) is present on disk; the runtime mechanics below are reconstructed strictly from verified call sites in [tools.ts](../../tools.ts):25-27,234, [query.ts](../../query.ts):1566-1578, [cli/print.ts](../../cli/print.ts):361-363,535-545,1834-1856,2475-2485,3876-3890, [constants/prompts.ts](../../constants/prompts.ts):72-80,861-886, [types/textInputTypes.ts](../../types/textInputTypes.ts):283-292, [services/mcp/channelNotification.ts](../../services/mcp/channelNotification.ts):9, [utils/attachments.ts](../../utils/attachments.ts):1052-1056, [utils/handlePromptSubmit.ts](../../utils/handlePromptSubmit.ts):320, and [screens/REPL.tsx](../../screens/REPL.tsx):1655-1682.

Where cron schedules discrete wall-clock prompts, proactive mode turns the harness into an autonomous loop driven by two cooperating primitives:

1. **The `<tick>` heartbeat (`cli/print.ts:1834-1856, 2475-2485`):** When `proactiveModule.isProactiveActive()` is true and not paused, finishing a turn with an empty queue schedules a `setTimeout(..., 0)` (yielding one event-loop turn so pending stdin/interrupts win) that enqueues `<tick><localTime></tick>` at `priority: 'later', isMeta: true` and restarts `run()`. The proactive system prompt section ([constants/prompts.ts](../../constants/prompts.ts):866-886) explains that `<tick>` means *"you're awake, what now?"*—and mandates that if there is no useful action to take, the model **must call `Sleep`** rather than outputting idle narration text.
2. **Interruptible `SleepTool` (`tools/SleepTool/prompt.ts` + observed call sites):**
   - Unlike `Bash(sleep 60)`, `Sleep` holds no OS child process, is concurrency-safe with sibling tools, declares `interruptBehavior: 'cancel'` ([utils/handlePromptSubmit.ts](../../utils/handlePromptSubmit.ts):320) so a human message cleanly cancels the sleep without surfacing an error, and suppresses active-tool spinner clutter when it is the only running tool ([screens/REPL.tsx](../../screens/REPL.tsx):1655-1682).
   - While sleeping, `SleepTool` polls `hasCommandsInQueue()` and wakes within 1 second whenever a user prompt, channel notification, cron fire, or `<task-notification>` arrives ([services/mcp/channelNotification.ts](../../services/mcp/channelNotification.ts):9).
   - On wakeup, `query.ts:1566-1571` sees `sleepRan === true` and upgrades the mid-turn drain threshold from `'next'` to `'later'`, pulling the waking event straight into the current turn's attachments so the model handles it immediately while staying inside its 5-minute prompt-cache window ([tools/SleepTool/prompt.ts](../../tools/SleepTool/prompt.ts):17).

### Hidden Invariants & Failure Modes

- **Lazy scheduler startup:** `cronScheduler.start()` does not unconditionally load `chokidar` or create `.claude/scheduled_tasks.lock` on every CLI startup. Unless `assistantMode` or `hasCronTasksSync()` is true (or `dir` is passed by a daemon), it polls `getScheduledTasksEnabled()` once per second until `CronCreateTool.call()` flips the flag—keeping cold start free of watcher overhead ([utils/cronScheduler.ts](../../utils/cronScheduler.ts):463-498).
- **Session vs. file split when non-owner:** Even when a second Claude window loses the `.claude/scheduled_tasks.lock` race (`isOwner === false`), `check()` still ticks its own process-private `getSessionCronTasks()` (`durable: false`) because no peer session can see or double-fire them ([utils/cronScheduler.ts](../../utils/cronScheduler.ts):371-378).

---

## Putting the Layer Together

```mermaid
flowchart TD
  Spawners["Task Spawners (BashTool, AgentTool, RemoteAgentTask, DreamTask)"] -->|"setAppStateForTasks ?? setAppState"| Store["AppState.tasks (TaskStateBase + per-type state)"]
  Spawners -->|"O_NOFOLLOW / O_EXCL or symlink"| Disk["projectTemp/frozenSessionId/tasks/taskId.output"]
  Store -->|"1s tailFile / readFileRange"| Poll["TaskOutput poller and generateTaskAttachments()"]
  Disk --> Poll
  Poll -->|"TOCTOU-safe offset patch and eviction"| Store

  Cron["CronScheduler (scheduled_tasks.json + lock + jitter)"] -->|"priority: 'later', WORKLOAD_CRON"| Queue["messageQueueManager (now / next / later, agentId-scoped)"]
  Spawners -->|"Atomic notified=true + abortSpeculation"| Queue
  Proactive["Proactive tick and SleepTool wakeups (PROACTIVE/KAIROS)"] --> Queue

  Queue -->|"Mid-turn (query.ts: sleepRan ? 'later' : 'next')"| Loop["query() tool-round attachments"]
  Queue -->|"Between-turn (queueProcessor.ts / cli/print.ts)"| Turn["Next REPL or SDK turn"]
  Stop["stopTask() / TaskStopTool"] -->|"getTaskByType(type).kill()"| Store
  Stop -->|"bash kill suppresses XML -> emitTaskTerminatedSdk"| SdkQ["sdkEventQueue (task_started / task_progress / task_notification)"]
  Store -->|"registerTask -> task_started"| SdkQ
```

The seven task types and their operational contracts fit in one compact reference matrix:

```text
Type                |Pfx| Output Backing         | Kill Action          |Snap
--------------------+---+------------------------+----------------------+----
local_bash          |b  | Direct fd (5GB cap)    | treeKill + evict     |Yes
local_agent         |a/s| Symlink -> JSONL chain | abort() + 30s grace  |Yes
remote_agent        |r  | appendTaskOutput poll  | archive CCR+sidecar  |Yes
in_process_teammate |t  | Transcript (cap: 50)   | abort teammate loop  |Yes
dream               |d  | UI-only (notified end) | abort+lock rollback  |Yes
local_workflow      |w  | WORKFLOW_SCRIPTS gate  | call-site observed   |No
monitor_mcp         |m  | MONITOR_TOOL gate      | call-site observed   |No
```

---

## How This Snaps Into the Next Layer

Everything built in this chapter is the execution substrate that subagents and worktrees snap directly onto in [Chapter 18](18-subagents-context-forking-and-worktrees.md):

- **Subagent lifecycle & root task wiring:** [tools/AgentTool/runAgent.ts](../../tools/AgentTool/runAgent.ts):338 resolves `rootSetAppState = toolUseContext.setAppStateForTasks ?? toolUseContext.setAppState`, while [utils/forkedAgent.ts](../../utils/forkedAgent.ts):410-418 stubs `setAppState` to a no-op and preserves `setAppStateForTasks` across nested forks.
- **Background agent registration & resumption:** [tools/AgentTool/AgentTool.tsx](../../tools/AgentTool/AgentTool.tsx) and [tools/AgentTool/resumeAgent.ts](../../tools/AgentTool/resumeAgent.ts) call `registerAsyncAgent()`, `registerAgentForeground()`, `completeAgentTask()`, `failAgentTask()`, and `enqueueAgentNotification()` from [tasks/LocalAgentTask/LocalAgentTask.tsx](../../tasks/LocalAgentTask/LocalAgentTask.tsx), symlinking each agent's `<agentId>.output` file straight to its sidechain JSONL transcript so `Read` and `--resume` share one durable log.
- **Deterministic child cleanup:** [tools/AgentTool/runAgent.ts](../../tools/AgentTool/runAgent.ts):844-857 invokes `killShellTasksForAgent()` ([tasks/LocalShellTask/killShellTasks.ts](../../tasks/LocalShellTask/killShellTasks.ts))—and, under `feature('MONITOR_TOOL')`, `killMonitorMcpTasksForAgent()`—in its `finally` block, purging orphaned shells and queued notifications keyed to the exiting `agentId`.

In Chapter 18, we step up one level to see how `AgentTool`, `forkSubagent.ts`, sidechain transcripts, and `EnterWorktreeTool` turn these background task primitives into isolated, cache-sharing, resumable subagents.

---

## Reading Exercises & Code Checkpoints

1. **Trace the `setAppStateForTasks` boundary:** Run `rg -n "setAppStateForTasks" Tool.ts utils/ tools/ services/` and inspect every call site. Which call site in [utils/attachments.ts](../../utils/attachments.ts) uses `setAppStateForTasks`, and which one (around line 3447) still passes `toolUseContext.setAppState`? Explain why `getUnifiedTaskAttachments()` can safely use `toolUseContext.setAppState` when called from a subagent whose `setAppState` is a no-op—and what happens to `outputOffset` updates in that case.
2. **Verify the TOCTOU window in `applyTaskOffsetsAndEvictions`:** Read [utils/task/framework.ts](../../utils/task/framework.ts):158-249 alongside [tasks/LocalAgentTask/LocalAgentTask.tsx](../../tasks/LocalAgentTask/LocalAgentTask.tsx):412-432. Walk through the exact interleaving where `generateTaskAttachments()` starts reading an agent's output file, the agent finishes and flips `status: 'completed'` + `notified: true`, and then `applyTaskOffsetsAndEvictions()` executes. Confirm which guard prevents reverting `status` to `'running'`.
3. **Audit the XML `<status>` contract between producers and `cli/print.ts`:** Run `rg -n "enqueuePendingNotification|TASK_NOTIFICATION_TAG" tasks/ cli/print.ts`. Compare `startStallWatchdog()` in [tasks/LocalShellTask/LocalShellTask.tsx](../../tasks/LocalShellTask/LocalShellTask.tsx):76-94 against `cli/print.ts:2015-2093`. What exact bug would occur in VS Code's subagent/task panel if the stall watchdog included `<status>stalled</status>`?
4. **Compute cron jitter bounds by hand:** Read `jitteredNextCronRunMs()` and `oneShotJitteredNextCronRunMs()` in [utils/cronTasks.ts](../../utils/cronTasks.ts):362-445. Given a task ID starting with `80000000` (`jitterFrac = 0.5`) and `DEFAULT_CRON_JITTER_CONFIG`:
   - What exact delay does a recurring `0 * * * *` job receive?
   - What exact lead time does a one-shot `30 14 15 6 *` job receive, and why does `oneShotJitteredNextCronRunMs` inspect `new Date(t1).getMinutes()` rather than `getUTCMinutes()`?


---

<!-- chapters/18-subagents-context-forking-and-worktrees.md — https://reverseengineeringclaudecode.com/chapters/18-subagents-context-forking-and-worktrees -->

# Chapter 18 — Subagents, Context Forking, and Git Worktrees

> **Layer:** Layer 6 (Concurrency, Tasks, Subagents & Swarms)
> **Prerequisites:** [Chapter 02](02-the-tool-contract.md) (`ToolUseContext`), [Chapter 04](04-prompt-engineering-and-cache-boundaries.md) (prompt-cache boundaries, `SystemPrompt`), [Chapter 07](07-the-heartbeat-query-loop.md) (`query()`), [Chapter 08](08-session-envelope-query-engine-and-transcripts.md) (JSONL transcripts & `parentUuid` DAG), [Chapter 17](17-background-task-runtime.md) (`LocalAgentTask`, `TaskStateBase`, disk output)
> **Primary Source Files:**
> - [`utils/forkedAgent.ts`](../../utils/forkedAgent.ts) — `createSubagentContext()`, `CacheSafeParams`, and `runForkedAgent()` for isolated yet cache-sharing child loops (689 lines)
> - [`tools/AgentTool/loadAgentsDir.ts`](../../tools/AgentTool/loadAgentsDir.ts) — Markdown/JSON agent parsing, source-precedence merging, and memory-tool auto-injection (755 lines)
> - [`tools/AgentTool/builtInAgents.ts`](../../tools/AgentTool/builtInAgents.ts) — built-in agent registry (`general-purpose`, `Explore`, `Plan`, `statusline-setup`, `claude-code-guide`, `verification`) and feature/env gates (72 lines)
> - [`tools/AgentTool/forkSubagent.ts`](../../tools/AgentTool/forkSubagent.ts) — `FORK_AGENT`, `buildForkedMessages()`, `isInForkChild()`, and worktree path-translation notices (210 lines)
> - [`tools/AgentTool/runAgent.ts`](../../tools/AgentTool/runAgent.ts) — subagent `query()` driver: permission overrides, `CLAUDE.md`/git stripping, scoped MCP/hooks/skills, sidechain persistence, and `finally` teardown (973 lines)
> - [`tools/AgentTool/AgentTool.tsx`](../../tools/AgentTool/AgentTool.tsx) — `Agent` tool front door: sync/async/mid-run backgrounding, fork routing, worktree lifecycle, and handoff classification (1,397 lines)
> - [`tools/AgentTool/agentToolUtils.ts`](../../tools/AgentTool/agentToolUtils.ts) — `filterToolsForAgent()`, `resolveAgentTools()`, `finalizeAgentTool()`, `classifyHandoffIfNeeded()`, and `runAsyncAgentLifecycle()` (686 lines)
> - [`tools/AgentTool/resumeAgent.ts`](../../tools/AgentTool/resumeAgent.ts) — sidechain transcript replay, `ContentReplacementState` reconstruction, and worktree/fork restoration (265 lines)
> - [`utils/cwd.ts`](../../utils/cwd.ts) — `AsyncLocalStorage`-backed `runWithCwdOverride()` isolating concurrent working directories (32 lines)
> - [`utils/worktree.ts`](../../utils/worktree.ts) — Git and hook-based worktree creation, `.worktreeinclude` copying, sparse-checkout teardown, and fail-closed stale cleanup (1,519 lines)
> - [`tools/EnterWorktreeTool/EnterWorktreeTool.ts`](../../tools/EnterWorktreeTool/EnterWorktreeTool.ts) & [`tools/ExitWorktreeTool/ExitWorktreeTool.ts`](../../tools/ExitWorktreeTool/ExitWorktreeTool.ts) — mid-session worktree entry/exit and fail-closed change verification (127 & 329 lines)

---

## Why This Layer Exists

By the end of [Chapter 17](17-background-task-runtime.md), Claude Code can run `query()` loops, persist conversations to JSONL, and track background jobs in `AppState.tasks`. Spawning a *child* agent inside the same Node/Bun process immediately triggers four hard systems failures:

1. **Shared-process state corruption:** Passing the parent's `ToolUseContext` into a child lets it mutate `readFileState`, fire parent UI callbacks, deadlock on interactive permission prompts from the background, or orphan `PPID=1` child shells when `setAppState` is stubbed out.
2. **Prompt-cache cliffs on context inheritance:** Naively giving a child the parent's conversation history causes a single-byte drift—a GrowthBook flag warming up mid-session, a different tool schema, or divergent tool-result truncation—that invalidates the entire 100k-token prefix cache on every spawn.
3. **Composable personas and long-lived continuity:** Built-in specialists (`Explore`, `Plan`), custom `.claude/agents/*.md` files, and plugin agents need strict tool/permission boundaries, scoped MCP servers and hooks, mid-run foreground-to-background promotion, and the ability to resume a stopped worker days later from disk.
4. **Filesystem collisions under a single `process.cwd()`:** Two concurrent subagents editing files in the same working tree overwrite each other, and calling `process.chdir()` for one child yanks the working directory out from under the parent and every sibling.

This chapter reverse-engineers how Claude Code solves all four problems in dependency order: context isolation, cache-exact forking, agent registration and lifecycle, sidechain resumption, and Git worktree isolation.

---

## 1. Isolating Child State Without Breaking the Root Store (`utils/forkedAgent.ts`)

### The Problem

A subagent executes inside the parent's `query()` engine (`query.ts`), which reads and mutates a `ToolUseContext` ([Chapter 02](02-the-tool-contract.md)). If two concurrent subagents share the parent's `readFileState`, one child's `Read` tricks another child's `Edit` staleness check. If a background agent calls `parentContext.setAppState`, it corrupts REPL UI state; yet if `setAppState` is simply replaced with `() => {}`, two production bugs erupt immediately:

- Any background bash process the subagent launches is never registered in `AppState.tasks`, so when the subagent finishes or the session exits, that shell survives as an orphaned `PPID=1` zombie.
- Any permission classifier denial counter stored in `AppState` stops incrementing across retries, creating an infinite retry loop.

### The Real Implementation (`utils/forkedAgent.ts`, `utils/abortController.ts`)

`createSubagentContext()` (`utils/forkedAgent.ts:345-462`) is the single chokepoint that constructs an isolated `ToolUseContext` for both internal forks (`runForkedAgent`) and user-visible subagents (`runAgent`). By default, **every mutable field is cloned or stubbed**, and callers explicitly opt in to sharing callbacks via `SubagentContextOverrides`:

```ts
// utils/forkedAgent.ts:345-436 (abbreviated for focus)
export function createSubagentContext(
  parentContext: ToolUseContext,
  overrides?: SubagentContextOverrides,
): ToolUseContext {
  const abortController =
    overrides?.abortController ??
    (overrides?.shareAbortController
      ? parentContext.abortController
      : createChildAbortController(parentContext.abortController))

  const getAppState: ToolUseContext['getAppState'] = overrides?.getAppState
    ? overrides.getAppState
    : overrides?.shareAbortController
      ? parentContext.getAppState
      : () => {
          const state = parentContext.getAppState()
          if (state.toolPermissionContext.shouldAvoidPermissionPrompts) {
            return state
          }
          return {
            ...state,
            toolPermissionContext: {
              ...state.toolPermissionContext,
              shouldAvoidPermissionPrompts: true,
            },
          }
        }

  return {
    readFileState: cloneFileStateCache(
      overrides?.readFileState ?? parentContext.readFileState,
    ),
    nestedMemoryAttachmentTriggers: new Set<string>(),
    loadedNestedMemoryPaths: new Set<string>(),
    dynamicSkillDirTriggers: new Set<string>(),
    discoveredSkillNames: new Set<string>(),
    toolDecisions: undefined,
    contentReplacementState:
      overrides?.contentReplacementState ??
      (parentContext.contentReplacementState
        ? cloneContentReplacementState(parentContext.contentReplacementState)
        : undefined),
    abortController,
    getAppState,
    setAppState: overrides?.shareSetAppState
      ? parentContext.setAppState
      : () => {},
    // Task registration/kill must always reach the root store, even when
    // setAppState is a no-op — otherwise async agents' background bash tasks
    // are never registered and never killed (PPID=1 zombie).
    setAppStateForTasks:
      parentContext.setAppStateForTasks ?? parentContext.setAppState,
    // Async subagents whose setAppState is a no-op need local denial tracking
    // so the denial counter actually accumulates across retries.
    localDenialTracking: overrides?.shareSetAppState
      ? parentContext.localDenialTracking
      : createDenialTrackingState(),
    setInProgressToolUseIDs: () => {},
    updateFileHistoryState: () => {},
    updateAttributionState: parentContext.updateAttributionState,
    // UI callbacks nulled; new agentId and queryTracking { chainId, depth + 1 } ...
  }
}
```

Five deliberate design choices carry the load here:

1. **Split store channels (`setAppState` vs. `setAppStateForTasks`):** `setAppState` is stubbed to `() => {}` unless `shareSetAppState: true` (which `runAgent.ts:709` sets only for `!isAsync` foreground agents). Meanwhile, `setAppStateForTasks` threads `parentContext.setAppStateForTasks ?? parentContext.setAppState` straight through arbitrary nesting depths (`async → async`) to the root React/AppState store. Every task registration, frontmatter hook registration (`runAgent.ts:569`), todo cleanup, and child-shell kill uses `rootSetAppState = toolUseContext.setAppStateForTasks ?? toolUseContext.setAppState`.
2. **Local denial tracking (`utils/permissions/denialTracking.ts:7-45`):** When `shareSetAppState` is false, `localDenialTracking` receives a fresh `{ consecutiveDenials: 0, totalDenials: 0 }` object instead of relying on the stubbed `setAppState`, so `DENIAL_LIMITS` (`maxConsecutive: 3`, `maxTotal: 20`) still trips `shouldFallbackToPrompting()`.
3. **WeakRef-linked vs. unlinked abort trees (`utils/abortController.ts:68-99`):** By default, `createSubagentContext()` calls `createChildAbortController(parentContext.abortController)`, which links parent abort → child abort using `WeakRef` in *both* directions and module-scope `propagateAbort` / `removeAbortHandler` functions—so dropping a child without aborting it never leaks memory onto the parent's `AbortSignal`. By contrast, `runAgent.ts:524-528` explicitly passes an **unlinked** `new AbortController()` for async agents (`AgentTool.tsx:694-696` notes that pressing `ESC` on the main thread must not kill background agents; only explicit `TaskStop` / `chat:killAgents` does).
4. **Clone vs. fresh `readFileState`:** `createSubagentContext()` clones `readFileState` by default so forked agents inherit the parent's file-read freshness table. Non-forked subagents in `runAgent.ts:375-378` override it with `createFileStateCacheWithSizeLimit(READ_FILE_STATE_CACHE_SIZE)` so a fresh agent cannot edit a file it has never read itself.
5. **Fresh per-agent telemetry and tracking:** Every subagent gets a fresh `agentId` (`createAgentId()`), fresh memory/skill discovery `Set`s, `undefined` UI setters (`addNotification`, `setToolJSX`, `setStreamMode`, `setSDKStatus`, `openMessageSelector`), and a fresh `queryTracking: { chainId: randomUUID(), depth: (parentContext.queryTracking?.depth ?? -1) + 1 }`. `updateAttributionState` is intentionally shared (`utils/forkedAgent.ts:433-435`) because it uses functional `(prev => next)` updates that safely compose across concurrent callers.

### Hidden Invariants & Failure Modes

> [!WARNING]
> **Whale-session leaks & zombie teardown (`tools/AgentTool/runAgent.ts:816-859`):** Every resource a subagent allocates must be released in `runAgent()`'s `finally` block—otherwise long sessions spawning hundreds of agents leak memory and orphan OS processes:
> - `agentToolUseContext.readFileState.clear()` and `initialMessages.length = 0` release cloned file contents and inherited message arrays.
> - `rootSetAppState` deletes `prev.todos[agentId]` (`runAgent.ts:835-843`) so `TodoWrite` keys do not accumulate forever.
> - `killShellTasksForAgent(agentId, ...)` (`runAgent.ts:847`)—and under `feature('MONITOR_TOOL')`, `killMonitorMcpTasksForAgent()` (`runAgent.ts:849-857`)—reap any background processes the subagent spawned via `rootSetAppState`.
> - `clearSessionHooks(rootSetAppState, agentId)` and `mcpCleanup()` remove frontmatter hooks and inline MCP connections.

---

## 2. Context Forking and Byte-Exact Prompt-Cache Sharing (`forkSubagent.ts`, `utils/forkedAgent.ts`)

### The Problem

As established in [Chapter 04](04-prompt-engineering-and-cache-boundaries.md), Anthropic's prompt cache hashes the exact request prefix:

```
cache_key = H(system_prompt, tools, model, thinking_config, messages_prefix)
```

When the parent already has a 120k-token cached conversation and spawns three parallel workers to investigate different subsystems, a fresh subagent either loses all context or re-pays full cache-creation tokens three times. Worse, even if you *try* to share the parent's prefix, **five subtle divergences silently bust the cache**:

1. Re-calling `getSystemPrompt()` can return different bytes if a GrowthBook gate flipped between cold start and warm cache mid-session.
2. Re-assembling tools under the child's permission mode (`bubble` or `acceptEdits`) changes the serialized tool array at the first differing tool.
3. Disabling thinking (the default for normal subagents) or setting `maxOutputTokens` on non-adaptive models (which clamps `budget_tokens` in `claude.ts`) changes `thinkingConfig`.
4. Passing a fresh `ContentReplacementState` causes `enforceToolResultBudget()` to make different truncation decisions on inherited parent `tool_use_id`s, mutating earlier messages on the wire.
5. Giving sibling forks different `tool_result` texts for the parent's parallel `Agent` calls diverges the message prefix *before* the end of the shared turn.

### The Real Implementation (`utils/forkedAgent.ts`, `tools/AgentTool/forkSubagent.ts`, `tools/AgentTool/AgentTool.tsx`)

Claude Code has two distinct fork layers built on the same cache-preservation invariants:

- **Internal utility forks (`runForkedAgent()` in `utils/forkedAgent.ts:489-626`):** Used by post-turn helpers—session memory (`services/SessionMemory/sessionMemory.ts`), background agent summaries (`services/AgentSummary/agentSummary.ts`), prompt suggestions, and `/btw`. `handleStopHooks` snapshots the parent's exact `CacheSafeParams` (`systemPrompt`, `userContext`, `systemContext`, `toolUseContext`, `forkContextMessages`) via `saveCacheSafeParams()` (`utils/forkedAgent.ts:70-81`). Callers pass `skipCacheWrite: true` for fire-and-forget forks whose suffix no future request will read, and `runForkedAgent()` logs `tengu_fork_agent_query` with the measured `cacheHitRate` (`utils/forkedAgent.ts:631-689`).
- **Implicit subagent forks (`tools/AgentTool/forkSubagent.ts`):** Gated by `feature('FORK_SUBAGENT')` via `isForkSubagentEnabled()` (`forkSubagent.ts:32-39`), which returns `false` in Coordinator Mode and non-interactive sessions. When enabled, omitting `subagent_type` on `AgentTool` routes to the synthetic `FORK_AGENT` (`agentType: 'fork'`, `tools: ['*']`, `model: 'inherit'`, `permissionMode: 'bubble'`, `maxTurns: 200`, `getSystemPrompt: () => ''`) and forces **all** `AgentTool` spawns async (`forceAsync = isForkSubagentEnabled()`, `AgentTool.tsx:557`).

To guarantee near-100% cache hits across all sibling forks, Claude Code locks down all five components of the cache key:

1. **Frozen `renderedSystemPrompt` (`AgentTool.tsx:495-511`, `screens/REPL.tsx:2543, 2788`):** The REPL stashes the exact rendered `SystemPrompt` bytes on `toolUseContext.renderedSystemPrompt`. `AgentTool.call()` passes `override: { systemPrompt: toolUseContext.renderedSystemPrompt }` directly into `runAgent()`, falling back to `buildEffectiveSystemPrompt()` only if absent.
2. **Exact tool pool & thinking parity (`AgentTool.tsx:610-633`, `runAgent.ts:500-502, 667-695`):** `AgentTool` passes `availableTools: toolUseContext.options.tools` and `useExactTools: true`. Inside `runAgent()`, `useExactTools` bypasses `resolveAgentTools()`, keeps `model: 'inherit'`, and copies `toolUseContext.options.thinkingConfig` and `isNonInteractiveSession` verbatim instead of forcing `{ type: 'disabled' }`.
3. **Cloned `ContentReplacementState` (`utils/forkedAgent.ts:399-403`, `utils/toolResultStorage.ts:405-412`):** `createSubagentContext()` calls `cloneContentReplacementState(parentContext.contentReplacementState)`, duplicating both `seenIds: Set<string>` and `replacements: Map<string, string>`. When `query()` runs tool-result budget enforcement on inherited messages, every parent `tool_use_id` hits the exact same cached replacement decision while child mutations stay isolated from the parent.
4. **Identical placeholder `tool_result` blocks (`tools/AgentTool/forkSubagent.ts:91-169`):** When the parent emits N parallel `Agent` calls in one assistant turn, `buildForkedMessages()` ensures all N children serialize an identical wire prefix right up to their final directive block:

```ts
// tools/AgentTool/forkSubagent.ts:91-169 (abbreviated)
const FORK_PLACEHOLDER_RESULT = 'Fork started — processing in background'

export function buildForkedMessages(
  directive: string,
  assistantMessage: AssistantMessage,
): MessageType[] {
  const fullAssistantMessage: AssistantMessage = {
    ...assistantMessage,
    uuid: randomUUID(),
    message: {
      ...assistantMessage.message,
      content: [...assistantMessage.message.content],
    },
  }
  const toolUseBlocks = assistantMessage.message.content.filter(
    (block): block is BetaToolUseBlock => block.type === 'tool_use',
  )
  if (toolUseBlocks.length === 0) {
    return [createUserMessage({ content: [{ type: 'text', text: buildChildMessage(directive) }] })]
  }
  const toolResultBlocks = toolUseBlocks.map(block => ({
    type: 'tool_result' as const,
    tool_use_id: block.id,
    content: [{ type: 'text' as const, text: FORK_PLACEHOLDER_RESULT }],
  }))
  const toolResultMessage = createUserMessage({
    content: [
      ...toolResultBlocks,
      { type: 'text' as const, text: buildChildMessage(directive) },
    ],
  })
  return [fullAssistantMessage, toolResultMessage]
}
```

Every sibling receives `[...parentHistory, fullAssistantMessage(all tool_uses), user(identical placeholder tool_results..., <fork_boilerplate> + directive)]`. Only the final text block differs per child.

### Hidden Invariants & Failure Modes

> [!IMPORTANT]
> **Compaction-resistant recursive fork guard (`AgentTool.tsx:325-335`, `runAgent.ts:688-694`, `forkSubagent.ts:74-89`):** Because fork children *must* keep the `Agent` tool in their tool pool for cache-identical tool definitions, recursion cannot be stopped by filtering `Agent` out. Instead, `AgentTool.call()` enforces a two-tier runtime guard:
> 1. **Primary:** `toolUseContext.options.querySource === 'agent:builtin:fork'` (injected by `runAgent.ts:694` when `useExactTools` is true). This lives on `context.options`, so it survives autocompact rewriting the message list.
> 2. **Fallback:** `isInForkChild(toolUseContext.messages)` scans for `<${FORK_BOILERPLATE_TAG}>` inside user text blocks—catching paths where `querySource` was not threaded, though autocompact can erase the boilerplate message.

- **Two different incomplete-tool-call strategies:** `runForkedAgent()` (`utils/forkedAgent.ts:520-524`) explicitly **does not** call `filterIncompleteToolCalls()` because dropping a whole assistant message on partial tool batches orphans paired `tool_result`s (API 400); instead it lets `ensureToolResultPairing()` in `claude.ts` repair dangling calls identically to the main thread. By contrast, `runAgent.ts:370-372` *does* run `filterIncompleteToolCalls(forkContextMessages)` (`runAgent.ts:866-904`) before appending `promptMessages`, because `AgentTool`'s fork path constructs the complete paired `fullAssistantMessage + toolResultMessage` inside `promptMessages` while `toolUseContext.messages` still holds the parent's history up through the prior turn.
- **Worktree + fork path drift (`AgentTool.tsx:598-602`, `forkSubagent.ts:205-210`):** When a fork child also uses `isolation: 'worktree'`, `buildWorktreeNotice(getCwd(), worktreeInfo.worktreePath)` is pushed *after* the fork directive so the shared prefix remains untouched while instructing the child to translate inherited parent paths into its worktree root and re-read files before editing.

---

## 3. Agent Registry, Custom Definitions, and Execution Lifecycle

### The Problem

A single generic subagent prompt is both too expensive (sending 40 KB of `gitStatus` and `CLAUDE.md` to every read-only `Explore` call burns billions of tokens per week fleet-wide) and too rigid (teams want repo-local `.claude/agents/*.md` specialists with custom models, tools, persistent memory, hooks, and MCP servers). At the same time, user-defined agents must not bypass enterprise `strictPluginOnlyCustomization` policies, and long-running foreground agents need a clean escape hatch into the background without hanging or leaking resources.

### The Real Implementation (`builtInAgents.ts`, `loadAgentsDir.ts`, `agentToolUtils.ts`, `runAgent.ts`, `AgentTool.tsx`)

#### Built-in vs. Custom & Plugin Registration

`getBuiltInAgents()` (`tools/AgentTool/builtInAgents.ts:22-72`) assembles the baseline roster behind explicit env, build-time, and GrowthBook gates:

- **Blank-slate SDK escape hatch:** `CLAUDE_AGENT_SDK_DISABLE_BUILTIN_AGENTS` (only in non-interactive sessions) returns `[]`.
- **Coordinator swap:** Under `feature('COORDINATOR_MODE')` and `CLAUDE_CODE_COORDINATOR_MODE`, `builtInAgents.ts:35-43` lazily `require`s `coordinator/workerAgent.ts` *(absent from this snapshot; observed at call site)* to break a module-init cycle (`coordinatorMode → tools → AgentTool → builtInAgents`).
- **Standard roster:** Always includes `GENERAL_PURPOSE_AGENT` (`tools: ['*']`) and `STATUSLINE_SETUP_AGENT`. Adds `EXPLORE_AGENT` and `PLAN_AGENT` when `feature('BUILTIN_EXPLORE_PLAN_AGENTS')` and GrowthBook `tengu_amber_stoat` (default `true`) are enabled. Adds `CLAUDE_CODE_GUIDE_AGENT` for non-SDK entrypoints (`CLAUDE_CODE_ENTRYPOINT` not in `sdk-ts`/`sdk-py`/`sdk-cli`). Adds `VERIFICATION_AGENT` when `feature('VERIFICATION_AGENT')` and GrowthBook `tengu_hive_evidence` (default `false`) are active.

`getAgentDefinitionsWithOverrides` (`tools/AgentTool/loadAgentsDir.ts:296-393`, memoized by `cwd`, bypassed when `CLAUDE_CODE_SIMPLE` is truthy) loads Markdown files via `loadMarkdownFilesForSubdir('agents', cwd)`, silently skipping `.md` files lacking a `name` frontmatter field so co-located documentation does not emit parse errors (`loadAgentsDir.ts:321-326`). Plugin agents (`loadPluginAgents()`) load concurrently with `initializeAgentMemorySnapshots()` (under `feature('AGENT_MEMORY_SNAPSHOT')` + `isAutoMemoryEnabled()`).

When an agent defines `memory: 'user' | 'project' | 'local'`, both `parseAgentFromMarkdown()` (`loadAgentsDir.ts:662-674`) and `parseAgentFromJson()` (`loadAgentsDir.ts:455-467`, used for CLI `--agents` `flagSettings`) automatically inject `Write`, `Edit`, and `Read` into its tool list if explicit `tools` were declared, and append `loadAgentMemoryPrompt()` (`tools/AgentTool/agentMemory.ts`) inside its `getSystemPrompt()` closure. Note also that `isolation: 'remote'` is accepted only when `process.env.USER_TYPE === 'ant'` (`loadAgentsDir.ts:94-97, 608-610`).

All sources merge in `getActiveAgentsFromList()` (`loadAgentsDir.ts:193-221`) using last-write-wins precedence in a `Map<agentType, AgentDefinition>`:

```
built-in < plugin < userSettings < projectSettings < flagSettings < policy
(lowest)                                                          (highest)
```

#### Tool Filtering, Permission Overrides, and Token Trimming

Before entering `query()`, `runAgent()` resolves tools, permissions, and context:

1. **Tool filtering (`tools/AgentTool/agentToolUtils.ts:70-225`, `constants/tools.ts:36-88`):** `AgentTool.tsx:573-577` builds `workerTools` via `assembleToolPool()` using the worker's own permission mode (`selectedAgent.permissionMode ?? 'acceptEdits'`) so parent restrictions do not leak into workers (and avoiding a `runAgent → tools.ts` circular import). For non-fork subagents, `resolveAgentTools()` runs `filterToolsForAgent()`:
   - Always allows `mcp__*` tools and allows `ExitPlanMode` when `permissionMode === 'plan'`.
   - Strips `ALL_AGENT_DISALLOWED_TOOLS` (`TaskOutput`, `EnterPlanMode`, `ExitPlanMode`, `AskUserQuestion`, `TaskStop`, `Workflow` under `feature('WORKFLOW_SCRIPTS')`, plus `Agent` for non-ant builds—`constants/tools.ts:41` omits `AGENT_TOOL_NAME` when `process.env.USER_TYPE === 'ant'` to allow nested agents).
   - When `isAsync` is true, allows only `ASYNC_AGENT_ALLOWED_TOOLS` (`Read`, `Edit`, `Write`, `NotebookEdit`, `Glob`, `Grep`, shells, `WebSearch`, `WebFetch`, `TodoWrite`, `Skill`, `SyntheticOutput`, `ToolSearch`, `EnterWorktree`, `ExitWorktree`), with an explicit bypass for `isInProcessTeammate()` that adds `Agent` (sync-only) and `IN_PROCESS_TEAMMATE_ALLOWED_TOOLS`.
   - Applies the agent's `disallowedTools` and `tools` allowlist, extracting `Agent(worker, researcher)` specs into `allowedAgentTypes`.
2. **Permission wrapping (`runAgent.ts:415-498`):** `agentGetAppState()` overlays `agentDefinition.permissionMode` *unless* the parent is already in `bypassPermissions`, `acceptEdits`, or `auto` (under `feature('TRANSCRIPT_CLASSIFIER')`). It sets `shouldAvoidPermissionPrompts: true` for background agents that cannot show UI (`!canShowPermissionPrompts`, overridden to `false` by `permissionMode === 'bubble'`), sets `awaitAutomatedChecksBeforeDialog: true` for async agents that *can* prompt so automated hooks/classifiers settle before interrupting the user, and when `allowedTools` is supplied, preserves SDK `cliArg` allow rules while replacing `session` rules so parent approvals do not leak.
3. **Admin-trusted policy gate on MCP & hooks (`runAgent.ts:112-127, 557-575`):** Agents may declare additive `mcpServers` (either string references to existing memoized servers or inline `{ [name]: config }` definitions—only inline clients are torn down in `finally`) and frontmatter `hooks` (registered via `rootSetAppState` with `isAgent = true`, converting `Stop` hooks to `SubagentStop`). Under `isRestrictedToPluginOnly('mcp' | 'hooks')`, user-controlled agents are blocked while `isSourceAdminTrusted(agentDefinition.source)` (plugin, built-in, `policySettings`) still loads.
4. **Fleet-scale token trimming (`runAgent.ts:385-410`, `AgentTool.tsx:1351-1362`, `constants.ts:8-12`):** Read-only `Explore` and `Plan` agents set `omitClaudeMd: true` (kill-switch GrowthBook `tengu_slim_subagent_claudemd`, default `true`), strip `gitStatus` from `systemContext`, and belong to `ONE_SHOT_BUILTIN_AGENT_TYPES` so `mapToolResultToToolResultBlockParam()` omits the `agentId`/`SendMessage`/`<usage>` trailer—source comments attribute ~6–20 Gtok/week of fleet savings to these three trims alone.

#### Sync, Async, and Mid-Run Backgrounding (`AgentTool.tsx:555-1262`)

`AgentTool.call()` forces `shouldRunAsync` when `run_in_background`, `selectedAgent.background`, Coordinator Mode, `isForkSubagentEnabled()`, `feature('KAIROS')` `appState.kairosEnabled`, or `proactiveModule?.isProactiveActive()` is true (unless `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` is set).

- **Async-from-start (`AgentTool.tsx:686-764`):** Registers the task via `registerAsyncAgent()` (unlinked abort controller), optionally registers `name → agentId` in `AppState.agentNameRegistry` for `SendMessage` routing, launches `runAsyncAgentLifecycle()` (`agentToolUtils.ts:508-686`) detached inside `runWithAgentContext` + `wrapWithCwd`, and returns `{ status: 'async_launched', agentId, outputFile }`.
- **Foreground with live promotion (`AgentTool.tsx:765-1262`):** Immediately registers via `registerAgentForeground()` (passing `autoBackgroundMs = 120_000` if `CLAUDE_AUTO_BACKGROUND_TASKS` or GrowthBook `tengu_auto_background_agents` is enabled), then loops over `Promise.race([agentIterator.next(), backgroundPromise])`—creating `backgroundPromise` *once* outside the `while` loop so iterations do not pile up `.then()` callbacks (`AgentTool.tsx:811-832`). If the user presses `Ctrl+B` or auto-background fires, `AgentTool` races `agentIterator.return(undefined)` against `sleep(1000)` (so a hanging MCP teardown cannot stall backgrounding), spawns a fresh `runAgent({ ..., isAsync: true })` stream in the background, and immediately returns `async_launched`.

### Hidden Invariants & Failure Modes

> [!WARNING]
> **Status transition BEFORE handoff/git work (`gh-20236`, `agentToolUtils.ts:599-603, 641-645`, `AgentTool.tsx:953-957, 994-996`):** In both `runAsyncAgentLifecycle()` and the mid-run-backgrounded closure, `completeAsyncAgent()` / `killAsyncAgent()` MUST run *before* `classifyHandoffIfNeeded()` (an auto-mode classifier API call under `feature('TRANSCRIPT_CLASSIFIER')`) and `getWorktreeResult()` / `cleanupWorktreeIfNeeded()` (git subprocesses). Both embellishments can hang; transitioning status first unblocks `TaskOutput(block=true)` immediately.

- **Pending MCP startup race (`AgentTool.tsx:371-392`):** If `selectedAgent.requiredMcpServers` matches a client in `pending` state, `AgentTool.call()` polls `getAppState()` every 500 ms up to 30 s—exiting early the moment any required server transitions to `failed`—before checking `mcp.tools` (a connected but unauthenticated server exposes zero tools).
- **The `AgentTool.tsx` DCE cliff (`utils/toolResultStorage.ts:997-999`):** Note an extraordinary bundler scar documented in `utils/toolResultStorage.ts`: `AgentTool.tsx` sits at Bun's `feature()` dead-code-elimination complexity ceiling, where adding even a single net line can break `feature('TRANSCRIPT_CLASSIFIER')` evaluation in tests. Notice too that in this snapshot, `AgentTool.tsx` has its `USER_TYPE` checks constant-folded to `"external" === 'ant'` (lines 99, 435, 525, 1287) with an inline source map at line 1398.
- **Inference cache eviction hint (`agentToolUtils.ts:337-346`):** `finalizeAgentTool()` logs `tengu_cache_eviction_hint` (`scope: 'subagent_end'`, `last_request_id`) when a subagent completes so inference servers can reclaim its KV cache chain promptly.

---

## 4. Sidechain Transcripts and Resuming Agents Days Later (`resumeAgent.ts`, `sessionStorage.ts`)

### The Problem

Once a background agent completes, its `LocalAgentTask` can be evicted from `AppState.tasks`—or the user can close the CLI and resume the session days later. Calling `SendMessage({ to: agentId })` (or replying in the UI) needs to revive that exact worker with its prior conversation, original agent persona (`FORK_AGENT` vs. custom agent), working tree, and prompt-cache alignment intact.

### The Real Implementation (`utils/sessionStorage.ts`, `tools/AgentTool/resumeAgent.ts`, `tools/SendMessageTool/SendMessageTool.ts`)

#### Sidechain JSONL + Sidecar `.meta.json`

Every subagent writes two files under the parent session directory (`utils/sessionStorage.ts:247-303`):

```
<projectDir>/<sessionId>/subagents/[<subdir>/]agent-<agentId>.jsonl
<projectDir>/<sessionId>/subagents/[<subdir>/]agent-<agentId>.meta.json
```

`runAgent()` persists `initialMessages` fire-and-forget before entering `query()`, then awaits `recordSidechainTranscript([message], agentId, lastRecordedUuid)` (`runAgent.ts:735-745, 792-805`, calling `insertMessageChain(..., isSidechain=true)` in `utils/sessionStorage.ts:1451-1462`) for every `assistant`, `user`, `progress`, and `compact_boundary` message—updating `lastRecordedUuid` on every non-`progress` message for O(1) incremental parent chaining. Alongside it, `writeAgentMetadata()` (`sessionStorage.ts:283-290`) writes `{ agentType, worktreePath?, description? }` into `.meta.json`. Using a sidecar file avoids changing the JSONL schema while ensuring that resuming a `fork` agent does not silently degrade to `general-purpose`.

#### The Resume Pipeline (`tools/AgentTool/resumeAgent.ts:42-265`)

`SendMessageTool.ts:800-874` handles messages addressed to a subagent by name (`appState.agentNameRegistry`) or raw ID (`toAgentId()`): if the task is `running`, it calls `queuePendingMessage()`; if the task is stopped *or already evicted from `AppState.tasks`*, it invokes `resumeAgentBackground()` (also called from `screens/REPL.tsx:3556`):

```ts
// tools/AgentTool/resumeAgent.ts:63-98 (abbreviated)
const [transcript, meta] = await Promise.all([
  getAgentTranscript(asAgentId(agentId)),
  readAgentMetadata(asAgentId(agentId)),
])
if (!transcript) {
  throw new Error(`No transcript found for agent ID: ${agentId}`)
}
const resumedMessages = filterWhitespaceOnlyAssistantMessages(
  filterOrphanedThinkingOnlyMessages(
    filterUnresolvedToolUses(transcript.messages),
  ),
)
const resumedReplacementState = reconstructForSubagentResume(
  toolUseContext.contentReplacementState,
  resumedMessages,
  transcript.contentReplacements,
)
const resumedWorktreePath = meta?.worktreePath
  ? await fsp.stat(meta.worktreePath).then(
      s => (s.isDirectory() ? meta.worktreePath : undefined),
      () => undefined,
    )
  : undefined
if (resumedWorktreePath) {
  // Bump mtime so stale-worktree cleanup doesn't delete a just-resumed worktree (#22355)
  const now = new Date()
  await fsp.utimes(resumedWorktreePath, now, now)
}
```

Step by step, `resumeAgentBackground()` repairs every invariant needed for a clean restart:

1. **Transcript & replacement-state replay:** `getAgentTranscript()` (`utils/sessionStorage.ts:4190-4236`) finds the latest leaf matching `agentId && isSidechain`, walks `buildConversationChain()`, and returns `{ messages, contentReplacements }`. `resumeAgent.ts:70-74` strips unresolved `tool_use`s, orphaned thinking-only messages, and whitespace-only assistant messages. `reconstructForSubagentResume()` (`utils/toolResultStorage.ts:1001-1012`) rebuilds `ContentReplacementState` from the sidechain's recorded replacements, gap-filling fork-inherited `mustReapply` entries from the parent's live `replacements` map so resumed forks preserve prompt-cache stability.
2. **Best-effort worktree survival + `utimes` touch (`#22355`):** If `meta.worktreePath` was deleted externally, `stat()` falls back to the parent CWD rather than crashing. If it still exists, `fsp.utimes()` refreshes its `mtime` so the 30-day stale-worktree sweeper cannot reap a freshly resumed worktree.
3. **Persona and fork restoration (`resumeAgent.ts:100-195`):** Skips `filterDeniedAgents` (the original spawn already passed permission checks). If `meta?.agentType === 'fork'`, it selects `FORK_AGENT`, restores `renderedSystemPrompt`, sets `useExactTools: true`, and crucially passes **`forkContextMessages: undefined`** (`resumeAgent.ts:187-189`)—because the sidechain JSONL *already* persisted the original parent history slice; re-supplying it would emit duplicate `tool_use` IDs and trigger an API 400. It also passes `worktreePath` and `description` back into `runAgent()` so `runAgent`'s `writeAgentMetadata()` overwrite does not erase them.
4. **Execution:** Re-registers the task via `registerAsyncAgent()` on `rootSetAppState` (preserving existing name-registry mappings) and launches `runAsyncAgentLifecycle()` inside `runWithAgentContext({ invocationKind: 'resume', ... })` and `runWithCwdOverride()`.

### Hidden Invariants & Failure Modes

- **Why `SendMessageTool` validates raw IDs with `toAgentId()` (`SendMessageTool.ts:804-805, 846-849`):** Unregistered teammate names must fall through to the swarm mailbox router ([Chapter 19](19-agent-teams-swarms-and-coordinator-mode.md)), never triggering a failed sidechain transcript lookup.
- **Disk-write-before-yield UI merge (`agentToolUtils.ts:556-570`):** Because `runAgent()` awaits `recordSidechainTranscript()` *before* `yield message`, a UI pane attaching mid-run (`task.retain`) can read the JSONL prefix from disk in parallel while appending live yielded messages as a guaranteed suffix, deduplicating cleanly by UUID.

---

## 5. Isolating Concurrent Edits with Git Worktrees (`utils/cwd.ts`, `utils/worktree.ts`, `EnterWorktreeTool`, `ExitWorktreeTool`)

### The Problem

A single Node/Bun process has one global `process.cwd()`. Calling `process.chdir()` for a worktree-isolated subagent would corrupt every sibling agent and the parent REPL. Conversely, when a *user* invokes `EnterWorktree` (or `--worktree` at CLI startup), the session *does* want to switch directories, propagate local configs and gitignored secrets (`.env`, `settings.local.json`), avoid multi-second `git fetch` stalls in monorepos, and refuse to destroy uncommitted work on exit.

### The Real Implementation

#### Concurrent Directory Isolation via `AsyncLocalStorage` (`utils/cwd.ts`)

Subagents with `isolation: 'worktree'` (or `feature('KAIROS')` explicit `cwd`) **never** touch `process.chdir()` or `currentWorktreeSession`. Instead, [`utils/cwd.ts`](../../utils/cwd.ts) scopes `getCwd()` per async execution tree:

```ts
// utils/cwd.ts:1-21
import { AsyncLocalStorage } from 'async_hooks'
import { getCwdState, getOriginalCwd } from '../bootstrap/state.js'

const cwdOverrideStorage = new AsyncLocalStorage<string>()

export function runWithCwdOverride<T>(cwd: string, fn: () => T): T {
  return cwdOverrideStorage.run(cwd, fn)
}

export function pwd(): string {
  return cwdOverrideStorage.getStore() ?? getCwdState()
}
```

`AgentTool.tsx:618-641` wraps both async and sync agent execution in `runWithCwdOverride(cwdOverridePath, fn)`. Equally subtle: when `worktreeInfo` or `cwd` is active on a non-fork agent, `AgentTool` intentionally passes `override: undefined` (`AgentTool.tsx:624-626`) so `runAgent()` computes `getAgentSystemPrompt()` *inside* `wrapWithCwd`, where `getCwd()` returns the worktree path rather than the parent repo root.

#### Worktree Creation, Monorepo Speedups, and VCS Hooks (`utils/worktree.ts`)

1. **Slug allowlist & injective D/F flattening (`utils/worktree.ts:48-87, 208-227`):** `validateWorktreeSlug()` runs synchronously before any git command, hook, or `chdir`. It enforces `<= 64` chars and validates every `/`-separated segment against `/^[a-zA-Z0-9._-]+$/`, rejecting `.`, `..`, leading/trailing `/`, and drive prefixes. `flattenSlug()` then replaces `/` with `+` for both `.claude/worktrees/<flat>` and branch `worktree-<flat>`. Because `+` is outside the allowlist, the mapping is injective and eliminates two real hazards: Git ref directory/file conflicts (`worktree-user` vs. `worktree-user/feature`) and nested worktree directories where removing a parent deletes a child's uncommitted files.
2. **Hook-first VCS abstraction (`utils/worktree.ts:715-728, 912-919, 1260-1272`):** Every entry point (`createWorktreeForSession`, `createAgentWorktree`, and the `--worktree --tmux` fast-path `execIntoTmuxWorktree`) checks `hasWorktreeCreateHook()` first, delegating to `WorktreeCreate` / `WorktreeRemove` hooks so non-Git VCS systems (Sapling, Mercurial, Jujutsu) work without Git.
3. **Fast creation & sparse checkout (`utils/worktree.ts:235-375`):**
   - *Fast resume:* Reads `.git` directly via `readWorktreeHeadSha()` instead of spawning `git rev-parse HEAD` (~15 ms spawn overhead saved).
   - *Zero-fetch local base:* Resolves `refs/remotes/origin/<defaultBranch>` from disk via `resolveRef()` before falling back to `git fetch`—avoiding a 6–8 s local commit-graph scan observed on 210k-file / 16M-object repos. When `fetch` *is* needed (or for PR refs parsed by `parsePRReference()`), `GIT_NO_PROMPT_ENV` (`GIT_TERMINAL_PROMPT=0`, `GIT_ASKPASS=''`, `stdin: 'ignore'`) prevents headless credential hangs.
   - *Orphan branch reset:* Uses `git worktree add -B <branch>` instead of a separate `git branch -D`.
   - *Transactional sparse checkout:* When `settings.worktree.sparsePaths` is set, runs `--no-checkout` → `sparse-checkout set --cone` → `checkout HEAD`. If either follow-up command fails, `tearDown()` immediately runs `git worktree remove --force` so a subsequent invocation's fast-resume does not treat an empty directory as a healthy worktree (`worktree.ts:336-366`).
4. **Post-creation setup (`utils/worktree.ts:391-624`):**
   - Copies `.claude/settings.local.json` into the worktree.
   - Configures `core.hooksPath` to the main repo's `.husky` or `.git/hooks` (skipping the `git config` subprocess when `parseGitConfigValue()` already matches). Under `feature('COMMIT_ATTRIBUTION')`, also dynamically imports `utils/postCommitAttribution.ts` *(absent from snapshot; observed at `worktree.ts:606-609`)* to install the attribution hook directly into the worktree's `.husky/`—because `bun install` runs `husky`'s prepare script, which resets shared `core.hooksPath` back to relative `.husky`!
   - Symlinks opt-in `settings.worktree.symlinkDirectories` (guarding each entry with `containsPathTraversal()`).
   - Copies gitignored files matching `.worktreeinclude` (`copyWorktreeIncludeFiles()`, `worktree.ts:391-504`) using `git ls-files --others --ignored --exclude-standard --directory`—collapsing massive ignored trees like `node_modules/` into single entries (cutting ~500k entries / ~7 s down to ~100 ms) and running a scoped second `ls-files` only on collapsed dirs matching a literal or anchored glob prefix.

#### Subagent Cleanup vs. 30-Day Sweeper (`utils/worktree.ts:902-1173`, `AgentTool.tsx:590-685`)

`createAgentWorktree('agent-' + earlyAgentId.slice(0, 8))` resolves the repo via `findCanonicalGitRoot(getCwd())` (not `findGitRoot()`) so agents spawned *inside* a session worktree still create sibling worktrees under the main repository's `.claude/worktrees/` where cleanup can find them. On completion, `cleanupWorktreeIfNeeded()` (`AgentTool.tsx:644-685`, made idempotent by nulling `worktreeInfo`) keeps hook-based worktrees unconditionally and calls `hasWorktreeChanges(worktreePath, headCommit)` (`worktree.ts:1144-1173`, fail-closed: any non-zero git exit returns `true`). If clean, it deletes the worktree and branch and strips `worktreePath` from `.meta.json`; if dirty or committed, it preserves the worktree and returns `{ worktreePath, worktreeBranch }` to the parent.

When the parent crashes or is killed before in-process cleanup runs, `cleanupStaleAgentWorktrees(cutoffDate)` (`worktree.ts:1058-1136`) sweeps only slugs matching `EPHEMERAL_WORKTREE_PATTERNS` (`/^agent-a[0-9a-f]{7}$/`, workflow `wf_*`, `bridge-*`, `job-*`—never user-named worktrees), skips the active session worktree and entries newer than `cutoffDate`, and requires **both** `git --no-optional-locks status --porcelain -uno` and `git rev-list --max-count=1 HEAD --not --remotes` to exit 0 with empty stdout before removing.

#### Session-Level `EnterWorktreeTool` and `ExitWorktreeTool`

Both tools are deferred (`shouldDefer: true`, discovered via `ToolSearchTool`—[Chapter 15](15-model-context-protocol-mcp.md)):

- **`EnterWorktreeTool` (`EnterWorktreeTool.ts:77-119`):** Rejects if `getCurrentWorktreeSession()` is already set, resolves `findCanonicalGitRoot()` so entering a worktree from inside a manual worktree still roots cleanly, calls `createWorktreeForSession()`, mutates process-wide `process.chdir()` + `setCwd()` + `setOriginalCwd()`, persists `saveWorktreeState()`, and invalidates CWD-dependent caches (`clearSystemPromptSections()`, `clearMemoryFileCaches()`, `getPlansDirectory.cache.clear()`).
- **`ExitWorktreeTool` (`ExitWorktreeTool.ts:67-321`):** Marks `isDestructive(input)` true for `action: 'remove'` and enforces two fail-closed guards inside `validateInput()`:
  1. **Session-scope guard:** Refuses as a no-op if `getCurrentWorktreeSession()` is null—never touching worktrees created manually or in a prior session.
  2. **Fail-closed change check (`countWorktreeChanges()`, `ExitWorktreeTool.ts:79-113`):** Returns `null` on any git error *or* when `git status` succeeds without an `originalHeadCommit` (the hook-wrapping-git case where commits cannot be counted). For `action: 'remove'` without `discard_changes: true`, both `null` and any `changedFiles > 0 || commits > 0` refuse deletion and report exact counts.

### Hidden Invariants & Failure Modes

> [!WARNING]
> **The `--worktree` vs. mid-session `projectRoot` distinction (`ExitWorktreeTool.ts:122-146, 244-250`):** Startup `--worktree` (`setup.ts`) sets *both* `originalCwd` and `projectRoot` to the realpath'd worktree and re-reads hooks via `updateHooksConfigSnapshot()`. Mid-session `EnterWorktreeTool` sets `originalCwd` but intentionally leaves `projectRoot` unchanged to preserve stable project identity. On exit, `ExitWorktreeTool` detects which mode created the worktree via `const projectRootIsWorktree = getProjectRoot() === getOriginalCwd()` (immune to `BashTool` `cd` mutations on `getCwd()` and symlink mismatch on raw `session.worktreePath`), restoring `projectRoot` and re-snapshotting hooks only when startup `--worktree` changed them.

- **`process.chdir()` does not update `getCwd()` (`utils/worktree.ts:838-846`):** `cleanupWorktree()` passes explicit `{ cwd: originalCwd }` to `execFileNoThrowWithCwd()` for `git worktree remove` and `git branch -D` (after `sleep(100)` so git releases locks), because `execFileNoThrow()` defaults to `getCwd()` which could point inside the directory being deleted or a non-repo dir the model `cd`'d into.
- **CLI `--worktree --tmux` fast-path (`utils/worktree.ts:1180-1519`):** Runs early in `entrypoints/cli.tsx` before loading `main.tsx`, supports iTerm2 control mode (`tmux -CC`, disabled by `--tmux=classic` or nested `$TMUX`), detects prefix keybinding collisions with Claude shortcuts, and for `USER_TYPE === 'ant'` inside `claude-cli-internal` auto-splits dev panes (`bun run watch` / `bun run start`).

---

## Putting the Layer Together

```mermaid
flowchart TD
  Caller["Parent query() calls AgentTool.call()"] --> Route{"teamName & name?"}
  Route -->|"Yes (Ch 19)"| Swarm["spawnTeammate() -> teammate_spawned"]
  Route -->|"No"| Defs["loadAgentsDir + builtInAgents (or FORK_AGENT)"]
  Defs --> WT{"isolation: 'worktree'?"}
  WT -->|"Yes"| CreateWT["createAgentWorktree('agent-' + id) + runWithCwdOverride()"]
  WT -->|"No"| ForkCheck{"isForkPath?"}
  CreateWT --> ForkCheck
  ForkCheck -->|"Yes (Byte-Exact Cache)"| ForkPrep["renderedSystemPrompt + useExactTools + buildForkedMessages()"]
  ForkCheck -->|"No (Isolated Specialist)"| NormPrep["resolveAgentTools() + agent prompt + Explore/Plan trims"]
  ForkPrep --> Ctx["createSubagentContext(): clone state, setAppStateForTasks -> root"]
  NormPrep --> Ctx
  Ctx --> Loop["runAgent() -> query() + sidechain JSONL + .meta.json"]
  Loop -->|"Sync (Ctrl+B / 120s race)"| Done["finalizeAgentTool() + cleanupWorktreeIfNeeded()"]
  Loop -->|"Async / Promoted"| AsyncLife["runAsyncAgentLifecycle(): complete -> handoff -> worktree -> notify"]
  Disk["subagents/agent-ID.jsonl + .meta.json"] -.->|"SendMessage(to: id)"| Resume["resumeAgentBackground(): reconstruct state + utimes()"]
  Loop -.-> Disk
  Resume --> AsyncLife
```

The four subagent execution shapes trade isolation against cache reuse and UI reachability:

```
Mode            | readFileState | Abort    | setAppState | Tasks | Cache
----------------+---------------+----------+-------------+-------+----------
Sync subagent   | fresh cache   | shared   | shared      | root  | cold/own
Async subagent  | fresh cache   | unlinked | no-op       | root  | cold/own
Forked subagent | parent clone  | unlinked | no-op       | root  | ~100% hit
Worktree child  | fresh/clone*  | per-mode | per-mode    | root  | +ALS cwd
(* clone when combined with fork, plus buildWorktreeNotice after directive)
```

> [!NOTE]
> **Snapshot-Absent Modules Observed via Call Sites Only:** Three modules referenced by this layer are **absent from this checkout** and documented solely from their call sites:
> - `types/message.ts` — message union types (`Message`, `AssistantMessage`, `UserMessage`, `SystemCompactBoundaryMessage`) imported across `utils/forkedAgent.ts`, `tools/AgentTool/runAgent.ts`, and `tools/AgentTool/forkSubagent.ts`.
> - `coordinator/workerAgent.ts` — lazily `require`d inside `tools/AgentTool/builtInAgents.ts:38-41` under `feature('COORDINATOR_MODE')` and `CLAUDE_CODE_COORDINATOR_MODE`.
> - `utils/postCommitAttribution.ts` — dynamically imported inside `utils/worktree.ts:606-609` under `feature('COMMIT_ATTRIBUTION')` to install `.husky` attribution hooks in fresh worktrees.

---

## How This Snaps Into the Next Layer

Everything in [Chapter 19 — Agent Teams, Swarms, and Coordinator Mode](19-agent-teams-swarms-and-coordinator-mode.md) builds directly on the primitives we just dissected:

1. **Teammate spawn intercept (`tools/AgentTool/AgentTool.tsx:284-316`):** Before any subagent resolution runs, `AgentTool.call()` checks `if (teamName && name)` and hands off to `spawnTeammate()` in [`tools/shared/spawnMultiAgent.ts`](../../tools/shared/spawnMultiAgent.ts) (blocking teammates from spawning nested teammates to keep `TeamFile.members` flat, and blocking in-process teammates from spawning background agents at `AgentTool.tsx:272-280, 361-363`).
2. **Multi-turn in-process teammates (`utils/swarm/inProcessRunner.ts:1035-1069`):** Rather than running one `runAgent()` call and exiting, `inProcessRunner.ts` drives `runAgent()` inside a persistent `while (!abortController.signal.aborted && !shouldExit)` mailbox loop—passing `canShowPermissionPrompts: true`, `preserveToolUseResults: true`, and a persistent `teammateReplacementState` so repeated turns over `allMessages` do not reset `ContentReplacementState` and bust the teammate's prompt cache.
3. **Teammate & Coordinator tool gates (`constants/tools.ts:77-88, 107-112`, `tools/AgentTool/agentToolUtils.ts:100-112`):** `filterToolsForAgent()` unlocks `IN_PROCESS_TEAMMATE_ALLOWED_TOOLS` (`TaskCreate`, `TaskGet`, `TaskList`, `TaskUpdate`, `SendMessage`, plus crons under `feature('AGENT_TRIGGERS')`) when `isInProcessTeammate()` is true, while Coordinator Mode restricts the leader to `COORDINATOR_MODE_ALLOWED_TOOLS` (`Agent`, `TaskStop`, `SendMessage`, `SyntheticOutput`) and swaps the built-in agent roster inside `builtInAgents.ts:35-43`.

---

## Reading Exercises & Code Checkpoints

1. **Trace the root-store bypass across nesting levels:** Run `rg -n "setAppStateForTasks" .` and verify every consumer that relies on `setAppStateForTasks ?? setAppState`. What breaks in `runAgent.ts:568-575` and `runAgent.ts:839-847` if a nested async subagent falls back to its own `toolUseContext.setAppState`?
2. **Audit every prompt-cache key component for fork children:** Compare `runAgentParams` in [`tools/AgentTool/AgentTool.tsx`](../../tools/AgentTool/AgentTool.tsx) (`lines 603-636`) against `agentOptions` in [`tools/AgentTool/runAgent.ts`](../../tools/AgentTool/runAgent.ts) (`lines 667-695`) and `CacheSafeParams` in [`utils/forkedAgent.ts`](../../utils/forkedAgent.ts) (`lines 46-68`). Verify why setting `maxOutputTokens` on `runForkedAgent()` can bust the cache on older models (`utils/forkedAgent.ts:96-103`) and why `resumeAgent.ts:187-189` sets `forkContextMessages: undefined`.
3. **Verify fail-closed worktree deletion invariants:** Inspect `countWorktreeChanges()` in [`tools/ExitWorktreeTool/ExitWorktreeTool.ts`](../../tools/ExitWorktreeTool/ExitWorktreeTool.ts) (`lines 79-113`), `hasWorktreeChanges()` (`lines 1144-1173`), and `cleanupStaleAgentWorktrees()` (`lines 1058-1136`) in [`utils/worktree.ts`](../../utils/worktree.ts). Confirm what each function returns when a `git` subprocess exits non-zero or when a hook-based worktree wraps a Git repository without `originalHeadCommit`.
4. **Trace `SendMessage` → sidechain resume:** Read [`tools/SendMessageTool/SendMessageTool.ts`](../../tools/SendMessageTool/SendMessageTool.ts) (`lines 800-874`) alongside [`tools/AgentTool/resumeAgent.ts`](../../tools/AgentTool/resumeAgent.ts) (`lines 63-195`). Confirm how a stopped agent that has already been evicted from `AppState.tasks` is distinguished from a swarm teammate name and restored from `<sessionId>/subagents/agent-<id>.jsonl` + `.meta.json`.


---

<!-- chapters/19-agent-teams-swarms-and-coordinator-mode.md — https://reverseengineeringclaudecode.com/chapters/19-agent-teams-swarms-and-coordinator-mode -->

# Chapter 19 — Agent Teams, Swarms, and Coordinator Mode: Multi-Agent IPC, Permission Bubbling, and Pure Orchestration

> **Layer:** Layer 6 (Concurrency, Tasks, Subagents & Swarms)
> **Prerequisites:** [Chapter 11](11-the-permission-engine.md), [Chapter 17](17-background-task-runtime.md), [Chapter 18](18-subagents-context-forking-and-worktrees.md)
> **Primary Source Files:**
> - [utils/swarm/teamHelpers.ts](../../utils/swarm/teamHelpers.ts) — `TeamFile` roster persistence, path sanitization, worktree teardown, and `SIGINT`/`SIGTERM` orphan cleanup
> - [tools/TeamCreateTool/TeamCreateTool.ts](../../tools/TeamCreateTool/TeamCreateTool.ts) & [tools/TeamDeleteTool/TeamDeleteTool.ts](../../tools/TeamDeleteTool/TeamDeleteTool.ts) — Team lifecycle tools, task-list alignment, and active-member cleanup guards
> - [utils/teammate.ts](../../utils/teammate.ts) & [utils/teammateContext.ts](../../utils/teammateContext.ts) — Three-tier identity resolution (`AsyncLocalStorage` → `dynamicTeamContext` → `AppState`) and zero-polling idle waiters
> - [utils/swarm/backends/registry.ts](../../utils/swarm/backends/registry.ts), [utils/swarm/backends/InProcessBackend.ts](../../utils/swarm/backends/InProcessBackend.ts), [utils/swarm/backends/PaneBackendExecutor.ts](../../utils/swarm/backends/PaneBackendExecutor.ts), [utils/swarm/backends/TmuxBackend.ts](../../utils/swarm/backends/TmuxBackend.ts), & [utils/swarm/backends/ITermBackend.ts](../../utils/swarm/backends/ITermBackend.ts) — Polymorphic teammate execution across in-process, `tmux`, and native `iTerm2` panes
> - [tools/shared/spawnMultiAgent.ts](../../tools/shared/spawnMultiAgent.ts), [utils/swarm/spawnInProcess.ts](../../utils/swarm/spawnInProcess.ts), & [utils/swarm/inProcessRunner.ts](../../utils/swarm/inProcessRunner.ts) — Spawning pipeline, persistent multi-turn teammate loop, dual abort controllers, and isolated compaction
> - [utils/teammateMailbox.ts](../../utils/teammateMailbox.ts), [tools/SendMessageTool/SendMessageTool.ts](../../tools/SendMessageTool/SendMessageTool.ts), & [hooks/useInboxPoller.ts](../../hooks/useInboxPoller.ts) — File-locked JSON mailboxes, structured control messages, priority wakeups, and graceful shutdown
> - [utils/swarm/leaderPermissionBridge.ts](../../utils/swarm/leaderPermissionBridge.ts), [utils/swarm/permissionSync.ts](../../utils/swarm/permissionSync.ts), [hooks/toolPermission/handlers/swarmWorkerHandler.ts](../../hooks/toolPermission/handlers/swarmWorkerHandler.ts), & [hooks/useSwarmPermissionPoller.ts](../../hooks/useSwarmPermissionPoller.ts) — Cross-async and cross-process permission bubbling with rule write-back
> - [coordinator/coordinatorMode.ts](../../coordinator/coordinatorMode.ts), [utils/toolPool.ts](../../utils/toolPool.ts), & [utils/systemPrompt.ts](../../utils/systemPrompt.ts) — Coordinator Mode gates, surgical tool stripping, worker-context injection, and pure-orchestrator prompt framing

## Why This Layer Exists

[Chapter 18](18-subagents-context-forking-and-worktrees.md) gave the harness subagents: a parent calls `AgentTool`, a child executes one isolated prompt—optionally in a forked cache-sharing context or a dedicated git worktree—and returns a single final result. That RPC model works well for narrow research or one-off refactors, but it breaks down as soon as work requires sustained multi-agent collaboration:

1. **Persistent, peer-addressable workers.** A researcher, an implementer, and a verifier often need to stay alive across multiple rounds, exchange findings directly, claim follow-up work from a shared task list, and negotiate graceful shutdown instead of exiting after one turn.
2. **Execution-mode polymorphism.** Inside `tmux` or `iTerm2`, developers want live split panes where each teammate is a visible terminal process. Inside VS Code's integrated terminal, SSH, or headless `-p` runs, there is no pane multiplexer—teammates must run concurrently inside the leader's own runtime without global-state collisions.
3. **Centralized permission governance.** In [Chapter 11](11-the-permission-engine.md), `useCanUseTool` assumed the agent asking for permission owns the interactive terminal. A teammate running either as a background async loop or inside a separate pane cannot safely prompt on a hidden TTY; its `ask` decisions must bubble up to the leader's interactive terminal with full diff/command rendering and propagate allow/deny decisions back without corrupting the leader's permission mode.
4. **Role separation through tool restriction.** When a single top-level model holds `Bash`, `Edit`, and `Read` alongside `Agent`, it constantly drifts into doing ad-hoc file reads and edits itself, serializing work and filling its own context window. Sometimes the architecture must strip editing tools from the leader outright and convert it into a pure orchestrator.

Two independent feature gates guard the subsystems in this chapter:

- **Agent Teams / Swarms** are gated by `isAgentSwarmsEnabled()` ([utils/agentSwarmsEnabled.ts:24-44](../../utils/agentSwarmsEnabled.ts)): always active when `process.env.USER_TYPE === 'ant'`, while external builds require *both* an explicit opt-in (`CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` env var or `--agent-teams` CLI flag) *and* the GrowthBook killswitch `tengu_amber_flint` (defaulting `true`).
- **Coordinator Mode** is dead-code-eliminated at bundle time behind `feature('COORDINATOR_MODE')` and enabled at runtime by `CLAUDE_CODE_COORDINATOR_MODE` ([coordinator/coordinatorMode.ts:36-41](../../coordinator/coordinatorMode.ts)).

This chapter traces the stack bottom-up: team rosters and identity first, then execution backends, then file-locked mailboxes, then permission bubbling, and finally Coordinator Mode.

---

## 1. Team Formation, Flat Rosters, and Dual Identity Resolution

### The Problem

Once two or more Claude instances cooperate on a task, the harness needs a shared source of truth on disk and an unambiguous answer to *"which agent am I?"* inside every helper function (`writeToMailbox`, `isTeammate`, `hasPermissionsToUseTool`). Two constraints make this harder than storing a global `currentAgentId`:

- **Mixed-process topology.** A pane-based teammate runs in its own OS process with its own `process.env` and `AppState`, whereas an in-process teammate shares the *leader's* Node/Bun process, event loop, and reactive `AppState` store. Mutating a module global for an in-process teammate would corrupt every concurrent teammate and the leader itself.
- **Directory and process leaks.** Every team writes a roster directory (`~/.claude/teams/{team}/`) and a task directory (`~/.claude/tasks/{team}/`), and may spawn external `tmux`/`iTerm2` panes plus git worktrees. If the leader exits via `SIGINT` without calling `TeamDelete`, orphaned panes keep running and stale directories accumulate on disk forever.

### The Real Implementation

#### Deterministic IDs and the `TeamFile` Roster

Team identities avoid random UUIDs in favor of deterministic `agentName@teamName` strings produced by `formatAgentId()` ([utils/agentId.ts:38-40](../../utils/agentId.ts)). Because `@` is the structural delimiter parsed by `parseAgentId()`, `sanitizeAgentName()` ([utils/swarm/teamHelpers.ts:108-110](../../utils/swarm/teamHelpers.ts)) strips `@` to `-` before forming an ID, and `sanitizeName()` (`teamHelpers.ts:100-102`) lowercases and replaces non-alphanumeric characters with `-` for filesystem paths and tmux window names.

When the leader invokes `TeamCreateTool` ([tools/TeamCreateTool/TeamCreateTool.ts:128-237](../../tools/TeamCreateTool/TeamCreateTool.ts)), it enforces a strict **one team per leader** rule (`appState.teamContext?.teamName`), resolves name collisions by falling back to `generateWordSlug()` (`lines 64-72`), and writes `~/.claude/teams/{sanitizedName}/config.json` (`TeamFile`, defined in [utils/swarm/teamHelpers.ts:64-90](../../utils/swarm/teamHelpers.ts)):

```ts
// utils/swarm/teamHelpers.ts:64-90
export type TeamFile = {
  name: string
  description?: string
  createdAt: number
  leadAgentId: string
  leadSessionId?: string // Actual session UUID of the leader (for discovery)
  hiddenPaneIds?: string[] // Pane IDs that are currently hidden from the UI
  teamAllowedPaths?: TeamAllowedPath[] // Paths all teammates can edit without asking
  members: Array<{
    agentId: string
    name: string
    agentType?: string
    model?: string
    prompt?: string
    color?: string
    planModeRequired?: boolean
    joinedAt: number
    tmuxPaneId: string
    cwd: string
    worktreePath?: string
    sessionId?: string
    subscriptions: string[]
    backendType?: BackendType
    isActive?: boolean // false when idle, undefined/true when active
    mode?: PermissionMode // Current permission mode for this teammate
  }>
}
```

Right after `writeTeamFileAsync()`, `TeamCreateTool` performs three load-bearing wiring steps (`TeamCreateTool.ts:177-212`):

1. **Session-end cleanup registration:** `registerTeamForSessionCleanup(finalTeamName)` records the team in a `Set` hosted inside `bootstrap/state.ts` (`teamHelpers.ts:554-562`, avoiding cross-shard test leaks and fixing `gh-32730` where undeleted teams lingered forever).
2. **Task-list unification (`Team = Project = TaskList`):** `resetTaskList(taskListId)`, `ensureTasksDir(taskListId)`, and `setLeaderTeamName(taskListId)` align the leader's task directory (`~/.claude/tasks/{sanitizedName}/`) with what pane-based teammates compute from `--team-name`. Without `setLeaderTeamName()`, the leader would fall through to `getSessionId()` and write tasks to a directory teammates never see (`TeamCreateTool.ts:188-191`).
3. **Leader identity omission:** `TeamCreateTool` stores the team in `AppState.teamContext` and **deliberately refrains from setting `CLAUDE_CODE_AGENT_ID` or `dynamicTeamContext`** (`TeamCreateTool.ts:224-228`). Setting an agent ID on the leader would make `isTeammate()` return `true`, breaking inbox polling and permission routing.

#### Three-Tier Identity Resolution

Every swarm helper queries [utils/teammate.ts](../../utils/teammate.ts), which layers [utils/teammateContext.ts](../../utils/teammateContext.ts) (`AsyncLocalStorage<TeammateContext>`) above process-scoped CLI state:

```ts
// utils/teammate.ts:88-131
export function getAgentId(): string | undefined {
  const inProcessCtx = getTeammateContext()
  if (inProcessCtx) return inProcessCtx.agentId
  return dynamicTeamContext?.agentId
}

export function getTeamName(teamContext?: {
  teamName: string
}): string | undefined {
  const inProcessCtx = getTeammateContext()
  if (inProcessCtx) return inProcessCtx.teamName
  if (dynamicTeamContext?.teamName) return dynamicTeamContext.teamName
  return teamContext?.teamName
}

export function isTeammate(): boolean {
  // In-process teammates run within the same process
  const inProcessCtx = getTeammateContext()
  if (inProcessCtx) return true
  // Tmux teammates require both agent ID and team name
  return !!(dynamicTeamContext?.agentId && dynamicTeamContext?.teamName)
}
```

For pane-based teammates, [main.tsx:1187-1211](../../main.tsx) validates that `--agent-id`, `--agent-name`, and `--team-name` appear together (exiting with status `1` if partial) and populates `dynamicTeamContext` via `setDynamicTeamContext()`. Before React's first render, `computeInitialTeamContext()` ([utils/swarm/reconnection.ts:23-66](../../utils/swarm/reconnection.ts)) reads `config.json` synchronously so `AppState.teamContext` is hydrated on mount without `useEffect` flicker. For in-process teammates, `runWithTeammateContext()` ([utils/teammateContext.ts:59-64](../../utils/teammateContext.ts)) binds a per-teammate store across every `await` inside that teammate's execution loop.

#### Teardown and Crash Cleanup

[tools/TeamDeleteTool/TeamDeleteTool.ts:71-135](../../tools/TeamDeleteTool/TeamDeleteTool.ts) refuses to disband a team if any non-lead member still has `isActive !== false` (`lines 81-98`), forcing the leader to run graceful shutdown first. Once clear, `cleanupTeamDirectories()` ([utils/swarm/teamHelpers.ts:641-683](../../utils/swarm/teamHelpers.ts)) reads `config.json` *before* deleting it, tears down any member `worktreePath` via `git worktree remove --force` (falling back to `rm -rf`, `lines 492-551`), removes both `~/.claude/teams/{team}` and `~/.claude/tasks/{team}`, and calls `unregisterTeamForSessionCleanup()` to avoid double cleanup.

If the leader dies ungracefully (`SIGINT`/`SIGTERM`), `cleanupSessionTeams()` ([utils/swarm/teamHelpers.ts:576-634](../../utils/swarm/teamHelpers.ts)) runs during `gracefulShutdown`. Crucially, it runs `killOrphanedTeammatePanes()` *before* `cleanupTeamDirectories()`—dynamically importing `registry.ts` and `detection.ts` so shutdown code doesn't bloat startup imports—because deleting directories while pane processes are still alive leaves runaway terminals behind.

### Hidden Invariants & Failure Modes

- **Flat rosters only:** In [tools/AgentTool/AgentTool.tsx:266-280](../../tools/AgentTool/AgentTool.tsx), passing both `team_name` and `name` triggers `spawnTeammate()`, *unless* the caller is already a teammate (`isTeammate()`), which throws immediately: `TeamFile.members` is a flat array with a single `leadAgentId`, so nested teammates would have no provenance. Likewise, `isInProcessTeammate()` forbids `run_in_background: true` subagents because their lifecycle is bound to the leader's process.
- **Identity-keyed vs. pane-keyed removal:** All in-process teammates share the sentinel `tmuxPaneId: 'in-process'`. Removing one must call `removeMemberByAgentId()` ([utils/swarm/teamHelpers.ts:326-348](../../utils/swarm/teamHelpers.ts)) rather than `removeMemberFromTeam(teamName, tmuxPaneId)` (`lines 285-317`), which would evict whichever in-process teammate appears first in `members`.

---

## 2. Execution Backends: In-Process Runner vs. `tmux` and `iTerm2` Panes

### The Problem

Spawning a teammate via `AgentTool` (`name` + `team_name`) must work identically across three wildly different terminal environments: inside `tmux`, inside macOS `iTerm2`, and everywhere else (plain terminals, VS Code, CI, headless `-p` runs). Each environment carries nasty operational edge cases:

- `Shell.ts` mutates `process.env.TMUX` after startup when initializing Claude's shell socket, and users click away to other panes mid-session.
- Spawning three teammates in parallel inside a single assistant message fires three concurrent split-pane commands that race on pane geometry and shell prompt initialization.
- `tmux` login shells drop environment variables (`CLAUDE_CODE_USE_BEDROCK`, `HTTPS_PROXY`, CA bundles) unless explicitly forwarded.
- Inside a single process, hundreds of turns across dozens of concurrent teammates can blow up heap RSS and shatter prompt caches if message mirrors or tool-result budgets aren't bounded.

### The Real Implementation

#### Startup Mode Snapshot and Backend Detection

Just like `hooksConfigSnapshot.ts` from Chapter 13, [utils/swarm/backends/teammateModeSnapshot.ts:56-87](../../utils/swarm/backends/teammateModeSnapshot.ts) snapshots `teammateMode` (`'auto' | 'tmux' | 'in-process'`) once during startup (CLI `--teammate-mode` overriding global config) so mid-session config edits cannot silently mix backends.

[utils/swarm/backends/registry.ts:351-398](../../utils/swarm/backends/registry.ts) decides between in-process and pane execution in `isInProcessEnabled()`:

1. Non-interactive (`-p`) sessions **always** force in-process (`lines 354-359`).
2. Explicit `'in-process'` or `'tmux'` snapshot modes win directly (`lines 364-368`).
3. In `'auto'` mode, if a prior spawn already fell back (`inProcessFallbackActive`), stay in-process (`lines 372-377`); otherwise use panes only if `isInsideTmuxSync() || isInITerm2()` (`lines 380-383`).

Look closely at the battle scars in [utils/swarm/backends/detection.ts](../../utils/swarm/backends/detection.ts):

- **Module-load capture (`lines 10-19`):** `ORIGINAL_USER_TMUX` and `ORIGINAL_TMUX_PANE` are read once at module load time before `Shell.ts` can overwrite `process.env.TMUX`, and before the user switches panes.
- **No `tmux display-message` fallback (`lines 32-34`):** Running `tmux display-message` succeeds whenever *any* tmux server exists on the machine—even if Claude was launched in a plain terminal—so `isInsideTmux()` trusts `ORIGINAL_USER_TMUX` exclusively.
- **Probing the iTerm2 Python API (`lines 112-120`):** `isIt2CliAvailable()` executes `it2 session list` instead of `it2 --version`, because `--version` exits `0` even when iTerm2's Python API is disabled in preferences, which would cause `session split` to fail later with no recovery.

When pane execution is chosen, `detectAndGetBackend()` ([utils/swarm/backends/registry.ts:136-254](../../utils/swarm/backends/registry.ts)) resolves in strict priority order: (1) inside `tmux` → native `TmuxBackend`; (2) inside `iTerm2` with `it2` (unless user chose `preferTmuxOverIterm2`) → native `ITermBackend`; (3) `tmux` installed anywhere → external `TmuxBackend` running on an isolated PID-scoped socket `-L claude-swarm-${process.pid}` ([utils/swarm/constants.ts:12-14](../../utils/swarm/constants.ts), [TmuxBackend.ts:87-91](../../utils/swarm/backends/TmuxBackend.ts)); (4) nothing available → throws platform-specific install instructions. In `'auto'` mode, `handleSpawn()` ([tools/shared/spawnMultiAgent.ts:1053-1069](../../tools/shared/spawnMultiAgent.ts)) catches that throw, calls `markInProcessFallback()`, and falls through to `handleSpawnInProcess()` transparently.

#### Pane-Based Spawning (`TmuxBackend`, `ITermBackend`, `PaneBackendExecutor`)

Both [TmuxBackend.ts:28-53](../../utils/swarm/backends/TmuxBackend.ts) and [ITermBackend.ts:15-31](../../utils/swarm/backends/ITermBackend.ts) serialize parallel pane splits through an in-memory promise-chain mutex (`acquirePaneCreationLock()`). Inside `tmux`, the first teammate splits horizontally alongside the leader (rebalancing to `main-vertical` with the leader pinned at 30% width, `TmuxBackend.ts:343-358`); outside `tmux`, teammates tile evenly in `claude-swarm:swarm-view`. `TmuxBackend` waits `PANE_SHELL_INIT_DELAY_MS = 200` (`lines 31-37`) so slow shells (`starship`, `oh-my-zsh`) finish initializing before `tmux send-keys` types the launch command. `ITermBackend` splits explicitly from the leader's UUID parsed out of `ITERM_SESSION_ID` (`wXtYpZ:UUID`, `ITermBackend.ts:63-73`) via `-s` so user pane clicks don't misplace splits, and sets `supportsHideShow = false` (whereas `TmuxBackend` hides panes via `break-pane` into a detached `claude-hidden` session and restores them via `join-pane`, `TmuxBackend.ts:281-361`).

The command injected into the new pane (`tools/shared/spawnMultiAgent.ts:401-444` and [utils/swarm/backends/PaneBackendExecutor.ts:114-158](../../utils/swarm/backends/PaneBackendExecutor.ts)) has three subtle invariants:

1. **Model alias resolution (`spawnMultiAgent.ts:93-101`):** `resolveTeammateModel()` expands `'inherit'` from agent frontmatter to the leader's model (fixing `gh-31069`, where literal `--model inherit` failed at the API) and otherwise defaults via `getHardcodedTeammateModelFallback()` ([utils/swarm/teammateModel.ts:8-10](../../utils/swarm/teammateModel.ts)) to the provider-aware Opus 4.6 model ID (`CLAUDE_OPUS_4_6_CONFIG[getAPIProvider()]`).
2. **Permission-mode safety (`utils/swarm/spawnUtils.ts:45-56`):** `buildInheritedCliFlags()` propagates `--dangerously-skip-permissions`, `--permission-mode acceptEdits`, or `--permission-mode auto` (`spawnMultiAgent.ts:226-231`), *except* when `planModeRequired` is true—plan mode always takes precedence over bypass permissions.
3. **Explicit env forwarding (`utils/swarm/spawnUtils.ts:96-146`):** `buildInheritedEnvVars()` builds `env CLAUDECODE=1 CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 ...` and selectively forwards `TEAMMATE_ENV_VARS`—including `CLAUDE_CODE_USE_BEDROCK`/`VERTEX`/`FOUNDRY` (fixing GitHub `#23561`), `ANTHROPIC_BASE_URL`, `CLAUDE_CODE_REMOTE` paired with `CLAUDE_CODE_REMOTE_MEMORY_DIR` (so remote auto-memory isn't accidentally disabled), and `HTTP(S)_PROXY`/`NODE_EXTRA_CA_CERTS` (so teammates route through the parent container's upstream MITM proxy).

Finally, `handleSpawnSplitPane()` calls `registerOutOfProcessTeammateTask()` (`spawnMultiAgent.ts:760-834`), registering a synthetic `in_process_teammate` task in the leader's `AppState.tasks` whose `abortController` listener invokes `getBackendByType(backendType).killPane()`. That single adapter makes external tmux/iTerm2 teammates appear in the leader's background-tasks pill and respond uniformly to task kills. It then writes the teammate's initial prompt into `~/.claude/teams/{team}/inboxes/{name}.json` (`lines 513-521`).

#### In-Process Spawning and the Persistent Runner Loop

In-process teammates follow a two-step launch: [utils/swarm/spawnInProcess.ts:104-216](../../utils/swarm/spawnInProcess.ts) creates an **independent** `AbortController` (not linked to the leader's turn controller, so pressing Escape on the leader does not kill running teammates), constructs `TeammateContext`, registers an `InProcessTeammateTaskState` in `AppState.tasks`, and registers a `registerCleanup()` hook. Then `startInProcessTeammate()` ([utils/swarm/inProcessRunner.ts:1544-1552](../../utils/swarm/inProcessRunner.ts)) launches `runInProcessTeammate()` fire-and-forget.

Notice two memory-retention defenses right at the launch boundary:

```ts
// tools/shared/spawnMultiAgent.ts:927-932
      // Strip messages: the teammate never reads toolUseContext.messages
      // (it builds its own history via allMessages in inProcessRunner).
      // Passing the parent's full conversation here would pin it for the
      // teammate's lifetime, surviving /clear and auto-compact.
      toolUseContext: { ...context, messages: [] },
```

```ts
// utils/swarm/inProcessRunner.ts:1544-1552
export function startInProcessTeammate(config: InProcessRunnerConfig): void {
  // Extract agentId before the closure so the catch handler doesn't retain
  // the full config object (including toolUseContext) while the promise is
  // pending - which can be hours for a long-running teammate.
  const agentId = config.identity.agentId
  void runInProcessTeammate(config).catch(error => {
    logForDebugging(`[inProcessRunner] Unhandled error in ${agentId}: ${error}`)
  })
}
```

Inside `runInProcessTeammate()` ([utils/swarm/inProcessRunner.ts:883-1534](../../utils/swarm/inProcessRunner.ts)), the runner constructs a full system prompt appended with `TEAMMATE_SYSTEM_PROMPT_ADDENDUM` ([utils/swarm/teammatePromptAddendum.ts](../../utils/swarm/teammatePromptAddendum.ts)—reminding the model that plain assistant text is invisible to peers and it *must* call `SendMessage`), pins `resolvedAgentDefinition.permissionMode = 'default'` (later overridden per-iteration from `task.permissionMode` so the leader can cycle an individual teammate's mode with `Shift+Tab`, `lines 1144-1154`), and injects team-essential tools (`SendMessage`, `TeamCreate`, `TeamDelete`, `TaskCreate`/`Get`/`List`/`Update`). Those extra tools survive subagent filtering because `filterToolsForAgent()` ([tools/AgentTool/agentToolUtils.ts:100-112](../../tools/AgentTool/agentToolUtils.ts)) checks `isAgentSwarmsEnabled() && isInProcessTeammate()` and exempts `IN_PROCESS_TEAMMATE_ALLOWED_TOOLS` ([constants/tools.ts:77-88](../../constants/tools.ts), which also includes `CronCreate`/`Delete`/`List` under `feature('AGENT_TRIGGERS')`) plus `AgentTool` for synchronous subagents.

The core execution loop (`inProcessRunner.ts:1048-1417`) wraps `runAgent()` inside nested `AsyncLocalStorage` scopes—`runWithTeammateContext(teammateContext, () => runWithAgentContext(agentContext, ...))`—and layers four production invariants on top of [Chapter 18](18-subagents-context-forking-and-worktrees.md)'s `runAgent()`:

1. **Dual AbortControllers (`lines 1053-1063, 1204-1219, 1292-1309`):** Each turn allocates a fresh `currentWorkAbortController` stored on `task`. Pressing Escape while viewing a teammate aborts only `currentWorkAbortController`: the loop breaks out of `runAgent()`, appends `ERROR_MESSAGE_USER_ABORT` to the teammate's scrollback, transitions the teammate to `isIdle: true` with `idleReason: 'interrupted'`, and keeps the teammate alive waiting for its next prompt. Only the outer lifecycle `abortController` terminates the teammate.
2. **Cache-preserving `teammateReplacementState` (`lines 1035-1045`):** Because `runAgent()` is called once per prompt over an accumulating `allMessages` array containing *full* unpersisted tool results, creating a fresh `contentReplacementState` on each iteration would make holistic "replace-globally-largest" decisions that diverge from earlier turns' frozen-first choices—mutating the wire prefix and causing a prompt-cache miss on every follow-up message. Persisting one `teammateReplacementState` across iterations (and resetting it only after full compaction at `lines 1111-1113`) keeps the wire prefix stable.
3. **Isolated auto-compaction (`lines 1071-1126`):** When `tokenCountWithEstimation(allMessages)` crosses `getAutoCompactThreshold()`, the runner builds an `isolatedContext` with a cloned `FileStateCache` (`cloneFileStateCache`) and cleared `onCompactProgress`/`setStreamMode` callbacks so compacting a teammate neither wipes the leader's read-file cache nor hijacks the leader's compaction spinner. It then mirrors the compacted array into `task.messages` (`lines 1121-1125`).
4. **Capped UI transcript mirror (`tasks/InProcessTeammateTask/types.ts:89-121`):** `task.messages` exists purely for the leader's zoomed transcript view, while the true conversation lives in `allMessages` and on disk. Every update goes through `appendCappedMessage()` with `TEAMMATE_MESSAGES_UI_CAP = 50`.

> [!WARNING]
> **Production scar — the 36.8 GB swarm burst:** The comment on `TEAMMATE_MESSAGES_UI_CAP` ([tasks/InProcessTeammateTask/types.ts:96-101](../../tasks/InProcessTeammateTask/types.ts)) documents why a UI mirror cannot hold unbounded history: BigQuery telemetry analysis (`2026-03-20`) showed ~20 MB RSS per agent at 500+ turns and ~125 MB per concurrent agent in swarm bursts, culminating in whale session `9a990de8` launching 292 agents in two minutes and hitting **36.8 GB RSS**. Capping `task.messages` at 50 entries and truncating terminal tasks to their last message (`inProcessRunner.ts:1440`, `spawnInProcess.ts:288-290`) eliminated that duplicate heap copy.

### Hidden Invariants & Failure Modes

- **Zero-polling idle barrier:** Headless/print mode and orchestration code wait for in-process teammates via `waitForTeammatesToBecomeIdle()` ([utils/teammate.ts:238-292](../../utils/teammate.ts)), which attaches `onIdleCallbacks` directly onto each running task inside `setAppState`. Crucially, inside the `setAppState` updater it re-checks `if (task.isIdle) onIdle()` (`lines 279-280`) to close the race where a teammate finishes between the initial snapshot scan and callback registration.
- **Single-emit SDK bookend guard:** Both `killInProcessTeammate()` (`spawnInProcess.ts:245-247, 308-315`) and `runInProcessTeammate()`'s normal/error exit paths (`inProcessRunner.ts:1425-1431, 1479-1482`) pre-set `notified: true` and guard `emitTaskTerminatedSdk()` on `task.status === 'running'`. Otherwise a force-kill racing with loop exit would flip `killed → completed` and emit duplicate SDK `task_notification` bookends.

---

## 3. File-Locked Mailboxes, Protocol Multiplexing, and Idle/Wakeup Semantics

### The Problem

A team can mix pane-based processes and in-process async loops, and *both* need to exchange plain DMs, broadcasts, plan approvals, permission prompts, mode switches, and shutdown handshakes. An in-memory queue won't cross OS process boundaries; raw `fs.writeFile` will lose updates under concurrent writers; a naive FIFO inbox lets noisy peer-to-peer chatter starve a leader's shutdown request; and a single inbox file read by both an attachment collector and a background poller can eat JSON control frames as raw LLM prompt text.

### The Real Implementation

#### File-Locked JSON Inboxes

All teammate IPC flows through [utils/teammateMailbox.ts](../../utils/teammateMailbox.ts), storing one JSON array per agent at `~/.claude/teams/{safeTeam}/inboxes/{safeAgentName}.json` (`getInboxPath`, `lines 56-66`). Every mutation (`writeToMailbox`, `markMessageAsReadByIndex`, `markMessagesAsRead`, `markMessagesAsReadByPredicate`) acquires `${inboxPath}.lock` through [utils/lockfile.ts](../../utils/lockfile.ts)—a lazy `require('proper-lockfile')` shim that keeps `graceful-fs`'s ~8 ms `fs` monkey-patching off cold-start paths like `--help`.

```ts
// utils/teammateMailbox.ts:35-41, 148-184 (abridged)
const LOCK_OPTIONS = {
  retries: { retries: 10, minTimeout: 5, maxTimeout: 100 },
}

// Ensure the inbox file exists before locking (proper-lockfile requires the file to exist)
try {
  await writeFile(inboxPath, '[]', { encoding: 'utf-8', flag: 'wx' })
} catch (error) {
  if (getErrnoCode(error) !== 'EEXIST') return
}

release = await lockfile.lock(inboxPath, {
  lockfilePath: lockFilePath,
  ...LOCK_OPTIONS,
})
// Re-read messages after acquiring lock to get the latest state
const messages = await readMailbox(recipientName, teamName)
messages.push({ ...message, read: false })
await writeFile(inboxPath, jsonStringify(messages, null, 2), 'utf-8')
```

Two details here are classic production scars: `{ flag: 'wx' }` creates an empty `[]` atomically without clobbering an existing file (satisfying `proper-lockfile`'s existence precondition), and `LOCK_OPTIONS` supplies 10 exponential retries because migrating from `lockSync` (which blocked the event loop) to async `lock()` dropped implicit serialization unless concurrent callers retried (`lines 31-41`). Similarly, `clearMailbox()` (`lines 349-368`) uses `{ flag: 'r+' }` so clearing a nonexistent inbox catches `ENOENT` instead of creating a phantom file.

#### `SendMessageTool`: One Tool, Four Routing Domains

[tools/SendMessageTool/SendMessageTool.ts](../../tools/SendMessageTool/SendMessageTool.ts) accepts `{ to, summary?, message }` where `message` is either a plain string (requiring a 5–10 word `summary` for UI previews and marked `isReadOnly: true`, `lines 539-541`) or a discriminated `StructuredMessage` (`shutdown_request`, `shutdown_response`, or `plan_approval_response`, `lines 46-65`).

Its `call()` method (`lines 741-913`) routes in four cascading tiers:

1. **Cross-session peer transport (`feature('UDS_INBOX')`, lines 742-798):** Recognizes `bridge:<session-id>` and `uds:<socket-path>` addresses via `parseAddress()`. Plain text only—structured messages are rejected up front in `validateInput()`. For `bridge:`, `checkPermissions()` (`lines 585-600`) returns a bypass-immune `safetyCheck` (`classifierApprovable: false`) so cross-machine prompt injection always requires explicit human consent, and `call()` *re-checks* `getReplBridgeHandle() && isReplBridgeActive()` after the permission prompt returns in case the bridge dropped during a multi-minute wait (`lines 745-756`).
2. **In-process subagent continuation (`lines 802-874`):** Before touching any team mailbox, `SendMessageTool` checks `appState.agentNameRegistry.get(input.to) ?? toAgentId(input.to)`. If the target is a running `LocalAgentTask`, it enqueues directly via `queuePendingMessage()` (`lines 809-821`); if the task is stopped or already evicted from `AppState`, it auto-resumes the agent from its sidechain transcript in the background via `resumeAgentBackground()` (`lines 823-872`). This is the exact primitive Coordinator Mode uses to continue workers.
3. **Team broadcast & DM (`lines 876-881`):** `to: '*'` iterates `teamFile.members` (skipping the sender case-insensitively, `lines 221-226`) and calls `writeToMailbox()` for each peer; structured messages cannot be broadcast (`lines 678-684, 883-885`). Named teammates receive a single `writeToMailbox()` call.
4. **Structured protocol handshakes (`lines 887-912`):**
   - `shutdown_request`: writes a `ShutdownRequestMessage` with a deterministic `requestId` (`shutdown-{ts}@{target}`).
   - `shutdown_response`: validated to target `TEAM_LEAD_NAME` only (`lines 694-703`). On `approve: true`, `handleShutdownApproval()` (`lines 305-399`) reads its own `tmuxPaneId` and `backendType` from `config.json`, writes `shutdown_approved` to `team-lead`, and then self-terminates: aborting its own `AbortController` if `in-process` (with an `AppState` fallback lookup), or calling `setImmediate(() => gracefulShutdown(0, 'other'))` if running in a pane process.
   - `plan_approval_response`: guarded by `isTeamLead(appState.teamContext)` (`lines 442-446, 487-491`), attaching the leader's current `permissionMode` (substituting `'default'` if the leader is itself in `'plan'` mode, `lines 448-449`) so the teammate transitions straight into the team's execution mode.

> [!NOTE]
> **Snapshot absence:** Under `feature('UDS_INBOX')`, `SendMessageTool.ts` dynamically requires `bridge/peerSessions.ts` (`line 759`, calling `postInterClaudeMessage`) and `utils/udsClient.ts` (`line 778`, calling `sendToUdsSocket`). Both modules are **absent from this snapshot**; their behavior is observed only from these call sites and `utils/peerAddress.ts`. Likewise, `types/message.ts` (imported by `inProcessRunner.ts` and `teammateMailbox.ts`) is absent from the snapshot.

#### Priority Wakeups, Idle Notifications, and the Poller Split

Two distinct pollers drain mailboxes because in-process teammates share the leader's React tree while pane teammates and the leader own their own REPLs:

- **In-process teammates** stay alive inside `waitForNextPromptOrShutdown()` ([utils/swarm/inProcessRunner.ts:689-868](../../utils/swarm/inProcessRunner.ts)), polling every `500 ms` across a strict five-tier priority hierarchy:
  1. `task.pendingUserMessages` (typed directly by the human while zoomed into the teammate's transcript via `injectUserMessageToTeammate()` in [InProcessTeammateTask.tsx:68-84](../../tasks/InProcessTeammateTask/InProcessTeammateTask.tsx))
  2. Unread `shutdown_request` scanned across the entire inbox (`inProcessRunner.ts:771-804`)—preventing peer-to-peer chatter from starving shutdown
  3. Unread messages from `TEAM_LEAD_NAME` (`lines 813-819`)—prioritizing leader intent over peer chatter
  4. First unread peer message in FIFO order (`lines 822-824`)
  5. Unclaimed, unblocked `pending` tasks in the team task list via `tryClaimNextTask()` (`lines 624-657, 854-861`)

  When an in-process teammate finishes a turn, it flips `isIdle: true`, invokes `task.onIdleCallbacks`, and calls `sendIdleNotification()` (`inProcessRunner.ts:1318-1347`, skipped if `wasAlreadyIdle` to avoid duplicates), attaching `getLastPeerDmSummary(allMessages)` ([utils/teammateMailbox.ts:1149-1183](../../utils/teammateMailbox.ts)) so the leader sees `[to peer] summary` even for peer-to-peer DMs it didn't receive.

- **Team leaders and pane teammates** run `useInboxPoller()` ([hooks/useInboxPoller.ts:126-969](../../hooks/useInboxPoller.ts)), mounted in [screens/REPL.tsx:4034-4039](../../screens/REPL.tsx) on a `1000 ms` interval. Its very first guard (`getAgentNameToPoll()`, `lines 81-105`) returns `undefined` if `isInProcessTeammate()` is true—because when an in-process teammate calls shared `setAppState`, React can re-render the leader's hooks *inside* the teammate's active `AsyncLocalStorage` context!
  - Pane teammates also register a `Stop` function hook during startup via `initializeTeammateHooks()` ([utils/swarm/teammateInit.ts:98-128](../../utils/swarm/teammateInit.ts)), which marks `isActive: false` in `config.json` and `await`s writing an `idle_notification` to `leadAgentName` before the turn closes.
  - On each poll, `useInboxPoller` partitions unread messages into 10 buckets (`lines 205-248`): 9 structured protocol types plus `regularMessages`.
  - Regular messages are formatted as `<teammate-message teammate_id="..." color="..." summary="...">` XML. If the session is idle (`!isLoading && !focusedInputDialog`), `onSubmitTeammateMessage(formatted)` starts a new turn immediately; if busy, messages are queued into `AppState.inbox.messages` (`status: 'pending'`) for mid-turn attachment pickup or post-turn delivery. Crucially, `markRead()` runs *only after* delivery or `AppState` enqueue (`lines 860-864`), so a crash mid-poll re-reads the messages instead of dropping them silently.
  - When the leader processes `shutdown_approved` (`lines 678-800`), it kills the pane via `ensureBackendsRegistered()` + `getBackendByType(backendType).killPane()`, removes the member from `config.json`, unassigns its tasks, and flips any matching synthetic task in `AppState.tasks` to `status: 'completed'` (`lines 749-765`) so the leader's spinner stops.

### Hidden Invariants & Failure Modes

> [!IMPORTANT]
> **Preventing the attachment-vs.-poller race:** In `ant` builds, `getTeammateMailboxAttachments()` ([utils/attachments.ts:3532-3630](../../utils/attachments.ts)) also reads the file mailbox mid-turn to inject peer messages as attachments without waiting for the turn to end. Without coordination, it raced `useInboxPoller`: whoever read first marked messages read, and if attachments won, raw JSON `permission_request` payloads were dumped into the LLM context and never reached the permission modal. Two guards close this hole:
> 1. `isStructuredProtocolMessage()` ([utils/teammateMailbox.ts:1073-1095](../../utils/teammateMailbox.ts)) filters all 10 control message types out of attachment reads so they stay unread for `useInboxPoller`.
> 2. `getTeammateMailboxAttachments()` skips `appState.inbox.messages` whenever `viewedTeammate || isInProcessTeammate()` (`attachments.ts:3607-3610`) so in-process teammates never read the leader's inbox (preventing broadcast self-echo), and deduplicates overlapping file + `AppState.inbox` reads by `from + timestamp + text` prefix (`lines 3615-3630`).

- **Protocol forgery defense:** Both `plan_approval_response` (`useInboxPoller.ts:158-195`) and `mode_set_request` (`useInboxPoller.ts:550-562`) explicitly verify `msg.from === 'team-lead'` before mutating `toolPermissionContext.mode`. A peer cannot forge a JSON approval to escape plan mode or escalate another teammate's permissions.
- **No double welcome prompts:** `handleSpawnInProcess()` deliberately does *not* write the initial prompt to the teammate's mailbox (`spawnMultiAgent.ts:1011-1014`) because `startInProcessTeammate()` already receives `prompt` directly; writing to both would duplicate turn 1.
- **Auto-approved plan mode on the leader:** Notice that in `useInboxPoller.ts:600-662`, incoming `plan_approval_request` messages are immediately auto-approved by the leader's poller (inheriting the leader's external permission mode) and *also* pushed into `regularMessages` so the leader model sees what the teammate planned.

---

## 4. Permission Bubbling Across Async and Process Boundaries

### The Problem

When a teammate calls `Bash` or `Edit` and `hasPermissionsToUseTool()` ([Chapter 11](11-the-permission-engine.md)) returns `behavior: 'ask'`, the teammate cannot simply block on `stdin`—an in-process teammate doesn't own the terminal, and a pane teammate may be tucked inside a hidden or detached `tmux` window. Returning an automatic denial cripples workers, while letting workers bypass prompts destroys the permission model. The harness needs every worker's `ask` decision to appear inside the leader's own `ToolUseConfirm` modal—complete with tool-specific diff previews, a colored `@worker` badge, and "always allow" rule persistence—and return the human's answer across either an in-process `Promise` or a cross-process mailbox round-trip.

### The Real Implementation

#### Path A: The Direct In-Process Bridge (`leaderPermissionBridge.ts`)

Because in-process teammates share the leader's heap but run *outside* React's component tree, [utils/swarm/leaderPermissionBridge.ts](../../utils/swarm/leaderPermissionBridge.ts) exposes a minimal 54-line module-level bridge holding two React state setters:

```ts
// utils/swarm/leaderPermissionBridge.ts:16-36
export type SetToolUseConfirmQueueFn = (
  updater: (prev: ToolUseConfirm[]) => ToolUseConfirm[],
) => void

export type SetToolPermissionContextFn = (
  context: ToolPermissionContext,
  options?: { preserveMode?: boolean },
) => void

let registeredSetter: SetToolUseConfirmQueueFn | null = null
let registeredPermissionContextSetter: SetToolPermissionContextFn | null = null
```

[screens/REPL.tsx](../../screens/REPL.tsx) binds both setters in `useEffect` hooks (`registerLeaderToolUseConfirmQueue(setToolUseConfirmQueue)` at `lines 1178-1181` and `registerLeaderSetToolPermissionContext(setToolPermissionContext)` at `lines 2378-2381`) and unregisters them on unmount.

Inside [utils/swarm/inProcessRunner.ts:128-334](../../utils/swarm/inProcessRunner.ts), `createInProcessCanUseTool()` handles `result.behavior === 'ask'` in five steps:

1. **Await Bash classifier first (`lines 159-176`):** Behind `feature('BASH_CLASSIFIER')`, if `result.pendingClassifierCheck` is present, the teammate awaits `awaitClassifierAutoApproval()` *before* queuing UI on the leader—unlike the main thread, which races the classifier against human keystrokes.
2. **Enqueue onto the leader's `ToolUseConfirm` queue (`lines 195-239`):** If `getLeaderToolUseConfirmQueue()` is non-null, it wraps a `Promise<PermissionDecision>` guarded by `let decisionMade = false`, stamps `workerBadge: { name: identity.agentName, color: identity.color }`, and pushes a full `ToolUseConfirm` entry directly onto the leader's UI queue.
3. **Subtract human wait time (`lines 201-207, 1182-1191`):** Every settlement path calls `reportPermissionWait()`, adding `Date.now() - permissionStartMs` to `task.totalPausedMs` so worker elapsed-time badges don't count minutes spent waiting on the user.
4. **Rule write-back with `preserveMode: true` (`lines 263-281`):**

```ts
// utils/swarm/inProcessRunner.ts:263-281
persistPermissionUpdates(permissionUpdates)
// Write back permission updates to the leader's shared context
if (permissionUpdates.length > 0) {
  const setToolPermissionContext = getLeaderSetToolPermissionContext()
  if (setToolPermissionContext) {
    const currentAppState = toolUseContext.getAppState()
    const updatedContext = applyPermissionUpdates(
      currentAppState.toolPermissionContext,
      permissionUpdates,
    )
    // Preserve the leader's mode to prevent workers'
    // transformed 'acceptEdits' context from leaking back
    // to the coordinator
    setToolPermissionContext(updatedContext, {
      preserveMode: true,
    })
  }
}
```

5. **Cascading queue rechecks (`screens/REPL.tsx:2365-2374`, `inProcessRunner.ts:305-330`):** Whenever the leader's `setToolPermissionContext` runs, it schedules a `setImmediate` sweep calling `item.recheckPermission()` on every remaining entry in `toolUseConfirmQueue`. If approving Worker A added an "always allow `npm test`" rule, Worker B's queued prompt for `npm test` re-evaluates `hasPermissionsToUseTool()`, removes itself from the queue, and resolves immediately with `allow` without bothering the user a second time.

#### Path B: Mailbox IPC for Pane Workers (and Headless In-Process Fallback)

When no React bridge is available—either because the worker lives in a separate `tmux`/`iTerm2` OS process, or because an in-process teammate is running headless without a mounted `REPL` (`getLeaderToolUseConfirmQueue() === null`)—permissions travel over the file-locked mailbox using [utils/swarm/permissionSync.ts](../../utils/swarm/permissionSync.ts), [hooks/toolPermission/handlers/swarmWorkerHandler.ts](../../hooks/toolPermission/handlers/swarmWorkerHandler.ts), and [hooks/useSwarmPermissionPoller.ts](../../hooks/useSwarmPermissionPoller.ts):

- **Worker side:** For pane teammates, `handleSwarmWorkerPermission()` (`swarmWorkerHandler.ts:40-156`) first awaits the optional `BASH_CLASSIFIER`, builds a `SwarmPermissionRequest` (`perm-{ts}-{rand}`), and **registers its callback in `pendingCallbacks` *before* sending the mailbox message** (`lines 79-123`) so an instant leader response can never race ahead of callback registration. It wraps resolution in `createResolveOnce()`'s atomic `claim()` before `await ctx.handleUserAllow(...)` so a concurrent abort cannot double-settle, and sets `AppState.pendingWorkerRequest` so the worker pane displays a "waiting for leader approval" indicator. For headless in-process fallback (`inProcessRunner.ts:337-449`), `createInProcessCanUseTool()` uses the exact same `registerPermissionCallback()` + `sendPermissionRequestViaMailbox()` pair and polls its own inbox every `500 ms` via `setInterval` until `isPermissionResponse()` matches `request.id`.
- **Leader side:** `useInboxPoller` ([hooks/useInboxPoller.ts:251-364](../../hooks/useInboxPoller.ts)) pops `permission_request` messages, resolves the `Tool` object via `findToolByName(getAllBaseTools(), parsed.tool_name)`, constructs a `ToolUseConfirm` with a cyan `workerBadge`, deduplicates by `toolUseID` in case `markMessagesAsRead` failed on a prior poll (`lines 338-345`), fires a desktop notification if the leader is idle, and wires `onAllow`/`onReject`/`onAbort` to `sendPermissionResponseViaMailbox()` (`permissionSync.ts:734-783`).
- **Response delivery & validation:** On the worker, `useInboxPoller` (`lines 367-397`) matches `permission_response` to `hasPermissionCallback(parsed.request_id)` and invokes `processMailboxPermissionResponse()` (`useSwarmPermissionPoller.ts:124-156`), which deletes the callback entry *before* running it and sanitizes `permissionUpdates` through Zod (`parsePermissionUpdates()`, `lines 35-53`).
- **Sandbox network prompts:** Outbound network blocks inside OS sandboxes ([Chapter 12](12-shell-execution-sandboxing-and-workspace-tools.md)) follow the identical mailbox round-trip via `sendSandboxPermissionRequestViaMailbox()` / `sendSandboxPermissionResponseViaMailbox()` (`permissionSync.ts:805-928`), routing through `AppState.workerSandboxPermissions.queue` on the leader (`useInboxPoller.ts:400-463`) and `pendingSandboxCallbacks` on the worker (`useSwarmPermissionPoller.ts:172-226`).

> [!NOTE]
> **Evolution scar in `permissionSync.ts`:** Lines 112–641 of [utils/swarm/permissionSync.ts](../../utils/swarm/permissionSync.ts) still retain the older directory-based permission protocol (`~/.claude/teams/{team}/permissions/{pending,resolved}/{id}.json` + `useSwarmPermissionPoller()`), kept for backward compatibility. As noted at [screens/REPL.tsx:4062-4064](../../screens/REPL.tsx), live interactive sessions now route all permission requests and responses exclusively through mailboxes and `useInboxPoller`.

### Hidden Invariants & Failure Modes

- **Untrusted IPC validation:** `parsePermissionUpdates()` ([hooks/useSwarmPermissionPoller.ts:35-53](../../hooks/useSwarmPermissionPoller.ts)) runs `permissionUpdateSchema().safeParse()` on every rule received over mailbox IPC, dropping malformed entries from mismatched or buggy peer versions instead of crashing `applyPermissionUpdates()`.
- **Team-wide directory rules:** Permissions granted to a directory can be persisted in `TeamFile.teamAllowedPaths` (applied at startup by `initializeTeammateHooks()` in [utils/swarm/teammateInit.ts:45-79](../../utils/swarm/teammateInit.ts), converting absolute `/foo` into `//foo/**` rule syntax) and broadcast live to running teammates via `team_permission_update` (`useInboxPoller.ts:498-547`).
- **Asymmetric `recheckPermission()`:** For in-process teammates sharing memory with the leader, `recheckPermission()` auto-dismisses duplicate queued prompts when rules update. For pane teammates, `recheckPermission()` in `useInboxPoller.ts:333-335` is an explicit no-op because the worker's `toolPermissionContext` lives in another process.

---

## 5. Coordinator Mode: Turning the Leader into a Pure Orchestrator

### The Problem

Swarms give a leader the *option* to delegate, but an LLM holding `Read`, `Grep`, `Edit`, and `Bash` suffers from strong "do it myself" inertia: it reads files directly, edits small bugs inline, and serializes investigations instead of fanning them out. Furthermore, when a leader delegates lazily (*"based on your findings, fix the bug"*), the next worker inherits vague instructions and misses root causes. Coordinator Mode solves both problems structurally by stripping all execution tools from the top-level agent, replacing its system prompt with an explicit orchestration discipline, and keeping workers asynchronous under a unified `<task-notification>` / `SendMessage` loop.

### The Real Implementation

#### Feature Gate, Live Env Toggle, and Resume Continuity

[coordinator/coordinatorMode.ts:36-78](../../coordinator/coordinatorMode.ts) gates the mode behind `feature('COORDINATOR_MODE')` and reads `process.env.CLAUDE_CODE_COORDINATOR_MODE` live without caching:

```ts
// coordinator/coordinatorMode.ts:36-41, 49-70 (abridged)
export function isCoordinatorMode(): boolean {
  if (feature('COORDINATOR_MODE')) {
    return isEnvTruthy(process.env.CLAUDE_CODE_COORDINATOR_MODE)
  }
  return false
}

export function matchSessionMode(
  sessionMode: 'coordinator' | 'normal' | undefined,
): string | undefined {
  if (!sessionMode) return undefined
  const currentIsCoordinator = isCoordinatorMode()
  const sessionIsCoordinator = sessionMode === 'coordinator'
  if (currentIsCoordinator === sessionIsCoordinator) return undefined

  // Flip the env var — isCoordinatorMode() reads it live, no caching
  if (sessionIsCoordinator) {
    process.env.CLAUDE_CODE_COORDINATOR_MODE = '1'
  } else {
    delete process.env.CLAUDE_CODE_COORDINATOR_MODE
  }
  // ...logs 'tengu_coordinator_mode_switched' and returns a user-facing banner
}
```

Every session save point (`main.tsx:3771`, `REPL.tsx:1904`, `cli/print.ts:5169`, `utils/sessionRestore.ts:515`) persists `'coordinator' | 'normal'` to the transcript. When a user resumes a coordinator session from a normal CLI (or vice versa), `matchSessionMode()` flips `process.env.CLAUDE_CODE_COORDINATOR_MODE` in-process so tool filtering and system-prompt selection immediately match the historical transcript without forcing a restart.

#### Surgical Tool Stripping and the `CLAUDE_CODE_SIMPLE` Dance

The entire tool restriction boils down to a four-tool allowlist in [constants/tools.ts:107-112](../../constants/tools.ts) and a 15-line filter in [utils/toolPool.ts:11-41](../../utils/toolPool.ts):

```ts
// constants/tools.ts:107-112
export const COORDINATOR_MODE_ALLOWED_TOOLS = new Set([
  AGENT_TOOL_NAME,
  TASK_STOP_TOOL_NAME,
  SEND_MESSAGE_TOOL_NAME,
  SYNTHETIC_OUTPUT_TOOL_NAME,
])

// utils/toolPool.ts:35-41
export function applyCoordinatorToolFilter(tools: Tools): Tools {
  return tools.filter(
    t =>
      COORDINATOR_MODE_ALLOWED_TOOLS.has(t.name) ||
      isPrActivitySubscriptionTool(t.name),
  )
}
```

`isPrActivitySubscriptionTool()` (`utils/toolPool.ts:11-18`) matches MCP tools ending in `subscribe_pr_activity` or `unsubscribe_pr_activity` by suffix (since MCP server prefixes vary), keeping lightweight GitHub PR event subscriptions directly on the coordinator.

`mergeAndFilterTools()` (`utils/toolPool.ts:55-79`)—placed in a React-free file so headless `cli/print.ts` can call it without pulling Ink/React into the SDK graph—runs partition-sorting (built-in tools first, MCP tools second, preserving Chapter 02's prompt-cache prefix) and then applies `applyCoordinatorToolFilter()` whenever `isCoordinatorMode()` is true. The same filter runs in `main.tsx:1876` and `hooks/useMergedTools.ts:32`.

There is a neat edge case in [tools.ts:273-298](../../tools.ts) when `CLAUDE_CODE_SIMPLE` (which normally exposes only `[BashTool, FileReadTool, FileEditTool]`) is combined with Coordinator Mode: `getTools()` explicitly *adds* `AgentTool`, `TaskStopTool`, and `SendMessageTool` to `simpleTools` so that `mergeAndFilterTools()` keeps orchestration tools for the coordinator while `filterToolsForAgent()` hands `[Bash, Read, Edit]` down to the spawned workers.

#### System Prompt Takeover and Worker Context Injection

In [utils/systemPrompt.ts:56-75](../../utils/systemPrompt.ts), Coordinator Mode occupies **Priority #1** in `buildEffectiveSystemPrompt()`—outranked only by `overrideSystemPrompt` and bypassed only if an explicit `mainThreadAgentDefinition` is active:

```ts
// utils/systemPrompt.ts:62-75
if (
  feature('COORDINATOR_MODE') &&
  isEnvTruthy(process.env.CLAUDE_CODE_COORDINATOR_MODE) &&
  !mainThreadAgentDefinition
) {
  // Lazy require to avoid circular dependency at module load time
  const { getCoordinatorSystemPrompt } =
    require('../coordinator/coordinatorMode.js') as typeof import('../coordinator/coordinatorMode.js')
  return asSystemPrompt([
    getCoordinatorSystemPrompt(),
    ...(appendSystemPrompt ? [appendSystemPrompt] : []),
  ])
}
```

Notice it uses an inline `isEnvTruthy(process.env.CLAUDE_CODE_COORDINATOR_MODE)` check + lazy `require` to break a test-time module load cycle.

`getCoordinatorSystemPrompt()` ([coordinator/coordinatorMode.ts:111-369](../../coordinator/coordinatorMode.ts)) reshapes the model's entire operating contract:

- **Role & XML framing (`lines 118-165`):** Every response goes to the human; incoming `<task-notification>` blocks arrive as `user`-role messages but are internal signals (never thanked or acknowledged). The coordinator must end its turn after launching workers and never predict or fabricate results.
- **Four-phase workflow (`lines 198-228`):** Parallel `Research` (workers) → `Synthesis` (coordinator) → `Implementation` (workers, serialized per file area) → independent `Verification` (workers instructed to run tests with the feature enabled and dig into typecheck errors rather than rubber-stamping).
- **Anti-lazy-delegation & continue-vs.-spawn rubric (`lines 251-307`):** Explicitly forbids writing *"based on your findings"*—the coordinator must absorb research outputs and emit self-contained specs with exact file paths, line numbers, and acceptance criteria. It then chooses between continuing an existing worker via `SendMessage({ to: agentId })` (high context overlap, fixing its own test failures) versus spawning a fresh worker via `Agent` (broad exploration → narrow edit, independent verification, or resetting after a wrong approach).

Alongside the system prompt, `screens/REPL.tsx:2775` and `QueryEngine.ts:304` spread `getCoordinatorUserContext(mcpClients, scratchpadDir)` ([coordinator/coordinatorMode.ts:80-109](../../coordinator/coordinatorMode.ts)) into the user context. This injects `workerToolsContext`: the sorted list of tools workers can use (`ASYNC_AGENT_ALLOWED_TOOLS` minus `INTERNAL_WORKER_TOOLS`, or `Bash, Edit, Read` under `CLAUDE_CODE_SIMPLE`), connected MCP server names, and—when GrowthBook gate `tengu_scratch` is enabled—a shared `scratchpadDir` where workers can read/write cross-worker notes without permission prompts. Notice the dependency-injection scar at `coordinatorMode.ts:19-27`: `isScratchpadGateEnabled()` duplicates the `tengu_scratch` check and takes `scratchpadDir` as a parameter because importing `utils/permissions/filesystem.ts` directly would introduce a circular dependency (`filesystem → permissions → … → coordinatorMode`).

### Hidden Invariants & Failure Modes

Four subtle runtime hooks keep Coordinator Mode coherent across Layer 6:

- **No worker model downgrading:** [tools/AgentTool/AgentTool.tsx:252](../../tools/AgentTool/AgentTool.tsx) strips any model argument chosen by the coordinator (`const model = isCoordinatorMode() ? undefined : modelParam`), forcing workers onto the default model for substantive engineering tasks.
- **Mutual exclusion with context forking:** [tools/AgentTool/forkSubagent.ts:32-39](../../tools/AgentTool/forkSubagent.ts) returns `false` whenever `isCoordinatorMode()` is true—a coordinator never forks its orchestration transcript into workers because workers are meant to start from clean, synthesized specs.
- **Automatic progress summaries on resumed workers:** [tools/AgentTool/resumeAgent.ts:250-253](../../tools/AgentTool/resumeAgent.ts) enables background progress summarization whenever `isCoordinatorMode()` is active, giving the user live visibility as `SendMessage` continues workers.
- **Proactive loop suppression:** [main.tsx:2199](../../main.tsx) disables autonomous proactive ticks (`!coordinatorModeModule?.isCoordinatorMode()`) so proactive heartbeats don't collide with coordinator orchestration.

---

## Putting the Layer Together

The diagram below shows how the leader REPL, file-locked mailboxes, direct permission bridge, pane backends, and Coordinator Mode compose at runtime:

```mermaid
flowchart TD
    subgraph Leader["Leader Process (screens/REPL.tsx & AppState)"]
        Coord["Coordinator Mode filter (toolPool.ts + systemPrompt.ts)"]
        AgentT["AgentTool -> spawnTeammate()"]
        SendT["SendMessageTool"]
        Bridge["leaderPermissionBridge.ts (ToolUseConfirmQueue + preserveMode)"]
        Poller["useInboxPoller (1000ms)"]
        UI["Ink PermissionRequest + WorkerBadge + TeamStatus"]
    end

    subgraph Disk["Shared Disk State (~/.claude/teams/{team}/)"]
        Cfg["config.json (TeamFile)"]
        LeadBox["inboxes/team-lead.json (+ .lock)"]
        WorkBox["inboxes/{agent}.json (+ .lock)"]
        Tasks["~/.claude/tasks/{team}/"]
    end

    subgraph InProc["In-Process Teammate (same Node/Bun process)"]
        ALS["AsyncLocalStorage (TeammateContext)"]
        Runner["inProcessRunner.ts (runAgent + 500ms wait loop)"]
    end

    subgraph Pane["Pane Teammate (tmux / iTerm2 OS process)"]
        DynCtx["dynamicTeamContext (--agent-id/--team-name)"]
        PanePoll["useInboxPoller + Stop hook (teammateInit.ts)"]
        SwarmPerm["swarmWorkerHandler.ts + useSwarmPermissionPoller"]
    end

    Coord --> AgentT
    Coord --> SendT
    AgentT -->|"in-process"| ALS
    AgentT -->|"tmux / iTerm2 split"| DynCtx
    AgentT --> Cfg

    ALS --> Runner
    Runner -->|"ask (fast path)"| Bridge
    Bridge --> UI
    Runner -->|"idle / DM / fallback perm"| LeadBox
    Runner -->|"500ms priority poll"| WorkBox
    Runner -->|"claim unclaimed"| Tasks

    SendT -->|"DM / broadcast / shutdown"| WorkBox
    SendT -->|"continue LocalAgentTask"| AgentT

    Poller -->|"reads & routes 10 types"| LeadBox
    Poller -->|"perm req -> ToolUseConfirm"| Bridge
    Poller -->|"perm resp / plan approval"| WorkBox

    DynCtx --> PanePoll
    PanePoll -->|"reads prompts & perm resp"| WorkBox
    PanePoll -->|"Stop hook -> idle"| LeadBox
    SwarmPerm -->|"permission_request"| LeadBox
```

Comparing the three Layer 6 multi-agent execution shapes side-by-side clarifies why each exists:

```text
+---------------+--------------------+-------------------+-------------------+
| Dimension     | In-Process         | Pane Teammate     | Coordinator       |
|               | Teammate           | (tmux / iTerm2)   | Worker            |
+---------------+--------------------+-------------------+-------------------+
| Isolation     | Shared heap +      | Separate OS proc  | Shared heap       |
|               | AsyncLocalStorage  | (--agent-id CLI)  | LocalAgentTask    |
+---------------+--------------------+-------------------+-------------------+
| Spawner       | AgentTool (name +  | AgentTool (name + | AgentTool         |
|               | team_name)         | team_name)        | (no team_name)    |
+---------------+--------------------+-------------------+-------------------+
| Continuation  | File mailbox +     | File mailbox      | SendMessage ->    |
| & IPC         | pendingUserMsgs    | (useInboxPoller)  | queue/resumeAgent |
+---------------+--------------------+-------------------+-------------------+
| Permissions   | leaderPermission-  | Mailbox IPC ->    | Parent canUseTool |
|               | Bridge (fallback:  | leader ToolUse-   | / async tool      |
|               | mailbox IPC)       | ConfirmQueue      | allowlist         |
+---------------+--------------------+-------------------+-------------------+
| Abort / Stop  | Dual: Escape stops | killPane() or     | TaskStopTool ->   |
|               | turn; lifecycle    | gracefulShutdown  | task abort; can   |
|               | kills teammate     | via mailbox       | resume via SendMsg|
+---------------+--------------------+-------------------+-------------------+
| Leader Tools  | Full tool pool +   | Full tool pool +  | Stripped to 4     |
|               | Team/SendMessage   | Team/SendMessage  | tools + PR MCPs   |
+---------------+--------------------+-------------------+-------------------+
```

---

## How This Snaps Into the Next Layer

Every concurrency primitive in Part VI ultimately has to be observed, controlled, and approved by a human sitting at a single terminal window. Look at the exact UI boundaries touched throughout this chapter:

- [components/permissions/PermissionRequest.tsx](../../components/permissions/PermissionRequest.tsx) and [components/permissions/WorkerBadge.tsx](../../components/permissions/WorkerBadge.tsx) render queued `ToolUseConfirm` prompts pushed by both `leaderPermissionBridge.ts` (in-process teammates) and `useInboxPoller.ts` (pane teammates), drawing colored `@worker` badges above live Bash/Edit diff modals.
- [components/teams/TeamStatus.tsx](../../components/teams/TeamStatus.tsx) and [components/teams/TeamsDialog.tsx](../../components/teams/TeamsDialog.tsx) project `AppState.teamContext` and `InProcessTeammateTaskState` (with its 50-message UI mirror cap and `getRunningTeammatesSorted()` index order) into footer pills, live spinner trees, and zoomed interactive transcripts.
- [utils/swarm/It2SetupPrompt.tsx](../../utils/swarm/It2SetupPrompt.tsx) hijacks `context.setToolJSX` mid-spawn to walk iTerm2 users through installing `it2` or choosing `tmux`.

Every single one of those components returns `<Box>` and `<Text>` elements from [ink.ts](../../ink.ts). In **[Chapter 20 — Inside `ink/`: A Custom React Renderer for the Terminal](20-inside-ink-terminal-react-renderer.md)**, we drop directly beneath those React components into [ink/reconciler.ts](../../ink/reconciler.ts), [ink/dom.ts](../../ink/dom.ts), and [ink/ink.tsx](../../ink/ink.tsx) to see how Claude Code lays out flexbox trees with Yoga, diffs 2D character cell screens, and paints simultaneous multi-agent spinners, permission dialogs, and keybindings at 60 FPS without tearing the terminal.

---

## Reading Exercises & Code Checkpoints

1. **Trace the mailbox lock & race guards:** Run `rg -n "isStructuredProtocolMessage|markMessagesAsRead" utils/ hooks/` and inspect [utils/attachments.ts:3583-3630](../../utils/attachments.ts) alongside [hooks/useInboxPoller.ts:204-248,860-864](../../hooks/useInboxPoller.ts). What would happen if a new structured control message type were added to `useInboxPoller` without also adding it to `isStructuredProtocolMessage()`?
2. **Verify `preserveMode` across permission write-back:** Run `rg -n "preserveMode" utils/swarm/ screens/`. Trace a worker running in `acceptEdits` mode whose `Bash` call triggers a leader prompt where the user selects "Always allow": why must [screens/REPL.tsx:2355-2359](../../screens/REPL.tsx) preserve `prev.toolPermissionContext.mode` while still running `recheckPermission()` across queued items?
3. **Audit Coordinator Mode's complete surface area:** Run `rg -n "COORDINATOR_MODE|isCoordinatorMode" .` across the repo. List every file that changes behavior in coordinator mode (tool pool, system prompt, user context, `AgentTool` model stripping, `forkSubagent` suppression, `resumeAgent` summarization, proactive suppression, and transcript mode persistence via `matchSessionMode`).
4. **Compare in-process vs. pane shutdown paths:** Inspect `handleShutdownApproval()` in [tools/SendMessageTool/SendMessageTool.ts:305-399](../../tools/SendMessageTool/SendMessageTool.ts) and the `shutdownApprovals` handler in [hooks/useInboxPoller.ts:678-800](../../hooks/useInboxPoller.ts). Why does `useInboxPoller` explicitly mark matching `in_process_teammate` tasks `status: 'completed'` for *out-of-process* tmux teammates?


---

<!-- chapters/20-inside-ink-terminal-react-renderer.md — https://reverseengineeringclaudecode.com/chapters/20-inside-ink-terminal-react-renderer -->

# Chapter 20 — Inside `ink/`: A Custom React Renderer for the Terminal

> **Layer:** Layer 7 (The Terminal UI Engine)
> **Prerequisites:** [Chapter 01](01-atoms-types-stores-and-primitives.md), [Chapter 19](19-agent-teams-swarms-and-coordinator-mode.md)
> **Primary Source Files:**
> - [ink/dom.ts](../../ink/dom.ts) — Custom terminal DOM nodes, dirty-flag propagation, text measurement, and Yoga tree wiring
> - [ink/reconciler.ts](../../ink/reconciler.ts) — React 19 `react-reconciler` host config, prop diffing, event priority bridge, and commit hooks
> - [ink/root.ts](../../ink/root.ts) & [ink/ink.tsx](../../ink/ink.tsx) — `createRoot` / `Ink` orchestrator: double-buffered frames, resize/SIGCONT, alt-screen, IME cursor parking, and shutdown cleanup
> - [ink/layout/yoga.ts](../../ink/layout/yoga.ts) & [native-ts/yoga-layout/index.ts](../../native-ts/yoga-layout/index.ts) — Layout adapter and 2,578-line pure-TypeScript port of Meta's Yoga flexbox engine
> - [ink/renderer.ts](../../ink/renderer.ts), [ink/render-node-to-output.ts](../../ink/render-node-to-output.ts), & [ink/output.ts](../../ink/output.ts) — Subtree blitting, `ScrollBox` culling/drain/shift fast path, grapheme clustering, and deferred paint pipeline
> - [ink/screen.ts](../../ink/screen.ts) — Packed 64-bit-per-cell `Screen` typed-array buffer, intern pools, `noSelect`/`softWrap` bitmaps, and `diffEach`
> - [ink/log-update.ts](../../ink/log-update.ts), [ink/optimizer.ts](../../ink/optimizer.ts), & [ink/terminal.ts](../../ink/terminal.ts) — Virtual cursor diffing, `DECSTBM` hardware scroll, patch peephole optimizer, and `DEC 2026` synchronized output
> - [ink/parse-keypress.ts](../../ink/parse-keypress.ts), [ink/termio/tokenize.ts](../../ink/termio/tokenize.ts), & [ink/terminal-querier.ts](../../ink/terminal-querier.ts) — Streaming VT input tokenizer, Kitty/CSI-u/`modifyOtherKeys`/mouse parser, and timeout-free `DA1` sentinel querier
> - [ink/focus.ts](../../ink/focus.ts), [ink/terminal-focus-state.ts](../../ink/terminal-focus-state.ts), [ink/hit-test.ts](../../ink/hit-test.ts), [ink/selection.ts](../../ink/selection.ts), & [ink/supports-hyperlinks.ts](../../ink/supports-hyperlinks.ts) — Focus management, mouse hit-testing/hover, fullscreen text selection, and OSC 8 hyperlinks
> - [ink/components/App.tsx](../../ink/components/App.tsx) & [ink/components/AlternateScreen.tsx](../../ink/components/AlternateScreen.tsx) — Raw-mode `stdin` loop, multi-click/drag/hover state machine, and DEC 1049 alt-screen lifecycle

---

## Why This Layer Exists

By the end of Layer 6, the harness can stream tokens from the model, orchestrate concurrent tools, manage background tasks, and coordinate multi-agent swarms. Now all of that concurrent activity has to land inside a 2D monospace grid connected over a PTY—potentially tunneled through `tmux`, `ssh`, VS Code's `xterm.js`, or Windows `conhost`—while running at 60 FPS (`FRAME_INTERVAL_MS = 16` in [ink/constants.ts](../../ink/constants.ts)).

A natural first question when opening this repository is: **why maintain a 96-file vendored fork of Ink (`ink/`) plus a 2,578-line pure-TypeScript port of Meta's Yoga layout engine ([native-ts/yoga-layout/index.ts](../../native-ts/yoga-layout/index.ts)) instead of installing stock `ink` from npm?**

Stock Ink was built for short-lived CLI widgets: it flattens the tree to strings each frame, erases and rewrites lines via `log-update`, loads Yoga as an async WASM binary, and treats terminals as write-only output streams with rudimentary keypress parsing. Every one of those assumptions breaks under an interactive coding agent:

1. **Streaming diffs & spinners destroy string-based rendering.** Re-tokenizing ANSI strings and rewriting 100+ rows on every 16 ms spinner tick causes visible flicker, tears frames across `tmux` chunk boundaries, and creates massive GC pressure.
2. **WASM Yoga imposes startup latency, async init races, and linear-memory growth.** Long-lived sessions that mount and unmount thousands of message nodes hit WASM heap overhead and dangling-pointer hazards.
3. **Alternate-screen (`DEC 1049`) + mouse tracking breaks native terminal ergonomics.** The moment a TUI enables SGR mouse tracking (`DEC 1000/1002/1003/1006`) for wheel scrolling and clickable controls, the terminal stops doing native click-drag text selection, double-click word selection, and Cmd+Click URL opening. The renderer must re-implement all of them faithfully—down to soft-wrap logical-line joining, `<NoSelect>` diff gutters, and clipboard fallback chains.
4. **Modern keyboard & terminal diversity cannot be solved with regex hacks.** Disambiguating `Shift+Enter` or `Ctrl+Shift+C` requires both Kitty's `CSI u` protocol and xterm's `modifyOtherKeys`, while CJK IME composition requires parking the physical terminal cursor at the React input caret without breaking relative cursor diffs.

What lives in `ink/` is therefore less a CLI helper and more a **browser-grade terminal compositor** built directly on `react-reconciler`.

> [!NOTE]
> **Snapshot notes:** Functional `.tsx` components inside `ink/` (such as [ink/components/AlternateScreen.tsx](../../ink/components/AlternateScreen.tsx), [ink/components/Link.tsx](../../ink/components/Link.tsx), and [ink/components/TerminalFocusContext.tsx](../../ink/components/TerminalFocusContext.tsx)) appear in this checkout after the React Compiler memoization pass (`const $ = _c(...)` from `react/compiler-runtime`), while class components like [ink/components/App.tsx](../../ink/components/App.tsx) and [ink/ink.tsx](../../ink/ink.tsx) remain untransformed. Three auxiliary files imported inside `ink/` are **absent from the snapshot** and observed only at call sites: `ink/cursor.ts` (type `Cursor = { x: number; y: number; visible: boolean }` in [ink/frame.ts](../../ink/frame.ts):1), `ink/devtools.ts` (dev-only dynamic import in [ink/reconciler.ts](../../ink/reconciler.ts):36), and `ink/global.d.ts` (JSX intrinsic declarations imported in [ink/components/Box.tsx](../../ink/components/Box.tsx):2 and [ink/components/ScrollBox.tsx](../../ink/components/ScrollBox.tsx):8). There are no build-time `feature()` gates inside `ink/` or `native-ts/yoga-layout/`; the sole build/user-tier gate is `process.env.USER_TYPE === 'ant'` in [ink/termio/osc.ts](../../ink/termio/osc.ts):468 for experimental OSC 21337 tab status indicators.

---

## 1. Custom DOM Nodes, React 19 Reconciliation, and Pure-TS Yoga Layout

### The Problem

React produces a fiber tree of components, props, and text strings; Yoga computes 2D flexbox rectangles. Bridging them naively creates three acute failure modes:

- **Spurious invalidation:** React allocates fresh `style`, `textStyles`, `children`, and event-handler closures on every render. Passing them blindly to the host node marks subtrees dirty, forcing full Yoga re-measurement and defeating screen-buffer blitting.
- **Commit-phase timing skew:** `react-reconciler` invokes `resetAfterCommit()` *before* React's layout phase (`ref` attachment and `useLayoutEffect`). Painting synchronously inside `resetAfterCommit()` leaves anything declared in `useLayoutEffect`—especially the native IME cursor position from `useDeclaredCursor`—lagging one keystroke behind.
- **Pathological flexbox relayout cascades:** In a 500-message `ScrollBox`, dirtying one leaf (such as a streaming assistant token) causes Yoga's measure→layout recursion to visit clean siblings with multiple constraint combinations, thrashing a single-slot layout cache into $O(2^{\text{depth}})$ visits.

### The Real Implementation

#### Seven Host Elements and Dirty Propagation ([ink/dom.ts](../../ink/dom.ts))

The custom DOM defines exactly seven element node names plus `#text`:

```ts
// ink/dom.ts:18-26, 110-132
export type TextName = '#text'
export type ElementNames =
  | 'ink-root'
  | 'ink-box'
  | 'ink-text'
  | 'ink-virtual-text'
  | 'ink-link'
  | 'ink-progress'
  | 'ink-raw-ansi'

export const createNode = (nodeName: ElementNames): DOMElement => {
  const needsYogaNode =
    nodeName !== 'ink-virtual-text' &&
    nodeName !== 'ink-link' &&
    nodeName !== 'ink-progress'
  const node: DOMElement = {
    nodeName,
    style: {},
    attributes: {},
    childNodes: [],
    parentNode: undefined,
    yogaNode: needsYogaNode ? createLayoutNode() : undefined,
    dirty: false,
  }

  if (nodeName === 'ink-text') {
    node.yogaNode?.setMeasureFunc(measureTextNode.bind(null, node))
  } else if (nodeName === 'ink-raw-ansi') {
    node.yogaNode?.setMeasureFunc(measureRawAnsiNode.bind(null, node))
  }

  return node
}
```

Three design details in `createNode` and `dom.ts` do heavy lifting:

1. **Inline nodes do not allocate Yoga nodes.** Nested `<Text>` elements become `ink-virtual-text` via `HostContext.isInsideText` ([ink/reconciler.ts](../../ink/reconciler.ts):342-345); `<Link>` emits `ink-link`; progress bars emit `ink-progress`. Because their `yogaNode` is `undefined`, `insertBeforeNode` ([ink/dom.ts](../../ink/dom.ts):168-186) cannot pass the DOM child index to Yoga—it counts preceding children that actually possess a `yogaNode` to compute `yogaIndex`.
2. **`ink-raw-ansi` fast-paths pre-rendered output.** Syntax-highlighted diffs (`ColorDiff`) already know their exact terminal dimensions and wrapped ANSI lines. `measureRawAnsiNode` ([ink/dom.ts](../../ink/dom.ts):379-387) simply returns `{ width: rawWidth, height: rawHeight }`—zero `stringWidth()`, zero wrapping, zero tab expansion.
3. **Value-equality dirty guards and side-channel event handlers.** `setStyle` and `setTextStyles` perform `shallowEqual` before calling `markDirty(node)` ([ink/dom.ts](../../ink/dom.ts):266-289), `setAttribute` ignores `children` and unchanged scalars, and `reconciler.ts` stores event handlers on `node._eventHandlers` rather than `node.attributes` ([ink/dom.ts](../../ink/dom.ts):48-51, [ink/reconciler.ts](../../ink/reconciler.ts):114-143) so inline callback identity changes never dirty the node or defeat blitting. When `markDirty(node)` runs ([ink/dom.ts](../../ink/dom.ts):393-413), it walks `parentNode` up to `ink-root` setting `.dirty = true`, and calls `yogaNode.markDirty()` on the first enclosing leaf with a measure function (`ink-text` or `ink-raw-ansi`).

#### React 19 Host Config and the Microtask Paint Boundary ([ink/reconciler.ts](../../ink/reconciler.ts), [ink/ink.tsx](../../ink/ink.tsx))

[ink/reconciler.ts](../../ink/reconciler.ts) constructs a `ConcurrentRoot` reconciler targeting React 19 (`commitUpdate` receives `oldProps` and `newProps` directly rather than a React 18 `updatePayload`; `maySuspendCommit` / `HostTransitionContext` / `resolveUpdatePriority` are implemented). Notice how `reconciler.ts` wires the event `Dispatcher` ([ink/events/dispatcher.ts](../../ink/events/dispatcher.ts)) into `resolveUpdatePriority`, `resolveEventType`, and `resolveEventTimeStamp`, then injects `dispatcher.discreteUpdates = reconciler.discreteUpdates.bind(reconciler)` at module end ([ink/reconciler.ts](../../ink/reconciler.ts):510) to break the circular import.

Inside `resetAfterCommit(rootNode)` ([ink/reconciler.ts](../../ink/reconciler.ts):247-315):
1. It synchronously calls `rootNode.onComputeLayout()`—which runs `yogaNode.calculateLayout(this.terminalColumns)` ([ink/ink.tsx](../../ink/ink.tsx):239-258)—*before* React runs `useLayoutEffect`, so layout effects read fresh Yoga geometry.
2. In test mode (`NODE_ENV === 'test'`), it skips empty post-content commits (guarding against React 19's effect double-invoke) and calls `onImmediateRender()`.
3. In production, it calls `rootNode.onRender()`, which points to a throttled microtask scheduler:

```ts
// ink/ink.tsx:212-216
const deferredRender = (): void => queueMicrotask(this.onRender);
this.scheduleRender = throttle(deferredRender, FRAME_INTERVAL_MS, {
  leading: true,
  trailing: true
});
```

That single `queueMicrotask` solves the commit-phase timing skew: React finishes attaching refs and running `useLayoutEffect` (including `useDeclaredCursor`) synchronously after `resetAfterCommit()`, and then `this.onRender` runs in the microtask queue of the *exact same event-loop turn*—zero keystroke lag for CJK IME preedit text, zero frame-rate penalty.

#### Pure-TypeScript Yoga and Generation-Stamped Layout Caching ([native-ts/yoga-layout/index.ts](../../native-ts/yoga-layout/index.ts))

Behind the thin adapter [ink/layout/yoga.ts](../../ink/layout/yoga.ts), the entire flexbox engine is implemented in pure TypeScript inside [native-ts/yoga-layout/index.ts](../../native-ts/yoga-layout/index.ts). There is no WASM binary, no linear-memory allocator, and no async initialization. Yet [ink/root.ts](../../ink/root.ts):111-115 and `137-138` retain a telling production scar:

```ts
// ink/root.ts:111-116
// Preserve the microtask boundary that `await loadYoga()` used to provide.
// Without it, the first render fires synchronously before async startup work
// (e.g. useReplBridge notification state) settles, and the subsequent Static
// write overwrites scrollback instead of appending below the logo.
await Promise.resolve()
const instance = renderSync(node, options)
```

To make pure-TS flexbox fast enough for 60 FPS scrolling over deep transcript trees, `layoutNode()` in [native-ts/yoga-layout/index.ts](../../native-ts/yoga-layout/index.ts):1058-1194 uses a **three-tier cache** (`_hasL` single-slot layout cache, `_cIn`/`_cOut` multi-entry cache, and `_hasM` measure cache) stamped with a monotonic `_generation` counter incremented on every `calculateLayout()`:

```ts
// native-ts/yoga-layout/index.ts:1086-1134 (abridged single-slot checks)
const sameGen = node._cGen === _generation && !performLayout
if (!node.isDirty_ || sameGen) {
  if (!node.isDirty_ && node._hasL && /* mode/force/size match */) {
    _yogaCacheHits++
    layout.width = node._lOutW
    layout.height = node._lOutH
    return
  }
  if (node._cN > 0 && (sameGen || !node.isDirty_)) {
    const cIn = node._cIn!
    for (let i = 0; i < node._cN; i++) {
      const o = i * 8
      if (
        cIn[o + 2] === widthMode &&
        cIn[o + 3] === heightMode &&
        cIn[o + 6] === (forceWidth ? 1 : 0) &&
        cIn[o + 7] === (forceHeight ? 1 : 0) &&
        sameFloat(cIn[o]!, availableWidth) &&
        sameFloat(cIn[o + 1]!, availableHeight) &&
        sameFloat(cIn[o + 4]!, ownerWidth) &&
        sameFloat(cIn[o + 5]!, ownerHeight)
      ) {
        layout.width = node._cOut![i * 2]!
        layout.height = node._cOut![i * 2 + 1]!
        _yogaCacheHits++
        return
      }
    }
  }
```

As the inline benchmark note explains, adding the multi-entry cache plus same-generation measure bypass cut a single dirty-leaf relayout in a 500-message scrollbox from **76,000 `layoutNode` visits (6.86 ms) to 4,000 visits (550 µs)**, and cut fresh virtual-scroll mounts from 105,000 visits to ~10,000.

### Hidden Invariants & Failure Modes

- **Never clear `isDirty_` on the measure pass:** `layoutNode()` clears `node.isDirty_ = false` *only* when `performLayout === true` ([native-ts/yoga-layout/index.ts](../../native-ts/yoga-layout/index.ts):1152-1194). Clearing it during the earlier measure pass (`performLayout === false`) lets the layout pass immediately hit a stale `_hasL` entry from the prior frame, so `ScrollBox` content height never grows and sticky-scroll stops following streaming tokens.
- **Explicit reference clearing before Yoga teardown:** Even though TS Yoga is GC-managed, `cleanupYogaNode` ([ink/reconciler.ts](../../ink/reconciler.ts):95-104) still unsets measure functions, recursively nulls `yogaNode` references via `clearYogaNodeReferences()` ([ink/dom.ts](../../ink/dom.ts):446-453), and calls `freeRecursive()`—while `Ink.unmount()` ([ink/ink.tsx](../../ink/ink.tsx):1526) calls `.free()` (not `.freeRecursive()`) on `rootNode` because `removeChildFromContainer` already freed the children, keeping `getYogaCounters().live` accurate as a leak detector.
- **Built-in repaint forensics:** Setting `CLAUDE_CODE_DEBUG_REPAINTS` causes `createInstance` ([ink/reconciler.ts](../../ink/reconciler.ts):354-356) to walk React's internal `_debugOwner` / `return` fiber chain (`getOwnerChain`) and attach `debugOwnerChain` to every DOM node, so `findOwnerChainAtRow(root, triggerY)` ([ink/dom.ts](../../ink/dom.ts):465-484) can blame the exact React component that triggered a scrollback flicker. Setting `CLAUDE_CODE_COMMIT_LOG` logs slow commits, `SLOW_YOGA` (>20 ms with `getYogaCounters()`), and `SLOW_PAINT` (>10 ms).

---

## 2. Painting the Tree: Blitting, ScrollBox Culling, and the Packed `Screen` Buffer

### The Problem

Once Yoga finishes `calculateLayout()`, the renderer must rasterize a tree of styled boxes, wrapped Unicode text, borders, and scrollable viewports into a 2D character grid every 16 ms. Two performance cliffs dominate this stage:

1. **Cell allocation pressure:** A 200×120 terminal has 24,000 cells. Allocating an object per cell per frame (times two frames for diffing) thrashes the nursery allocator and stalls interactive typing.
2. **Wasted re-rasterization:** During token streaming or spinner animation, >95% of the terminal is visually identical to the previous frame—or shifted vertically by $N$ rows during scrolling. Re-running ANSI tokenization, `Intl.Segmenter` grapheme clustering, and bidi reordering across the whole viewport wastes milliseconds on every tick.

### The Real Implementation

#### The Packed 64-Bit-Per-Cell `Screen` Buffer ([ink/screen.ts](../../ink/screen.ts))

`Ink` maintains a double-buffered pair of `Frame` objects (`frontFrame` and `backFrame`, [ink/ink.tsx](../../ink/ink.tsx):99-100) backed by grow-only `Screen` buffers that are zeroed and reused via `resetScreen()` rather than reallocated. Each `Screen` allocates a single `ArrayBuffer` (`width * height * 8` bytes) with **two typed-array views over the same memory**:

- `cells: Int32Array` (2 words per cell) for fast per-cell reads/writes and integer diffing.
- `cells64: BigInt64Array` (1 `BigInt64` per cell) for single-call bulk clears (`cells64.fill(0n, 0, size)`) and in-place row shifting (`cells64.copyWithin(...)` in `shiftRows`).

```ts
// ink/screen.ts:332-348
// Each cell is 2 consecutive Int32 elements in the cells array:
//   word0 (cells[ci]):     charId (full 32 bits)
//   word1 (cells[ci + 1]): styleId[31:17] | hyperlinkId[16:2] | width[1:0]
const STYLE_SHIFT = 17
const HYPERLINK_SHIFT = 2
const HYPERLINK_MASK = 0x7fff // 15 bits
const WIDTH_MASK = 3 // 2 bits

function packWord1(
  styleId: number,
  hyperlinkId: number,
  width: number,
): number {
  return (styleId << STYLE_SHIFT) | (hyperlinkId << HYPERLINK_SHIFT) | width
}
```

Three interning pools—shared across both frames so cell comparisons are pure integer equality—sit beside the buffer:

1. **`CharPool` ([ink/screen.ts](../../ink/screen.ts):21-53):** Reserves index `0` for `' '` and `1` for `''` (spacer cells), with a 128-entry `Int32Array` ASCII fast path bypassing `Map.get`. Because `StylePool.none === 0`, an unwritten cell is `[0, 0]` (`0n`), indistinguishable from an explicitly cleared cell without normalization.
2. **`HyperlinkPool` ([ink/screen.ts](../../ink/screen.ts):57-75):** Reserves `0` for "no hyperlink" and interns URLs into 15-bit IDs. Both `CharPool` and `HyperlinkPool` undergo generational migration (`migrateScreenPools`, [ink/screen.ts](../../ink/screen.ts):554-587) every 5 minutes ([ink/ink.tsx](../../ink/ink.tsx):600-603) so long sessions never leak unique grapheme clusters or URLs.
3. **`StylePool` ([ink/screen.ts](../../ink/screen.ts):112-260):** Session-lived (never reset, so `Output.charCache` can cache `styleId` across frames). Encodes a clever bit-0 invariant: `id = (rawId << 1) | (hasVisibleSpaceEffect ? 1 : 0)`. Styles with background color, inverse, underline, strikethrough, or overline get **odd** IDs; foreground-only styles get **even** IDs. In `visibleCellAtIndex()` ([ink/screen.ts](../../ink/screen.ts):624-650), checking `(word1 & 0x3fffc) === 0` tests hyperlink ID + style visibility bit in one mask so invisible or fg-only spaces can be skipped with cursor-forward instead of allocating a `Cell` view. `StylePool.transition(fromId, toId)` caches the pre-serialized ANSI transition string keyed by `fromId * 0x100000 + toId`.

Two parallel sidecar typed arrays complete `Screen`:
- `noSelect: Uint8Array` (1 byte/cell): Fenced off by `<NoSelect>` (e.g., diff line numbers and `⎿` prefixes).
- `softWrap: Int32Array` (1 Int32/row): `softWrap[r] = N > 0` records that row `r` is a word-wrap continuation of row `r - 1` *and* that row `r - 1`'s actual written content ended at column `N`—solving the ambiguity between unwritten padding spaces and genuine word-separator spaces (both pack as `[0, 0]`) when copying wrapped prose.

#### Deferred Paint Pipeline, Clean-Subtree Blitting, and the ScrollBox Fast Path

[ink/renderer.ts](../../ink/renderer.ts) reuses a single `Output` instance across frames so `Output.charCache` (capped at 16,384 entries, [ink/output.ts](../../ink/output.ts):204) preserves tokenized, grapheme-clustered (`getGraphemeSegmenter()`), bidi-reordered (`reorderBidi()`), pre-interned `ClusteredChar[]` arrays per unique text line. `renderNodeToOutput()` ([ink/render-node-to-output.ts](../../ink/render-node-to-output.ts)) walks the DOM tree and records seven deferred operation types into `Output`: `clear`, `clip`, `unclip`, `blit`, `shift`, `write`, and `noSelect`.

Two optimizations make 60 FPS steady-state rendering possible:

1. **Clean-subtree blitting (`nodeCache`):** Every painted `DOMElement` caches its `{ x, y, width, height, top }` in a `WeakMap` ([ink/node-cache.ts](../../ink/node-cache.ts)). On the next frame, if `!node.dirty`, layout coordinates are unchanged, and `prevScreen` is clean, `renderNodeToOutput()` ([ink/render-node-to-output.ts](../../ink/render-node-to-output.ts):454-482) emits a single `output.blit(prevScreen, fx, fy, fw, fh)`—which executes a contiguous `TypedArray.set()` copy of `cells`, `noSelect`, and `softWrap` in [ink/screen.ts](../../ink/screen.ts):858-952—plus `blitEscapingAbsoluteDescendants()` so floating overlays (like slash-command menus with `position='absolute' bottom='100%'`) survive a parent blit.
2. **DOM-bypass scrolling & three-pass `blit + shift`:** In [ink/components/ScrollBox.tsx](../../ink/components/ScrollBox.tsx):103-117, `scrollTo()` and `scrollBy()` **bypass React's reconciler completely**: they mutate `el.scrollTop` / `el.pendingScrollDelta` on the DOM node, call `markScrollActivity()` (telling background IDE/LSP polls to skip a tick), call `markDirty(el)`, and coalesce multiple wheel events in one `discreteUpdates` batch via `queueMicrotask(() => scheduleRenderFrom(el))`.
   - At paint time ([ink/render-node-to-output.ts](../../ink/render-node-to-output.ts):803-850), `pendingScrollDelta` is drained via `drainProportional` (3/4 of remaining, min 4 rows, capped at `innerHeight - 1` so `DECSTBM` triggers) on native terminals, or `drainAdaptive` (instant for ≤5 rows, 2–3 rows/frame for bursts) on `xterm.js` / VS Code, and visually clamped to `[scrollClampMin, scrollClampMax]` so rapid `PageUp` bursts never flash blank virtual-scroll spacers while React catches up.
   - When the scroll delta fits inside the viewport (`|delta| < innerHeight`) and `heightDelta === 0 || (delta > 0 && heightDelta === delta)`, `renderNodeToOutput()` ([ink/render-node-to-output.ts](../../ink/render-node-to-output.ts):917-1105) records a `ScrollHint` for hardware scrolling and executes a **three-pass fast path**:
     - *Pass 1:* `output.blit` the previous scroll region, `output.shift(top, bottom, delta)` in place, clip strictly to the newly exposed edge rows, and render only children intersecting those edge rows.
     - *Pass 2:* Re-render dirty children in stable rows and any clean children below a mid-list height growth (tracking `cumHeightShift` so bottom-append stays $O(\text{dirty})$ instead of $O(\text{mounted})$).
     - *Pass 3:* Repair rows where shifted copies of `position: absolute` overlays (recorded in `absoluteRectsPrev`) landed inside the scrolled region.

### Hidden Invariants & Failure Modes

- **Wide-character orphan prevention:** Double-wide CJK/emoji characters occupy two cells: `CellWidth.Wide` at `x` and `CellWidth.SpacerTail` at `x + 1` (plus `CellWidth.SpacerHead` at the right margin when a wide char cannot fit at `screenWidth - 1`). Overwriting *either* half in `setCellAt()` ([ink/screen.ts](../../ink/screen.ts):703-808) or clipping across a boundary in `clearRegion()` ([ink/screen.ts](../../ink/screen.ts):998-1028) explicitly clears the orphaned partner cell and expands `screen.damage`—otherwise a lingering `SpacerTail` is skipped by the diff engine and ghosts stale text from prior frames.
- **Blit contamination rules:** `output.clear()` only expands `screen.damage` (because `resetScreen` already zeroed the buffer), so blitting from a polluted `prevScreen` can resurrect deleted overlays. Five guards prevent ghosting: (a) `collectRemovedRects` ([ink/dom.ts](../../ink/dom.ts):225-245) sets a global `absoluteNodeRemoved` flag if *any* removed node or ancestor had `position: 'absolute'`, disabling blit for one frame; (b) `prevFrameContaminated` ([ink/ink.tsx](../../ink/ink.tsx):159, 743) disables blit whenever selection/search overlays mutated `frontFrame` or after alt-screen/resize resets; (c) `renderChildren` ([ink/render-node-to-output.ts](../../ink/render-node-to-output.ts):1257-1294) disables sibling blit after an unclipped dirty child (`seenDirtyChild`) while still allowing clean siblings *after* a both-axis-clipped `ScrollBox` to blit (`seenDirtyClipped` only forces `skipSelfBlit` on non-opaque absolute overlays); (d) `didLayoutShift()` forces full-screen damage in [ink/ink.tsx](../../ink/ink.tsx):559-566 as a correctness backstop against sibling-resize boundary bleed; and (e) `noSelect` ops apply *last* in `Output.get()` ([ink/output.ts](../../ink/output.ts):510-520) so they always override blits.
- **Drain-timer vs. lodash throttle bug:** When `frame.scrollDrainPending` is true, `Ink.onRender()` schedules the next drain frame with `setTimeout(() => this.onRender(), FRAME_INTERVAL_MS >> 2)` (~250 fps floor) rather than `this.scheduleRender()` ([ink/ink.tsx](../../ink/ink.tsx):745-759). Calling lodash's `throttle` from inside its own trailing-edge invocation hits `leadingEdge` immediately, causing back-to-back renders 0.1 ms apart.
- **Sanitizing stray C0/escape bytes:** `writeLineToScreen` ([ink/output.ts](../../ink/output.ts):659-757) expands `\t` to 8-column tab stops, drops `\r`/`\b`/zero-width combining codepoints, and parses/skips any raw CSI/OSC/DCS/APC/PM/SOS sequences that `@alcalzone/ansi-tokenize` left unparsed so untrusted tool output cannot hijack the terminal cursor.

---

## 3. Diffing, Peephole Optimization, Synchronized Output, and Alt-Screen Lifecycle

### The Problem

Having two packed `Screen` buffers is only half the battle. Turning the difference into minimal, flicker-free ANSI bytes requires modeling the terminal's stateful cursor and graphics attributes without ever letting the virtual model diverge from the physical emulator—across `iTerm2`, `Ghostty`, `kitty`, `WezTerm`, `Alacritty`, `VS Code`/`xterm.js`, `tmux`, and Windows Terminal.

### The Real Implementation

#### Zero-Allocation Diffing and Hardware Scrolling ([ink/log-update.ts](../../ink/log-update.ts))

`LogUpdate.render(prev, next, altScreen, decstbmSafe)` translates `(prevFrame, nextFrame)` into a `Patch[]` array:

1. **Resize and offscreen scrollback guards:** On main screen, shrinking height from overflowing-viewport back into viewport, narrowing width, or modifying any row `y < viewportY` (where `viewportY = prev.screen.height - prev.viewport.height + (prevHadScrollback ? 1 : 0)`, accounting for the `+1` row scrolled off by the previous frame's trailing LF) is unreachable via relative cursor moves. `LogUpdate` falls back to `fullResetSequence_CAUSES_FLICKER()` ([ink/log-update.ts](../../ink/log-update.ts):503-513), emitting a `clearTerminal` patch that `Ink.onRender()` records in `FrameEvent.flickers` and attributes via `findOwnerChainAtRow()`.
2. **`DECSTBM` hardware scroll fast path:** When `altScreen && next.scrollHint && decstbmSafe`, `LogUpdate` mutates `prev.screen` with `shiftRows()` to mirror what the terminal is about to do, then prepends a single hardware-scroll patch:

```ts
// ink/log-update.ts:165-185
let scrollPatch: Diff = []
if (altScreen && next.scrollHint && decstbmSafe) {
  const { top, bottom, delta } = next.scrollHint
  if (
    top >= 0 &&
    bottom < prev.screen.height &&
    bottom < next.screen.height
  ) {
    shiftRows(prev.screen, top, bottom, delta)
    scrollPatch = [
      {
        type: 'stdout',
        content:
          setScrollRegion(top + 1, bottom + 1) +
          (delta > 0 ? csiScrollUp(delta) : csiScrollDown(-delta)) +
          RESET_SCROLL_REGION +
          CURSOR_HOME,
      },
    ]
  }
}
```

Because `prev.screen` was shifted in lockstep, the subsequent `diffEach()` sees **only the newly exposed edge rows** (plus any dirty/repaired cells) as changed—cutting scroll output from tens of kilobytes to ~200 bytes. Crucially, `ink.tsx:586-591` passes `decstbmSafe = SYNC_OUTPUT_SUPPORTED`. Under `tmux`, `SYNC_OUTPUT_SUPPORTED` is `false` ([ink/terminal.ts](../../ink/terminal.ts):70-74) because `tmux` chunks proxied output and breaks `DEC 2026` atomicity; omitting `DECSTBM` there avoids flashing blank scrolled edge rows.

3. **Integer-scanned `diffEach` ([ink/screen.ts](../../ink/screen.ts):1156-1372):** Computes the bounding box `unionRect(prev.damage, next.damage)` (plus grown/shrunk edge bands) and scans rows with a tiny JIT-inlinable loop (`findNextDiff`, comparing `a[w0] !== b[w0] || a[w1] !== b[w1]`). It unpacks differing cells into **two reused `Cell` scratch objects**—zero heap allocations per cell diff—and drives `VirtualScreen` to emit relative cursor moves, `StylePool.transition()` strings, hyperlink transitions, and character writes.

#### Single-Pass Patch Optimizer and Synchronized Output ([ink/optimizer.ts](../../ink/optimizer.ts), [ink/terminal.ts](../../ink/terminal.ts))

`optimize(diff)` ([ink/optimizer.ts](../../ink/optimizer.ts):16-93) folds the `Patch[]` list in one pass: stripping empty `stdout`/zero `cursorMove`/`clear(0)`, merging adjacent `cursorMove` vectors, collapsing consecutive `cursorTo`, deduplicating identical `hyperlink` URIs, and cancelling adjacent `cursorHide`/`cursorShow` pairs.

One subtle scar sits at [ink/optimizer.ts](../../ink/optimizer.ts):58-66:

```ts
// ink/optimizer.ts:58-66
// Concat adjacent style patches. styleStr is a transition diff
// (computed by diffAnsiCodes(from, to)), not a setter — dropping
// the first is only sound if its undo-codes are a subset of the
// second's, which is NOT guaranteed. e.g. [\e[49m, \e[2m]: dropping
// the bg reset leaks it into the next \e[2J/\e[2K via BCE.
if (type === 'styleStr' && lastType === 'styleStr') {
  result[lastIdx] = { type: 'styleStr', str: last.str + patch.str }
  continue
}
```

Dropping an earlier `styleStr` would discard its reset codes (like `\x1b[49m`), causing Background Color Erase (BCE) to paint erased rows with a stale background color.

Finally, `writeDiffToTerminal()` ([ink/terminal.ts](../../ink/terminal.ts):190-248) serializes the optimized patches into a **single string** wrapped in `BSU` (`\x1b[?2026h`) and `ESU` (`\x1b[?2026l`)—unless `skipSyncMarkers` is set (alt-screen on non-DEC-2026 terminals like `tmux`)—and flushes it in one `terminal.stdout.write(buffer)` syscall.

#### Alt-Screen (`DEC 1049`), Resize Atomicity, and Native Cursor Parking

Fullscreen mode is mounted declaratively via `<AlternateScreen>` ([ink/components/AlternateScreen.tsx](../../ink/components/AlternateScreen.tsx)), which wraps children in a fixed-height `<Box height={rows} width="100%" flexShrink={0}>` and enters/exits `DEC 1049` inside **`useInsertionEffect`** (not `useLayoutEffect`). Why? Because `react-reconciler` runs `resetAfterCommit()` between the mutation and layout phases; `useLayoutEffect` fires *after* frame 1 has already painted to the main screen, corrupting scrollback when the user later exits. Insertion effects fire during the mutation phase, guaranteeing `ENTER_ALT_SCREEN` lands on stdout before frame 1.

Five cooperating invariants keep alt-screen rendering completely flicker-free and drift-proof:

1. **Fake `viewport.height = terminalRows + 1` & clamped `cursor.y` ([ink/renderer.ts](../../ink/renderer.ts):152-175):** `shouldClearScreen()` treats `screen.height >= viewport.height` as main-screen scrollback overflow. Adding `+1` prevents spurious `fullResetSequence_CAUSES_FLICKER`, while clamping `cursor.y` to `terminalRows - 1` keeps the cursor inside the viewport so no trailing LF scrolls the alt buffer.
2. **Blank `rows×cols` seed frames (`resetFramesForAltScreen`, [ink/ink.tsx](../../ink/ink.tsx):984-1009):** Seeding `frontFrame` as `0×0` would make `LogUpdate` see `heightDelta > 0` (`growing`) and run `renderFrameSlice`, whose per-row `\r\n` on the final row scrolls the alt buffer by one row. Seeding a full `rows×cols` blank buffer forces `heightDelta === 0` so every cell writes via cursor positioning without ever emitting LF.
3. **Self-healing `CSI H` anchor & bottom park ([ink/ink.tsx](../../ink/ink.tsx):45-66, 568-584, 624-651):** Every non-empty alt-screen diff is computed from `ALT_SCREEN_ANCHOR_CURSOR` `(0, 0)`, prefixed with `CSI H` (healing any out-of-band cursor drift from `tmux` status bars or pane redraws), and suffixed with `cursorPosition(terminalRows, 1)` so `iTerm2`'s cursor guide doesn't jump wildly around the viewport.
4. **Atomic resize erase (`handleResize` + `needsEraseBeforePaint`, [ink/ink.tsx](../../ink/ink.tsx):309-346, 636-649):** `handleResize` is deliberately **not debounced** (debouncing opens a window where `stdout.columns` is new while Yoga is old, triggering a double clear-flicker). It never writes `ENTER_ALT_SCREEN` (iTerm2 treats `?1049h` as a buffer clear even when already in alt-screen) and never writes `ERASE_SCREEN` synchronously (which would leave the terminal blank during the ~80 ms React re-render). Instead it sets `needsEraseBeforePaint = true`, prepending `ERASE_SCREEN + CURSOR_HOME` *inside* the next frame's `BSU`/`ESU` block so clear + paint swap atomically.
5. **Native cursor parking (`useDeclaredCursor` + `displayCursor`, [ink/ink.tsx](../../ink/ink.tsx):660-734):** After the diff, `onRender` looks up the declared node's fresh screen rect in `nodeCache`, moves the physical terminal cursor to `(rect.x + relativeX, rect.y + relativeY)` so OS CJK IME preedit overlays and screen magnifiers track the input caret, and remembers `this.displayCursor` on main-screen so the *next* frame's preamble moves back to `prevFrame.cursor` before relative diffs execute.

### Hidden Invariants & Failure Modes

- **Emoji `wcwidth` drift compensation ([ink/log-update.ts](../../ink/log-update.ts):662-681, 733-750):** For Unicode 12+ pictographs (`U+1FA70–U+1FBFF`) and text-by-default emoji carrying VS16 (`U+FE0F`, e.g., `⚔️`, `❤️`), older terminal `wcwidth` tables advance the cursor 1 column instead of 2. `writeCellWithStyleStr` writes a styled space at `col + 1`, moves back, writes the glyph, and emits `CHA` (`cursorTo(px + 3)`) to force-lock the terminal cursor column. On modern terminals the `CHA` is a harmless no-op; on old terminals it prevents permanent row corruption.
- **Stray `stderr` interception ([ink/ink.tsx](../../ink/ink.tsx):1604-1639):** `patchConsole()` only intercepts `console.*`, not direct `process.stderr.write()` calls from dependencies. `patchStderr()` intercepts raw stderr writes (with a `reentered` guard so `--debug-to-stderr` doesn't stack-overflow), routes them to the debug log, and sets `prevFrameContaminated = true` + `scheduleRender()` in alt-screen to heal any damage.
- **Kitty keyboard stack balance & external editor handoff ([ink/ink.tsx](../../ink/ink.tsx):357-419, 875-919):** Unlike idempotent DEC private modes, Kitty's `CSI >1u` (`ENABLE_KITTY_KEYBOARD`) pushes onto a **stack**. Whenever Ink re-asserts terminal modes—after returning from an external editor (`exitAlternateScreen`), `SIGCONT`, or a >5-second stdin silence gap (`STDIN_RESUME_GAP_MS = 5000` in [ink/components/App.tsx](../../ink/components/App.tsx):35, catching `tmux` detach/reattach, SSH reconnect, and laptop sleep/wake)—it writes `DISABLE_KITTY_KEYBOARD + ENABLE_KITTY_KEYBOARD + ENABLE_MODIFY_OTHER_KEYS` (**pop before push**). Because popping an empty stack is a spec no-op, stack depth stays pinned at 1 and a single pop on exit leaves the user's shell clean.
- **Shutdown cleanup and non-blocking `/dev/tty` drain ([ink/ink.tsx](../../ink/ink.tsx):921-950, 1480-1505, 1664-1718):** `unmount()` uses synchronous `writeSync(1, ...)` to exit alt-screen *first*, unconditionally disable mouse tracking, Kitty, `modifyOtherKeys`, focus events (`DFE`), bracketed paste (`DBP`), restore the cursor, and clear iTerm2 progress / OSC 21337 tab status. It then runs `drainStdin()`, which briefly re-enters raw mode and opens a fresh `/dev/tty` descriptor with `O_RDONLY | O_NONBLOCK` (bounded to 64×1 KB reads) to drain kernel-buffered in-flight mouse bytes so they never spill onto the shell prompt. `detachForShutdown()` prevents `signal-exit` from running a duplicate `EXIT_ALT_SCREEN` after `gracefulShutdown` has already printed the resume hint.

---

## 4. Terminal I/O Protocols: Keyboard Parsing, Querying, Focus, Mouse Hit-Testing, Selection, and Hyperlinks

### The Problem

Everything coming back from the terminal—human keystrokes, multi-kilobyte pastes, SGR/X10 mouse coordinates, focus gain/loss notifications, and responses to capability queries—arrives concatenated over a single raw-mode `stdin` stream, arbitrarily fragmented across `read()` chunks. Worse, once alt-screen mouse tracking is enabled, the application owns *every* pointer interaction: clicking buttons, hovering, single/double/triple-click selection, drag-to-scroll, and opening links.

### The Real Implementation

#### Streaming Tokenization, Extended Keys, and Batch Dispatch ([ink/termio/tokenize.ts](../../ink/termio/tokenize.ts), [ink/parse-keypress.ts](../../ink/parse-keypress.ts), [ink/components/App.tsx](../../ink/components/App.tsx))

When any component enables raw mode (reference-counted via `rawModeEnabledCount` in [ink/components/App.tsx](../../ink/components/App.tsx):209-280), `App` stops early-input capture (`stopCapturingEarlyInput()`), puts `stdin` into raw UTF-8 mode, enables bracketed paste (`EBP`), DECSET 1004 focus reporting (`EFE`), and—for allowlisted emulators (`EXTENDED_KEYS_TERMINALS`: `iTerm.app`, `kitty`, `WezTerm`, `ghostty`, `tmux`, `windows-terminal` in [ink/terminal.ts](../../ink/terminal.ts):156-169)—writes both `ENABLE_KITTY_KEYBOARD` (`CSI >1u`) and `ENABLE_MODIFY_OTHER_KEYS` (`CSI >4;2m`).

Incoming chunks flow through `createTokenizer({ x10Mouse: true })` ([ink/termio/tokenize.ts](../../ink/termio/tokenize.ts)), an 8-state streaming scanner (`ground`, `escape`, `escapeIntermediate`, `csi`, `ss3`, `osc`, `dcs`, `apc`) that splits raw bytes into `{ type: 'text' }` and `{ type: 'sequence' }` tokens while buffering incomplete escape sequences across chunks. `x10Mouse: true` is strictly stdin-only: `\x1b[M` consumes 3 payload bytes on stdin (X10 mouse), whereas on stdout `\x1b[M` is CSI Delete Lines!

`parseMultipleKeypresses()` ([ink/parse-keypress.ts](../../ink/parse-keypress.ts):213-302) turns tokens into a discriminated union `ParsedInput = ParsedKey | ParsedMouse | ParsedResponse`:

```ts
// ink/parse-keypress.ts:247-283 (condensed)
const response = parseTerminalResponse(token.value)
if (response) {
  keys.push({ kind: 'response', sequence: token.value, response })
} else {
  const mouse = parseMouseEvent(token.value)
  if (mouse) {
    keys.push(mouse)
  } else {
    keys.push(parseKeypress(token.value))
  }
}
```

Key protocol details handled in `parseKeypress()` ([ink/parse-keypress.ts](../../ink/parse-keypress.ts):611-785):
- **Bracketed paste (`CSI 200~` … `CSI 201~`):** Switches parser state to `IN_PASTE`, accumulates all sequences literally into `pasteBuffer`, and emits a single `ParsedKey` with `isPasted: true`—even when empty, so macOS image-paste handlers can trigger on an empty clipboard text paste.
- **Kitty `CSI u` (`\x1b[codepoint[;modifier]u`) & xterm `modifyOtherKeys` (`\x1b[27;modifier;keycode~`):** Decodes XTerm bitmask modifiers (`m = modifier - 1`: shift=1, meta/alt=2, ctrl=4, super=8) and Kitty Private Use Area numpad codepoints (`57399–57415`). Note that `modifyOtherKeys` puts `modifier` *before* `keycode` (the reverse of `CSI u`) and must run before `FN_KEY_RE`.
- **iTerm2 natural editing:** Translates `\x1bb` / `\x1bf` into `meta+left` / `meta+right`.
- **Mouse split:** SGR mouse events (`\x1b[<btn;col;row[Mm]`) with wheel bit `0x40` stay `ParsedKey` (`wheelup`/`wheeldown`) so they flow cleanly through the keybinding system; clicks, drags (`0x20`), releases, and mode-1003 hover motions (`0x20 | 3`) become `ParsedMouse` routed to `handleMouseEvent()`.
- **Single-batch `discreteUpdates` + Bun recovery:** [ink/components/App.tsx](../../ink/components/App.tsx):319-321 wraps the entire parsed batch in one `reconciler.discreteUpdates(processKeysInBatch, ...)` call to prevent "Maximum update depth exceeded" during fast pastes. `handleReadable` ([ink/components/App.tsx](../../ink/components/App.tsx):348-367) wraps `stdin.read()` in `try/catch` and re-attaches the `'readable'` listener on error—working around a Bun runtime bug where an uncaught throw inside `'readable'` permanently wedges stdin.

#### Timeout-Free Terminal Capability Querying ([ink/terminal-querier.ts](../../ink/terminal-querier.ts))

Environment variables like `TERM_PROGRAM` do not survive `ssh`. Immediately after enabling raw mode, `App` fires an in-band `XTVERSION` query (`CSI > 0 q`) through `TerminalQuerier` ([ink/components/App.tsx](../../ink/components/App.tsx):253-262) so `isXtermJs()` detects VS Code / Cursor / Windsurf even across remote SSH hops.

How do you know if a terminal ignored a query without waiting on a fragile timeout? Every VT100-compatible terminal answers Primary Device Attributes (`DA1`, `CSI c`), and terminals answer queries in FIFO order. `TerminalQuerier.flush()` appends a `DA1` sentinel to the queue:

```ts
// ink/terminal-querier.ts:195-211
onResponse(r: TerminalResponse): void {
  const idx = this.queue.findIndex(p => p.kind === 'query' && p.match(r))
  if (idx !== -1) {
    const [q] = this.queue.splice(idx, 1)
    if (q?.kind === 'query') q.resolve(r)
    return
  }

  if (r.type === 'da1') {
    const s = this.queue.findIndex(p => p.kind === 'sentinel')
    if (s === -1) return
    for (const p of this.queue.splice(0, s + 1)) {
      if (p.kind === 'query') p.resolve(undefined)
      else p.resolve()
    }
  }
}
```

If `XTVERSION` (`DCS > | xterm.js(5.5.0) ST`) arrives before `DA1`, it resolves with the version string; if `DA1` arrives first, all preceding unmatched queries resolve immediately to `undefined` in a single PTY round-trip.

#### Two-Layer Focus Tracking and Capture/Bubble Events

1. **Terminal window focus (DECSET 1004):** `FOCUS_IN` (`CSI I`) and `FOCUS_OUT` (`CSI O`) update a lightweight module-level store in [ink/terminal-focus-state.ts](../../ink/terminal-focus-state.ts) (`'focused' | 'blurred' | 'unknown'`, where `'unknown'` behaves as focused). [ink/components/TerminalFocusContext.tsx](../../ink/components/TerminalFocusContext.tsx) subscribes via `useSyncExternalStore` inside a separate provider component so focus flips never re-render `App` itself—only consumers like `ClockProvider` (which throttles animation timers when blurred). Receiving any keypress while blurred self-heals focus back to `true` ([ink/components/App.tsx](../../ink/components/App.tsx):495-497).
2. **DOM element focus & event dispatch ([ink/focus.ts](../../ink/focus.ts), [ink/events/dispatcher.ts](../../ink/events/dispatcher.ts)):** `ink-root` owns a `FocusManager` tracking `activeElement` and a deduplicated `focusStack` (max depth 32). When a modal unmounts, `reconciler.removeChild` calls `handleNodeRemoved()`, which blurs the removed element and pops the stack back to the most recent still-mounted ancestor. Keyboard events dispatch via `Dispatcher.dispatchDiscrete(activeElement ?? rootNode, event)` using `react-dom`'s two-phase accumulation (`[root-cap, ..., target-cap, target-bub, ..., root-bub]`); if no handler calls `preventDefault()`, `Ink.dispatchKeyboardEvent` ([ink/ink.tsx](../../ink/ink.tsx):1269-1283) runs browser-style `Tab`/`Shift+Tab` cycling across `tabIndex >= 0` nodes.

#### Mouse Hit-Testing and Hover ([ink/hit-test.ts](../../ink/hit-test.ts))

In alt-screen, `nodeCache` rects map 1:1 to screen coordinates (with `-scrollTop` already applied). `hitTest()` traverses `childNodes` in **reverse order** so later siblings (painted on top, including overlays) win:

```ts
// ink/hit-test.ts:18-41
export function hitTest(
  node: DOMElement,
  col: number,
  row: number,
): DOMElement | null {
  const rect = nodeCache.get(node)
  if (!rect) return null
  if (
    col < rect.x ||
    col >= rect.x + rect.width ||
    row < rect.y ||
    row >= rect.y + rect.height
  ) {
    return null
  }
  // Later siblings paint on top; reversed traversal returns topmost hit.
  for (let i = node.childNodes.length - 1; i >= 0; i--) {
    const child = node.childNodes[i]!
    if (child.nodeName === '#text') continue
    const hit = hitTest(child, col, row)
    if (hit) return hit
  }
  return node
}
```

`dispatchClick()` finds the closest ancestor with a numeric `tabIndex` for click-to-focus, then bubbles a `ClickEvent` with per-target `localCol = col - rect.x` and `localRow = row - rect.y`. `dispatchHover()` diffs the ancestor chain of hover-listening nodes against `Ink.hoveredNodes`, firing non-bubbling `onMouseLeave` (skipping detached nodes) and `onMouseEnter` on mode-1003 motion events.

#### Fullscreen Text Selection, Scroll-Off Capture, and Clipboard ([ink/selection.ts](../../ink/selection.ts))

[ink/selection.ts](../../ink/selection.ts) implements a complete terminal-native linear selection engine owned by `Ink`:

- **Multi-click on press, not release:** `handleMouseEvent` ([ink/components/App.tsx](../../ink/components/App.tsx):570-595) detects double-click (word) and triple-click (line) within `MULTI_CLICK_TIMEOUT_MS = 500` and `MULTI_CLICK_DISTANCE = 1` on mouse *press* so the highlight appears immediately and dragging extends word-by-word or line-by-line around `anchorSpan`. `WORD_CHAR = /[\p{L}\p{N}_/.\-+~\\]/u` mirrors iTerm2's default so double-clicking `/usr/bin/bash` selects the whole path.
- **Sub-pixel tremor & lost-release recovery:** Mode-1002 drag events at the exact anchor cell are ignored before focus is set (`updateSelection`, [ink/selection.ts](../../ink/selection.ts):111-112) so bare clicks never turn into 1-cell selections that clobber the clipboard. If the user releases the mouse outside the terminal window (where emulators drop the SGR `'m'` release), both `FOCUS_OUT` and the next mode-1003 no-button motion event (`button & 0x20 && baseButton === 3`) call `finishSelection()` so drag-to-scroll timers never run away ([ink/components/App.tsx](../../ink/components/App.tsx):480-488, 528-538).
- **Scroll-off accumulation with virtual clamp debt:** Because `Screen` holds only the visible viewport, both drag-to-scroll and streaming auto-follow (`consumeFollowScroll()` in [ink/ink.tsx](../../ink/ink.tsx):462-513) call `captureScrolledRows()` on `this.frontFrame.screen` *before* the front/back buffer swap, appending outgoing lines and their `softWrap` flags into `scrolledOffAbove`/`scrolledOffBelow`, paired with `shiftAnchor()` / `shiftSelectionForFollow()`. Keyboard scrolling (`shiftSelection`, [ink/selection.ts](../../ink/selection.ts):470-565) tracks `virtualAnchorRow`/`virtualFocusRow` (pre-clamp coordinates) so scrolling down (`PgDn`) and back up (`PgUp`) pops rows cleanly off the accumulator instead of double-counting them.
- **Logical-line copy & theme-aware overlay:** `getSelectedText()` skips `noSelect` cells and `SpacerTail`/`SpacerHead` cells, reads `screen.softWrap[row + 1]` to preserve trailing word-separator spaces on wrapped rows, and concatenates `softWrap[row] > 0` continuations without inserting spurious newlines. Visually, `applySelectionOverlay` replaces each cell's `styleId` via `StylePool.withSelectionBg` (theme-aware solid background preserving syntax-highlighted foregrounds, falling back to SGR 7 inverse before the theme loads). Copying via `setClipboard()` ([ink/termio/osc.ts](../../ink/termio/osc.ts):138-158) fires native `pbcopy`/`wl-copy`/`xclip`/`xsel`/`clip` *first* (gated on `!SSH_CONNECTION`, not `SSH_TTY`, because tmux clears `SSH_CONNECTION` on local reattach), then runs `tmux load-buffer` (omitting `-w` under iTerm2 because tmux's empty-param OSC 52 crashes iTerm2 over SSH), and returns DCS-passthrough-wrapped OSC 52.

#### OSC 8 Hyperlinks and Plain-Text URL Fallback

`<Link>` ([ink/components/Link.tsx](../../ink/components/Link.tsx)) renders `<ink-link href={url}>` when `supportsHyperlinks()` ([ink/supports-hyperlinks.ts](../../ink/supports-hyperlinks.ts)) detects support via `supports-hyperlinks` plus `ADDITIONAL_HYPERLINK_TERMINALS` (`ghostty`, `Hyper`, `kitty`, `alacritty`, `iTerm.app`, `iTerm2`, checked against `TERM_PROGRAM`, tmux-surviving `LC_TERMINAL`, and `TERM` for kitty).

During text wrapping ([ink/render-node-to-output.ts](../../ink/render-node-to-output.ts):585-592), each wrapped line is individually wrapped in `\x1b]8;;url\x07...\x1b]8;;\x07` so `Output.flushBuffer` extracts the URL into `HyperlinkPool` on every cell. At terminal output time, `termio/osc.ts` attaches a deterministic `id=` parameter so terminals treat wrapped lines as one unified clickable link:

```ts
// ink/termio/osc.ts:403-417
export function link(url: string, params?: Record<string, string>): string {
  if (!url) return LINK_END
  const p = { id: osc8Id(url), ...params }
  const paramStr = Object.entries(p)
    .map(([k, v]) => `${k}=${v}`)
    .join(':')
  return osc(OSC.HYPERLINK, paramStr, url)
}

function osc8Id(url: string): string {
  let h = 0
  for (let i = 0; i < url.length; i++)
    h = ((h << 5) - h + url.charCodeAt(i)) | 0
  return (h >>> 0).toString(36)
}
```

In fullscreen mode, where mouse tracking intercepts the terminal's native Cmd+Click, single-clicks that aren't consumed by a DOM `onClick` handler synchronously query `Ink.getHyperlinkAt(col, row)` ([ink/ink.tsx](../../ink/ink.tsx):1293-1304): it checks the cell's OSC 8 hyperlink (stepping left on `SpacerTail`), then falls back to `findPlainTextUrlAt()` ([ink/selection.ts](../../ink/selection.ts):272-359), which scans ASCII URL runs and strips unbalanced trailing punctuation (`.,;:!?` and unmatched `)]}`). Browser launch is deferred by `MULTI_CLICK_TIMEOUT_MS` (500 ms) so double-clicking a URL selects the word without launching a browser—and is **disabled entirely on `xterm.js` / VS Code** ([ink/components/App.tsx](../../ink/components/App.tsx):632-643) because `xterm.js`'s `Linkifier` opens Cmd+Click URLs *without* stopping SGR mouse propagation, which would otherwise open every link twice.

### Hidden Invariants & Failure Modes

- **50 ms escape flush vs. Node's event-loop phases ([ink/components/App.tsx](../../ink/components/App.tsx):283-306, [ink/parse-keypress.ts](../../ink/parse-keypress.ts):262-279):** Because Node executes the `timers` phase *before* the `poll` phase, a >50 ms render stall can fire `incompleteEscapeTimer` while the rest of an SGR mouse sequence (`[<64;74;16M`) is already sitting in `stdin`'s buffer—splitting it into a bogus `Escape` key plus literal text. `flushIncomplete` checks `this.props.stdin.readableLength > 0` and re-arms instead of flushing; as a second line of defense, `parseMultipleKeypresses` re-synthesizes orphaned SGR/wheel-X10 tails back into mouse events (restricting X10 `Cb` to the wheel range `[\x60-\x7f]` so typed strings like `[MAX]` are never swallowed as phantom clicks).
- **Non-alphanumeric key leak guard:** `nonAlphanumericKeys` ([ink/parse-keypress.ts](../../ink/parse-keypress.ts):408-421) explicitly appends `'escape'` and `'backspace'` (not present in `keyName`), preventing `Ctrl+Escape` via Kitty/`modifyOtherKeys` from leaking the literal string `"escape"` into text input.

---

## Putting the Layer Together

The entire `ink/` subsystem forms a closed bidirectional loop between `stdin` and `stdout`, with a fast DOM-only bypass for 60–250 fps scrolling:

```mermaid
flowchart TD
    STDIN["stdin raw bytes"] --> TOK["termio/tokenize.ts (8-state VT scanner)"]
    TOK --> PARSE["parse-keypress.ts (CSI-u / modifyOtherKeys / paste / SGR mouse / responses)"]
    PARSE -->|"kind: response"| QUERIER["TerminalQuerier (DA1 sentinel barrier)"]
    PARSE -->|"FOCUS_IN / FOCUS_OUT"| TFOCUS["terminal-focus-state.ts (useSyncExternalStore)"]
    PARSE -->|"kind: mouse"| MOUSE["App.tsx handleMouseEvent (hitTest / hover / selection / links)"]
    PARSE -->|"kind: key"| BATCH["reconciler.discreteUpdates (EventEmitter + Dispatcher capture/bubble)"]

    BATCH --> REACT["React 19 Tree + reconciler.ts"]
    REACT -->|"commitUpdate / createInstance"| DOM["ink/dom.ts (7 element types + dirty flags)"]
    MOUSE -->|"ScrollBox.scrollBy (bypass React)"| DOM
    DOM -->|"resetAfterCommit"| YOGA["native-ts/yoga-layout (pure-TS flexbox + gen cache)"]
    YOGA -->|"throttled queueMicrotask"| RENDER["render-node-to-output.ts (nodeCache blit / ScrollBox 3-pass shift)"]
    RENDER --> OUT["Output.get() (charCache + grapheme/bidi + clips)"]
    OUT --> SCR["Screen (packed Int32Array/BigInt64Array + noSelect/softWrap)"]
    SCR --> OVERLAY["Selection & Search Overlays (alt-screen)"]
    OVERLAY --> DIFF["LogUpdate.render() (DECSTBM + damage-bounded diffEach)"]
    DIFF --> OPT["optimize() (peephole merge + BCE-safe styleStr concat)"]
    OPT --> WRITE["writeDiffToTerminal() (single write wrapped in BSU/ESU)"]
    WRITE --> STDOUT["stdout PTY"]
```

At the center of that pipeline sits the packed 8-byte cell layout in [ink/screen.ts](../../ink/screen.ts) that makes both blitting and integer diffing allocation-free:

```text
Screen backing ArrayBuffer (8 bytes / cell; width * height cells)
+-----------------------------------+-----------------------------------+
| word0: cells[ci] (Int32)          | word1: cells[ci + 1] (Int32)      |
| [ 31 ......................... 0 ]| [31..17]     [16..2]       [1..0] |
|          charId (CharPool)        | styleId      hyperlinkId   width  |
|   0 = ' ' (space), 1 = '' (spacer)| (bit 0 =     (0 = none)    0=Narr |
|                                   |  visOnSpace)               1=Wide |
|                                   |                            2=Tail |
|                                   |                            3=Head |
+-----------------------------------+-----------------------------------+
|<------------ cells64[i]: single BigInt64 (0n = empty cell) ---------->|

Parallel sidecars:
  noSelect : Uint8Array(width * height)  -> 1 = excluded from selection/copy
  softWrap : Int32Array(height)          -> N>0 = row continues prev (end col N)
```

---

## How This Snaps Into the Next Layer

Application code outside `ink/` rarely imports `ink/root.ts` or `ink/ink.tsx` directly. Instead, it goes through the top-level barrel [ink.ts](../../ink.ts), which wraps `ink/root.ts`'s `render()` and `createRoot()` in `ThemeProvider` (keeping `ink/` itself theme-agnostic) and re-exports themed `Box`/`Text` alongside `useInput`, `useSelection`, `useTerminalFocus`, `useAnimationFrame`, `RawAnsi`, `NoSelect`, and `Link`.

When starting an interactive session, `main.tsx` calls `createRoot()` from [ink.ts](../../ink.ts) and hands the resulting `Root` to `launchRepl()` in [replLauncher.tsx](../../replLauncher.tsx):12-22, which dynamically imports and mounts `<App>` ([components/App.tsx](../../components/App.tsx)) wrapping `<REPL>` ([screens/REPL.tsx](../../screens/REPL.tsx)). In [Chapter 21](21-the-interactive-repl-screens-keybindings-and-vim.md), we step right across that boundary to see how the interactive REPL turns this 60 FPS terminal engine into a full coding workspace with modal dialogs, keybinding contexts, and a pure-functional Vim editor.

---

## Reading Exercises & Code Checkpoints

1. **Trace a zero-React-commit scroll frame.** Read `scrollMutated` in [ink/components/ScrollBox.tsx](../../ink/components/ScrollBox.tsx):103-117, follow `scheduleRenderFrom` in [ink/dom.ts](../../ink/dom.ts):419-423, and trace how `renderNodeToOutput` ([ink/render-node-to-output.ts](../../ink/render-node-to-output.ts):852-957) emits `ScrollHint` and hands off to `LogUpdate.render` ([ink/log-update.ts](../../ink/log-update.ts):165-185). Under what exact condition does `safeForFastPath` clear `scrollHint = null`?
2. **Audit every terminal capability check.** Run:
   ```sh
   rg -n "TERM_PROGRAM|TMUX|WT_SESSION|SSH_CONNECTION|XTVERSION|isXtermJs" ink/
   ```
   Verify why `setClipboard` checks `SSH_CONNECTION` instead of `SSH_TTY`, why `SYNC_OUTPUT_SUPPORTED` returns `false` under `TMUX`, and why `App.tsx` suppresses hyperlink opening when `isXtermJs()` is true.
3. **Inspect the blit-safety guards.** Run:
   ```sh
   rg -n "prevFrameContaminated|absoluteNodeRemoved|didLayoutShift|seenDirtyClipped" ink/
   ```
   Trace what happens on Frame $N$ and Frame $N+1$ when a user clears a fullscreen text selection or unmounts an absolute-positioned autocomplete menu.
4. **Verify pure-TS Yoga's generation cache invariant.** Read [native-ts/yoga-layout/index.ts](../../native-ts/yoga-layout/index.ts):1086-1195 and explain why `sameGen` is gated on `!performLayout` and why `isDirty_` must remain `true` until the layout pass begins.


---

<!-- chapters/21-the-interactive-repl-screens-keybindings-and-vim.md — https://reverseengineeringclaudecode.com/chapters/21-the-interactive-repl-screens-keybindings-and-vim -->

# Chapter 21 — The Interactive REPL: Screens, Input, Keybindings, and Vim Mode

> **Layer:** Layer 7 (The Terminal UI Engine)
> **Prerequisites:** [Chapter 01](01-atoms-types-stores-and-primitives.md), [Chapter 03](03-command-and-message-contracts.md), [Chapter 07](07-the-heartbeat-query-loop.md), [Chapter 11](11-the-permission-engine.md), [Chapter 20](20-inside-ink-terminal-react-renderer.md)
> **Primary Source Files:**
> - [replLauncher.tsx](../../replLauncher.tsx) — lazy dynamic import boundary that mounts `<App>` + `<REPL>` after setup dialogs finish
> - [interactiveHelpers.tsx](../../interactiveHelpers.tsx) — sequential setup-screen runner (`showSetupScreens`), workspace trust boundary, Ink-safe exit helpers, and frame-telemetry wiring
> - [components/App.tsx](../../components/App.tsx) — top-level provider stack (`FpsMetricsProvider` → `StatsProvider` → `AppStateProvider`)
> - [screens/REPL.tsx](../../screens/REPL.tsx) — the interactive orchestrator bridging `query()`, streaming deltas, modal dialogs, permission queues, and `PromptInput`
> - [utils/QueryGuard.ts](../../utils/QueryGuard.ts) — synchronous 3-state generation-numbered lifecycle guard exposed via `useSyncExternalStore`
> - [utils/handlePromptSubmit.ts](../../utils/handlePromptSubmit.ts) — unified submission, mid-turn queueing, immediate `local-jsx` dispatch, and `processUserInput()` driver
> - [utils/messageQueueManager.ts](../../utils/messageQueueManager.ts) & [hooks/useQueueProcessor.ts](../../hooks/useQueueProcessor.ts) — priority command queue (`now > next > later`) and idle auto-drain loop
> - [hooks/useMergedCommands.ts](../../hooks/useMergedCommands.ts), [hooks/useMergedTools.ts](../../hooks/useMergedTools.ts), & [utils/toolPool.ts](../../utils/toolPool.ts) — live merging of built-in, plugin, and MCP capabilities with cache-safe tool partitioning
> - [components/Messages.tsx](../../components/Messages.tsx), [components/VirtualMessageList.tsx](../../components/VirtualMessageList.tsx), & [hooks/useVirtualScroll.ts](../../hooks/useVirtualScroll.ts) — memoized transcript pipeline, fullscreen height-cached virtualization, and main-screen UUID-anchored render cap
> - [components/PromptInput/PromptInput.tsx](../../components/PromptInput/PromptInput.tsx), [inputModes.ts](../../components/PromptInput/inputModes.ts), & [inputPaste.ts](../../components/PromptInput/inputPaste.ts) — prompt editor shell, paste/image pills, undo, stash, history, and queue pop-to-edit
> - [keybindings/schema.ts](../../keybindings/schema.ts), [defaultBindings.ts](../../keybindings/defaultBindings.ts), [resolver.ts](../../keybindings/resolver.ts), [match.ts](../../keybindings/match.ts), [KeybindingContext.tsx](../../keybindings/KeybindingContext.tsx), [KeybindingProviderSetup.tsx](../../keybindings/KeybindingProviderSetup.tsx), [useKeybinding.ts](../../keybindings/useKeybinding.ts), [loadUserBindings.ts](../../keybindings/loadUserBindings.ts), & [reservedShortcuts.ts](../../keybindings/reservedShortcuts.ts) — context-aware chorded keybinding engine with hot-reload
> - [vim/types.ts](../../vim/types.ts), [vim/motions.ts](../../vim/motions.ts), [vim/textObjects.ts](../../vim/textObjects.ts), [vim/operators.ts](../../vim/operators.ts), [vim/transitions.ts](../../vim/transitions.ts), [hooks/useVimInput.ts](../../hooks/useVimInput.ts), & [components/VimTextInput.tsx](../../components/VimTextInput.tsx) — pure-functional Vim state machine bridged into the terminal prompt editor

> [!NOTE]
> **Snapshot boundaries & compiled `.tsx` output:** Three type-only modules imported by this layer—`types/message.ts`, `types/messageQueueTypes.ts`, and `keybindings/types.ts`—are **absent from this source snapshot**; their shapes are observed directly at call sites and in companion runtime schemas ([keybindings/schema.ts](../../keybindings/schema.ts), [keybindings/validate.ts](../../keybindings/validate.ts), [utils/messageQueueManager.ts](../../utils/messageQueueManager.ts)). Additionally, `.tsx` files in this checkout contain React Compiler memoization transforms (`const $ = _c(N)`) and inline base64 source maps; all descriptions and excerpts below refer strictly to the underlying application logic, never compiler-emitted cache arrays.

---

## Why This Layer Exists

By the end of [Chapter 20](20-inside-ink-terminal-react-renderer.md), we have a custom 60 FPS terminal React renderer (`ink/`) with Yoga flexbox layout, mouse hit-testing, synchronized output, and Kitty keyboard parsing. From Layers 0–6, we have a pull-based `query()` async generator ([Chapter 07](07-the-heartbeat-query-loop.md)), a multi-mode permission engine ([Chapter 11](11-the-permission-engine.md)), dynamic MCP/plugin discovery ([Chapters 15–16](15-model-context-protocol-mcp.md)), and background tasks/swarms ([Chapters 17–19](17-background-task-runtime.md)).

Gluing an asynchronous, streaming agent engine to a reactive terminal UI is where clean abstractions collide with human timing:

1. **Startup trust vs. bundle weight.** Before the workspace is trusted, the harness cannot apply repo environment variables, start OTel helpers, or pay the parse cost of the 5,000-line `REPL.tsx` module graph—yet it still needs interactive dialogs rendered through the same Ink root.
2. **React batching vs. synchronous concurrency.** React `useState` updates asynchronously; `query()`, permission prompts, `Esc` cancellations, and rapid follow-up submits happen synchronously across microtask boundaries. One desynced loading boolean produces duplicate turns, stale `finally` cleanups, or a 56-year elapsed timer.
3. **Unbounded transcript growth vs. terminal memory.** Mounting one React/Yoga subtree per message costs ~250 KB RSS each. Without virtualization (fullscreen) or a stable render-window cap (main screen), long sessions enter a GC death spiral.
4. **Overlapping keybindings, chords, and modal Vim editing.** Eighteen UI contexts share `Escape`, `Enter`, `Tab`, and arrow keys; multi-key chords like `ctrl+x ctrl+k` must stop their second key from landing in the text box; and Vim commands like `2d3w` or `ci"` must run faster than React re-renders without corrupting inline `[Image #N]` pills or wrapped terminal lines.

This chapter dissects the five subsystems that make the interactive REPL hold together under real terminal workloads.

---

## 1. Mounting the Workspace: Setup Screens, Lazy REPL Launch, and Live Capability Merging

### The Problem

When `main.tsx` enters interactive mode, it allocates a single Ink `Root`, runs up to half a dozen sequential consent/onboarding screens (theme onboarding, workspace trust, `.mcp.json` server approval, external `CLAUDE.md` includes, custom API key approval, bypass-permissions/auto-mode consent, dev channels), and only then mounts the REPL. If any of those screens statically imported `screens/REPL.tsx`, users sitting at a first-run trust dialog would pay the entire REPL + prompt-input + markdown + tool-UI import cost upfront—and if a fatal error occurred after `createRoot()`, calling `console.error()` would vanish silently because Ink's `patchConsole` intercepts stdout/stderr.

Once `<REPL>` does mount, MCP servers and plugins finish connecting asynchronously in the background. The UI must merge newly discovered tools and slash commands into the active session without reordering built-in tools (which would invalidate the Anthropic prompt cache prefix established in [Chapter 02](02-the-tool-contract.md) and [Chapter 04](04-prompt-engineering-and-cache-boundaries.md)).

### The Real Implementation

Interactive bootstrapping is split cleanly across three small files: [interactiveHelpers.tsx](../../interactiveHelpers.tsx), [replLauncher.tsx](../../replLauncher.tsx), and [components/App.tsx](../../components/App.tsx).

First, `getRenderContext(exitOnCtrlC)` in [interactiveHelpers.tsx](../../interactiveHelpers.tsx):299-365 wires Ink's `onFrame` hook to three observers before `createRoot()` runs: `FpsTracker`, a process-wide `StatsStore`, an optional JSONL frame-timing benchmark sink gated by `CLAUDE_CODE_FRAME_TIMING_LOG`, and a flicker telemetry detector that skips DEC 2026 synchronized-output terminals (`isSynchronizedOutputSupported()`) and only logs `tengu_flicker` when two non-resize flickers land within 1,000 ms.

Second, `showSetupScreens()` ([interactiveHelpers.tsx](../../interactiveHelpers.tsx):104-298) drives every pre-REPL modal sequentially over that *same* Ink `Root` via `showDialog()` and `showSetupDialog()`:

```ts
// interactiveHelpers.tsx:39-44, 86-92
export function showDialog<T = void>(
  root: Root,
  renderer: (done: (result: T) => void) => React.ReactNode,
): Promise<T> {
  return new Promise<T>(resolve => {
    const done = (result: T): void => void resolve(result)
    root.render(renderer(done))
  })
}

export function showSetupDialog<T = void>(
  root: Root,
  renderer: (done: (result: T) => void) => React.ReactNode,
  options?: { onChangeAppState?: typeof onChangeAppState },
): Promise<T> {
  return showDialog<T>(root, done => (
    <AppStateProvider onChangeAppState={options?.onChangeAppState}>
      <KeybindingSetup>{renderer(done)}</KeybindingSetup>
    </AppStateProvider>
  ))
}
```

Wrapping each dialog in a temporary `<AppStateProvider>` + `<KeybindingSetup>` means confirmation keys (`Enter`, `Esc`, `Up`/`Down`) work identically before `<App>` exists. For fatal exits after `createRoot()`, `exitWithError()` / `exitWithMessage()` ([interactiveHelpers.tsx](../../interactiveHelpers.tsx):52-80) dynamically import `<Text>`, render the final line through Ink, call `root.unmount()`, await optional cleanup, and then `process.exit(exitCode)`.

Only after `showSetupScreens()` resolves does `main.tsx` call `launchRepl()` in [replLauncher.tsx](../../replLauncher.tsx):12-22:

```ts
// replLauncher.tsx:12-22
export async function launchRepl(
  root: Root,
  appProps: AppWrapperProps,
  replProps: REPLProps,
  renderAndRun: (root: Root, element: React.ReactNode) => Promise<void>,
): Promise<void> {
  const { App } = await import('./components/App.js')
  const { REPL } = await import('./screens/REPL.js')
  await renderAndRun(
    root,
    <App {...appProps}>
      <REPL {...replProps} />
    </App>,
  )
}
```

`<App>` ([components/App.tsx](../../components/App.tsx):19-55) is a thin three-provider shell: `FpsMetricsProvider` → `StatsProvider` → `AppStateProvider` (wired to `onChangeAppState`). `renderAndRun()` ([interactiveHelpers.tsx](../../interactiveHelpers.tsx):98-103) calls `root.render(element)`, triggers `startDeferredPrefetches()` in `main.tsx`, awaits `root.waitUntilExit()`, and runs `gracefulShutdown(0)`.

Inside `screens/REPL.tsx:811-835`, live capability merging uses two specialized hooks:

- **Commands** ([hooks/useMergedCommands.ts](../../hooks/useMergedCommands.ts):5-15): `REPL.tsx` chains `useMergedCommands` twice—first merging `localCommands` + `plugins.commands`, then merging `mcp.commands` on top with `uniqBy([...initialCommands, ...mcpCommands], 'name')`, short-circuiting to the original array reference when the dynamic list is empty.
- **Tools** ([hooks/useMergedTools.ts](../../hooks/useMergedTools.ts):20-44 + [utils/toolPool.ts](../../utils/toolPool.ts):55-79): `useMergedTools` runs inside `useMemo`, delegating to `assembleToolPool(toolPermissionContext, mcpTools)` and then `mergeAndFilterTools(initialTools, assembled, toolPermissionContext.mode)`. `mergeAndFilterTools()` deduplicates by `name`, **partitions MCP tools from built-in tools**, sorts each partition alphabetically (`[...builtIn.sort(byName), ...mcp.sort(byName)]`) so built-ins remain a stable contiguous prompt-cache prefix, and—when `feature('COORDINATOR_MODE')` is enabled and coordinator mode is active—filters the pool through `applyCoordinatorToolFilter()`. Finally, `REPL.tsx:814-829` applies `resolveAgentTools()` if `--agent` (`mainThreadAgentDefinition`) is set.

### Hidden Invariants & Failure Modes

- **Trust boundary ordering in `showSetupScreens()`** ([interactiveHelpers.tsx](../../interactiveHelpers.tsx):131-190): Workspace trust is enforced *even in `bypassPermissions` mode* (skipped only under `process.env.CLAUBBIT`). Once `TrustDialog` resolves (or fast-paths via `checkHasTrustDialogAccepted()`), the runner executes a strict sequence: `setSessionTrustAccepted(true)` → `resetGrowthBook()` + `initializeGrowthBook()` (so GrowthBook picks up authenticated headers after trust/login) → `getSystemContext()` prefetch → `handleMcpjsonServerApprovals()` → `ClaudeMdExternalIncludesDialog` → `updateGithubRepoPathMapping()` (post-trust so untrusted repos cannot poison teleport mappings) → `applyConfigEnvironmentVariables()` (applies untrusted repo env vars only after consent) → `setImmediate(() => initializeTelemetryAfterTrust())`. Deferring OTel to `setImmediate` keeps its dynamic import out of the pre-render microtask queue.
- **Feature-gated setup screens:** `AutoModeOptInDialog` is gated behind `feature('TRANSCRIPT_CLASSIFIER')` and only runs when `permissionMode === 'auto'` actually resolved ([interactiveHelpers.tsx](../../interactiveHelpers.tsx):224-235). `DevChannelsDialog` is gated behind `feature('KAIROS') || feature('KAIROS_CHANNELS')` and awaits `checkGate_CACHED_OR_BLOCKING('tengu_harbor')` first so a cold disk cache does not silently drop channel notifications ([interactiveHelpers.tsx](../../interactiveHelpers.tsx):241-288).
- **Turn-1 MCP race avoidance** ([screens/REPL.tsx](../../screens/REPL.tsx):2746-2755): Even though `useMergedTools` keeps React state fresh, `onQueryImpl` intentionally extracts `freshTools` and `freshMcpClients` from `getToolUseContext(...)` (which reads `store.getState()` directly) rather than trusting the closure-captured `tools` prop—ensuring MCP connections that flushed between render and `onQuery` appear on turn 1.

---

## 2. Bridging `query()` Into React: `QueryGuard`, Stream Dispatch, Queued Prompts, and Modal Arbitration

### The Problem

A single interactive turn spans at least four asynchronous stages: (1) `processUserInput()` expanding slash commands, shell `!` commands, images, and attachments; (2) `onBeforeQuery` hooks and system-prompt construction; (3) `for await (const event of query(...))` streaming hundreds of SSE chunks and executing tools; and (4) `finally` cleanup + queue draining.

Originally, `REPL.tsx` tracked "is a turn running?" with two values: a React `isLoading` state (asynchronously batched) and an `isQueryRunning` ref (synchronous). Those two regularly drifted apart, opening four severe failure modes:

1. A second submission arriving during `processUserInput()`'s `await` started a concurrent turn instead of queueing.
2. Pressing `Esc` (`onCancel`) and immediately submitting a new prompt let the cancelled turn's microtask `finally` block clear the *new* turn's loading state.
3. A spinner rendered in the gap between reserving a turn and resetting `loadingStartTimeRef` computed `Date.now() - 0 ≈ 56 years` (**INC-4549**).
4. Nineteen competing overlays (permission prompts, sandbox network approvals, MCP elicitations, rewind selector, cost warnings, onboarding callouts) could fight over focus and steal keystrokes while the user was mid-sentence.

### The Real Implementation

#### 1. `QueryGuard`: Synchronous Generation-Numbered Turn Ownership

[utils/QueryGuard.ts](../../utils/QueryGuard.ts) replaces the dual-state pattern with a 3-state machine (`idle` → `dispatching` → `running` → `idle`) subscribed to by React via `useSyncExternalStore`:

```ts
// utils/QueryGuard.ts:29-93 (abridged)
export class QueryGuard {
  private _status: 'idle' | 'dispatching' | 'running' = 'idle'
  private _generation = 0
  private _changed = createSignal()

  reserve(): boolean {
    if (this._status !== 'idle') return false
    this._status = 'dispatching'
    this._notify()
    return true
  }

  tryStart(): number | null {
    if (this._status === 'running') return null
    this._status = 'running'
    ++this._generation
    this._notify()
    return this._generation
  }

  end(generation: number): boolean {
    if (this._generation !== generation) return false
    if (this._status !== 'running') return false
    this._status = 'idle'
    this._notify()
    return true
  }

  forceEnd(): void {
    if (this._status === 'idle') return
    this._status = 'idle'
    ++this._generation
    this._notify()
  }
}
```

In [screens/REPL.tsx](../../screens/REPL.tsx):900-916, `REPL` allocates one `queryGuard` ref and derives read-only `isLoading = isQueryActive || isExternalLoading` (where `isExternalLoading` covers remote CCR sessions and foregrounded background tasks that bypass `onQuery`).

#### 2. Submission, Priority Queueing, and Idle Auto-Drain

Every prompt submission flows through `onSubmit` ([screens/REPL.tsx](../../screens/REPL.tsx):3170-3545) into `handlePromptSubmit()` ([utils/handlePromptSubmit.ts](../../utils/handlePromptSubmit.ts):120-387):

1. **Immediate `local-jsx` escape hatch** ([screens/REPL.tsx](../../screens/REPL.tsx):3184-3281, [utils/handlePromptSubmit.ts](../../utils/handlePromptSubmit.ts):229-311): Slash commands marked `immediate: true` (e.g., `/config`, `/model`, `/btw`) or invoked via a keybinding (`fromKeybinding`) execute *while `queryGuard.isActive` is true*, mounting their UI via `setToolJSX({ isLocalJSXCommand: true, isImmediate: true })` without queueing or clobbering the user's draft text.
2. **Mid-turn queueing vs. interruptible tools** ([utils/handlePromptSubmit.ts](../../utils/handlePromptSubmit.ts):313-351): If `queryGuard.isActive || isExternalLoading`, `handlePromptSubmit` filters orphaned image entries, expands pasted text refs early (`expandPastedTextRefs`), and pushes a `QueuedCommand` onto the module-level priority queue in [utils/messageQueueManager.ts](../../utils/messageQueueManager.ts):53-193 (`PRIORITY_ORDER`: `'now' (0) > 'next' (1, user input) > 'later' (2, task notifications)`). If every currently running tool declares `interruptBehavior: 'cancel'` (such as `SleepTool`), `handlePromptSubmit` also calls `abortController.abort('interrupt')` so the queued prompt preempts the sleep immediately.
3. **Reservation & `AsyncLocalStorage` workload scoping** ([utils/handlePromptSubmit.ts](../../utils/handlePromptSubmit.ts):396-610): When idle, `executeUserInput()` calls `queryGuard.reserve()` *synchronously before the first `await`*, wraps the turn in `runWithWorkload(turnWorkload, ...)` so detached subagents inherit the turn's workload tag via `AsyncLocalStorage`, iterates `commands` through `processUserInput()` (only command `0` attaches IDE selection, attachments, and `pastedContents`), snapshots `fileHistory`, and calls `onQuery()`. Its `finally` block calls `queryGuard.cancelReservation()`, which is a no-op if `onQuery` already promoted `dispatching → running` and later ran `end()`.
4. **Reactive queue drain** ([hooks/useCommandQueue.ts](../../hooks/useCommandQueue.ts) + [hooks/useQueueProcessor.ts](../../hooks/useQueueProcessor.ts)): Both `useCommandQueue` and `useQueueProcessor` subscribe to the module-level queue via `useSyncExternalStore` (avoiding React context lag in Ink). Whenever `!isQueryActive && !hasActiveLocalJsxUI && queueSnapshot.length > 0`, `useQueueProcessor` calls `processQueueIfReady({ executeInput: executeQueuedInput })`, whose synchronous chain immediately calls `queryGuard.reserve()` before React re-runs the effect on the dequeue snapshot update.

#### 3. Pumping `query()` Events Into React State

Inside `onQuery` ([screens/REPL.tsx](../../screens/REPL.tsx):2855-2960), `queryGuard.tryStart()` atomically claims the next `thisGeneration` (if a race still occurs and returns `null`, non-meta user messages are salvaged by re-enqueueing them onto the command queue instead of dropping them). It appends `newMessages`, reads `messagesRef.current` synchronously, and calls `onQueryImpl()` ([screens/REPL.tsx](../../screens/REPL.tsx):2661-2854), which builds `systemPrompt`/`userContext`/`systemContext` in parallel and drives the generator:

```ts
// screens/REPL.tsx:2793-2803
for await (const event of query({
  messages: messagesIncludingNewMessages,
  systemPrompt,
  userContext,
  systemContext,
  canUseTool,
  toolUseContext,
  querySource: getQuerySourceForREPL(),
})) {
  onQueryEvent(event)
}
```

Each yielded item goes to `onQueryEvent` → `handleMessageFromStream()` ([utils/messages.ts](../../utils/messages.ts):2930-3090), which fans out five distinct streams:

| Generator Event | Target State / Callback | Purpose |
| :--- | :--- | :--- |
| `stream_request_start` | `setStreamMode('requesting')` | Spinner transitions to waiting-for-TTFT state |
| `message_start` | `apiMetricsRef.current.push(...)` | Captures `ttftMs` and response-length baseline |
| `content_block_start` (`thinking`/`text`/`tool_use`) | `setStreamMode(...)`, `setStreamingToolUses(...)` | Updates spinner verb; registers live tool stub before full JSON arrives |
| `content_block_delta` (`text_delta`/`input_json_delta`/`thinking_delta`) | `setResponseLength`, `onStreamingText`, `setStreamingToolUses` | Feeds live token counter, streaming markdown preview, and partial tool args (`signature_delta` explicitly excluded from length/OTPS!) |
| `message_stop` | `setStreamMode('tool-use')`, `setStreamingToolUses([])` | Clears transient tool stubs as execution begins |
| `tombstone` | `setMessages(filter)`, `removeTranscriptMessage(uuid)` | Deletes rolled-back/superseded messages from UI and JSONL |
| Completed `Message` (`assistant`, `user`, `progress`, `system`, `attachment`) | `onStreamingText(() => null)`, `setMessages(...)` | Atomically swaps streaming preview for final message |

Notice the streaming-text polish at [screens/REPL.tsx](../../screens/REPL.tsx):1461-1473: `streamingText` updates on every `text_delta` (coalesced by Ink's 16 ms render throttle), but `visibleStreamingText` slices to `streamingText.lastIndexOf('\n') + 1` so Markdown streams **line-by-line** instead of jittering character-by-character, and disables itself entirely when `prefersReducedMotion` or `hasCursorUpViewportYankBug()` is true.

#### 4. Permission Prompts and `getFocusedInputDialog()` Arbitration

Tool permissions ([Chapter 11](11-the-permission-engine.md)) enter `REPL` through `useCanUseTool(setToolUseConfirmQueue, setToolPermissionContext)` ([screens/REPL.tsx](../../screens/REPL.tsx):2382), which pushes a `ToolUseConfirm` onto `toolUseConfirmQueue` and returns a `Promise` that blocks `runToolUse()` until `<PermissionRequest>` calls `onDone`.

Because nineteen different interactive overlays can become ready at the same moment, `getFocusedInputDialog()` ([screens/REPL.tsx](../../screens/REPL.tsx):2017-2065) resolves focus with a single deterministic priority ladder:

1. **Exit flow** (`isExiting || exitFlow`) → returns `undefined` (nothing steals exit).
2. **High-priority explicit overlay:** `isMessageSelectorVisible` → `'message-selector'` (always wins).
3. **Typing guard:** `if (isPromptInputActive) return undefined` — if the user is mid-keystroke in `PromptInput`, incoming permission modals are **suppressed** rather than eating the user's next `y` or `Enter`! `hasSuppressedDialogs` ([screens/REPL.tsx](../../screens/REPL.tsx):2068) flags `PromptInput` to show a dim `"Waiting for permission…"` banner until the prompt clears.
4. **Blocking security & tool queues:** `sandbox-permission` → (gated by `allowDialogsWithAnimation = !toolJSX || toolJSX.shouldContinueAnimation` so background tool hints never deadlock a permission prompt) → `tool-permission` → `prompt` → `worker-sandbox-permission` → `elicitation`.
5. **Turn-end & advisory dialogs:** `cost` → `idle-return` → `ultraplan-choice`/`ultraplan-launch` (`feature('ULTRAPLAN')`) → `ide-onboarding` → ant-only callouts (`model-switch`, `undercover-callout`, dead-code-eliminated in external builds via `"external" === 'ant'`) → `effort-callout` → `remote-callout` → `lsp-recommendation` → `plugin-hint` → `desktop-upsell`.

### Hidden Invariants & Failure Modes

> [!WARNING]
> **INC-4549 (The 56-Year Elapsed Timer):** `queryGuard.reserve()` flips `isQueryActive` to `true` *before* `processUserInput()` awaits, whereas `onQuery()` resets `loadingStartTimeRef` *after* `processUserInput()` finishes. During that window, the spinner read `loadingStartTimeRef.current === 0` and displayed `Date.now() - 0 ≈ 56 years`. [screens/REPL.tsx](../../screens/REPL.tsx):949-953 fixes this with an inline render-phase edge check (`if (isQueryActive && !wasQueryActiveRef.current) resetTimingRefs()`), and `setIsExternalLoading` performs the same reset for remote sessions.

- **Ephemeral progress coalescing prevents 120 MB transcripts** ([screens/REPL.tsx](../../screens/REPL.tsx):2608-2627): `SleepTool` and `BashTool` emit a progress tick every second. When `isEphemeralToolProgress(newMessage.data.type)` is true and the last message shares the same `parentToolUseID` and progress type, `onQueryEvent` **replaces the last array element in place** instead of appending. Appending previously grew `messages` past 13,000 entries and bloated JSONL logs to 120 MB; same-length replacement also keeps `useLogMessages` from writing redundant lines to disk. Conversely, `agent_progress`, `hook_progress`, and `skill_progress` are *not* ephemeral because the UI renders their full subagent/hook trail.
- **Cancel preserves partial text and bumps generation** ([screens/REPL.tsx](../../screens/REPL.tsx):2106-2163): `onCancel()` calls `queryGuard.forceEnd()` (invalidating any pending `finally` via `++_generation`), commits any non-empty `streamingText` into `messages` *before* `resetLoadingState()` clears it (ensuring transcript order `[user, partial-assistant, [Request interrupted by user]]`), aborts the active controller or permission queue, and clears `abortController` to `null` so subsequent `Esc` presses don't see a stale aborted signal.
- **Synchronous `messagesRef` & `streamModeRef` prevent latency spikes and heap leaks** ([screens/REPL.tsx](../../screens/REPL.tsx):838-848, 2901-2906, 3538-3545): Updating `messagesRef.current` synchronously inside the `setMessages` wrapper lets `onQuery` pass `latestMessages` immediately without awaiting React's scheduler (eliminating a 20–56 ms per-prompt stall). Reading `messagesRef.current` and `streamModeRef.current` inside `onSubmit` keeps `onSubmit` referentially stable across ~30 `setMessages` and ~10 `streamMode` flips per turn—preventing downstream closures from pinning ~9–15 historical 1,776-byte REPL scopes and message arrays on the heap.
- **Config lock-storm guard (GH #3117)** ([screens/REPL.tsx](../../screens/REPL.tsx):3840-3857): Counting prompt-queue usage via `saveGlobalConfig` uses an edge-triggered `hasCountedQueueUseRef` (firing only on `0 → ≥1`), because writing on every queue length mutation caused `ELOCKED` write storms and `~/.claude.json` corruption across concurrent sessions.

---

## 3. Rendering Thousands of Messages Without a GC Death Spiral: `Messages.tsx`, `VirtualMessageList`, and `PromptInput`

### The Problem

Once `messages` is in React state, rendering it at 60 FPS inside a terminal hits two scaling walls:

1. **Memory & O(n) scroll stalls:** Every mounted `MessageRow` allocates React fibers, memo caches, and Yoga nodes (~250 KB RSS per message). At ~2,000 messages, main-screen Ink held ~500 MB of fibers and 3,000-line screen buffers—triggering observed 59 GB RSS / 14k `mmap`/`munmap`/sec GC death spirals. Even in fullscreen virtual scroll, rebuilding grouping/collapse Maps on every scroll range change burned ~50 ms of allocations per scroll over 27k messages, causing 100–173 ms stop-the-world GC pauses.
2. **Rich terminal editing in a single box:** `PromptInput` has to handle multi-line text, `!` bash mode, 50 KB pastes, clipboard images, inline `[Image #N]` pills, undo history, prompt stashing, external `$EDITOR`, queued-command recall, and floating notifications—without causing Ink to repaint the whole terminal or unmounting stateful background hooks.

### The Real Implementation

#### 1. The Split Memo Pipeline in `Messages.tsx`

[components/Messages.tsx](../../components/Messages.tsx):379-543 splits transcript preparation into two strictly separated `useMemo` stages so scrolling never recomputes O(n) message transforms:

1. **Transform stage** (`collapsed_0`, `lookups_0`):
   - `normalizeMessages(messages).filter(isNotEmptyMessage)` splits multi-block API messages into one renderable row per block with deterministic derived UUIDs.
   - `syntheticStreamingToolUseMessages` converts in-flight `streamingToolUses` into synthetic rows whose UUID is `deriveUUID(streamingToolUse.contentBlock.id, 0)`—never `randomUUID()`, which would remount rows on every `input_json_delta` chunk and corrupt Ink's DOM ([components/Messages.tsx](../../components/Messages.tsx):447-458).
   - Main-screen mode slices at the latest compact boundary (`getMessagesAfterCompactBoundary(..., { includeSnipped: true })`); fullscreen keeps pre-compact scrollback (capped to one compact interval in `onQueryEvent` at [screens/REPL.tsx](../../screens/REPL.tsx):2594-2600).
   - Drops `progress` rows and `isNullRenderingAttachment(msg)` rows (`hook_success`, etc.) *before* counting or slicing (CC-724), reorders tool results next to their tool calls (`reorderMessagesInUI`), applies optional `BRIEF` filtering (`feature('KAIROS') || feature('KAIROS_BRIEF')`), and runs the grouping/collapsing chain: `applyGrouping` → `collapseReadSearchGroups` → `collapseTeammateShutdowns` → `collapseHookSummaries` → `collapseBackgroundBashNotifications` → `buildMessageLookups`.
2. **Cheap slice stage** (`renderableMessages`):
   - In **fullscreen mode** (`virtualScrollRuntimeGate = scrollRef != null && !CLAUDE_CODE_DISABLE_VIRTUAL_SCROLL`), `Messages` mounts `<VirtualMessageList>` ([components/VirtualMessageList.tsx](../../components/VirtualMessageList.tsx)), powered by `useVirtualScroll()` ([hooks/useVirtualScroll.ts](../../hooks/useVirtualScroll.ts):19-130). Instead of mounting all items, `useVirtualScroll` mounts only viewport + `OVERSCAN_ROWS = 80` rows flanked by top/bottom Yoga spacer `<Box>` nodes. It caches measured Yoga heights per item key (invalidated whenever `columns` changes), quantizes `scrollTop` to `SCROLL_QUANTUM = 40` rows for `useSyncExternalStore` so wheel ticks bypass React completely via Ink's `ScrollBox.forceRender`, caps newly mounted rows at `SLIDE_STEP = 25` per commit (preventing 290 ms synchronous Markdown-lexing stalls), and enforces a hard ceiling of `MAX_MOUNTED_ITEMS = 300`.
   - In **main-screen mode** (no fullscreen `scrollRef`), `Messages` caps mounted rows via `computeSliceStart()` ([components/Messages.tsx](../../components/Messages.tsx):307-340):

```ts
// components/Messages.tsx:307-340
const MAX_MESSAGES_WITHOUT_VIRTUALIZATION = 200
const MESSAGE_CAP_STEP = 50

export function computeSliceStart(
  collapsed: ReadonlyArray<{ uuid: string }>,
  anchorRef: { current: SliceAnchor },
  cap = MAX_MESSAGES_WITHOUT_VIRTUALIZATION,
  step = MESSAGE_CAP_STEP,
): number {
  const anchor = anchorRef.current
  const anchorIdx = anchor
    ? collapsed.findIndex(m => m.uuid === anchor.uuid)
    : -1
  let start =
    anchorIdx >= 0
      ? anchorIdx
      : anchor
        ? Math.min(anchor.idx, Math.max(0, collapsed.length - cap))
        : 0
  if (collapsed.length - start > cap + step) {
    start = collapsed.length - cap
  }
  const msgAtStart = collapsed[start]
  if (msgAtStart && (anchor?.uuid !== msgAtStart.uuid || anchor.idx !== start)) {
    anchorRef.current = { uuid: msgAtStart.uuid, idx: start }
  } else if (!msgAtStart && anchor) {
    anchorRef.current = null
  }
  return start
}
```

Why a `{ uuid, idx }` anchor instead of `collapsed.slice(-200)`? Naive `slice(-200)` drops one row on every append, shifting scrollback and triggering a full terminal reset every turn (CC-941). Quantizing to 50-row steps (CC-1154) still jittered whenever compaction or regrouping changed `collapsed.length`. The UUID anchor advances *only* when rendered count exceeds `cap + step` (CC-1174), and the fallback `idx` heals cases where `collapseHookSummaries` + `reorderMessagesInUI` changes the first UUID in a merged group.

Each visible row renders through `<MessageRow>` ([components/MessageRow.tsx](../../components/MessageRow.tsx)) → `<Message>` ([components/Message.tsx](../../components/Message.tsx):58-180), which dispatches across ~30 specialized renderers in `components/messages/` (`AssistantTextMessage`, `AssistantToolUseMessage`, `AssistantThinkingMessage`, `UserTextMessage`, `UserToolResultMessage`, `CollapsedReadSearchContent`, `GroupedToolUseContent`, `AttachmentMessage`, `SystemTextMessage`, `CompactBoundaryMessage`, etc.). Live streaming text renders as a sibling `<StreamingMarkdown>` directly below the list ([components/Messages.tsx](../../components/Messages.tsx):703-712), so when the final assistant message arrives and `streamingText` clears in the same React batch, the transition is positionally seamless.

#### 2. `PromptInput`: Pills, Pastes, Stash, and Queue Editing

[components/PromptInput/PromptInput.tsx](../../components/PromptInput/PromptInput.tsx) coordinates every input concern around a single inner editor (`<VimTextInput>` when `isVimModeEnabled()`, otherwise `<TextInput>`, at line 2243):

- **Mode prefixing** ([components/PromptInput/inputModes.ts](../../components/PromptInput/inputModes.ts):4-33): Typing or pasting a leading `!` into an empty prompt flips `mode` to `'bash'`, strips `!` from the displayed value, and swaps the border to `bashBorder`; history serialization prepends `!` back via `prependModeCharacterToInput()`.
- **Paste & image pill lifecycle** ([components/PromptInput/PromptInput.tsx](../../components/PromptInput/PromptInput.tsx):1151-1246, [inputPaste.ts](../../components/PromptInput/inputPaste.ts):4-90):
  - `onTextPaste()` strips ANSI codes, normalizes `\r` and tabs, and collapses any paste longer than `PASTE_THRESHOLD` (`800` chars in `utils/imagePaste.ts:30`) or taller than `Math.min(rows - 10, 2)` lines into a compact `[Pasted text #N]` ref backed by `pastedContents[pasteId]`—keeping Ink's input box from growing tall enough to force a full terminal repaint. Separately, `maybeTruncateInput()` in `inputPaste.ts` truncates huge programmatic inputs over `10,000` chars into `[...Truncated text #N +M lines...]`.
  - `onImagePaste()` caches the image path synchronously, persists the base64 payload to disk asynchronously, inserts `[Image #N]`, and arms `pendingSpaceAfterPillRef.current = true` so `lazySpaceInputFilter` auto-inserts a single space before the next printable character. A companion `useEffect` ([PromptInput.tsx](../../components/PromptInput/PromptInput.tsx):1189-1200) prunes any `pastedContents` image whose `[Image #N]` token was deleted from the text.
- **Stash, external editor, undo, and queue recall** ([PromptInput.tsx](../../components/PromptInput/PromptInput.tsx):1257-1383):
  - `ctrl+s` (`handleStash`) snapshots `{ text, cursorOffset, pastedContents }` into `stashedPrompt` (and pops it back on empty input, or automatically after a submitted prompt/slash command completes—deferred past `handlePromptSubmit` when submitting a slash command or queueing mid-turn so the restored draft isn't clobbered, [screens/REPL.tsx](../../screens/REPL.tsx):3328-3357, 3521-3532).
  - `ctrl+g` / `ctrl+x ctrl+e` (`handleExternalEditor`) expands collapsed paste refs, opens `$EDITOR`, and pushes the previous state onto the undo buffer (`ctrl+_` / `ctrl+shift+-`) before writing edits back.
  - Pressing Up when editable commands are waiting in the queue calls `popAllCommandsFromQueue()`, restoring both queued prompt text and any attached images back into the active input box.

### Hidden Invariants & Failure Modes

- **React Compiler `memoCache` pinning trap** ([components/Messages.tsx](../../components/Messages.tsx):695-698, [components/MessageRow.tsx](../../components/MessageRow.tsx):45-48): `Messages` intentionally precomputes `isUserContinuation` and `hasContentAfter` as booleans instead of passing `renderableMessages` to each `MessageRow`. Because the React Compiler caches previous prop values inside each fiber's `memoCache`, passing the array prop pinned every historical version of `renderableMessages` (~1–2 MB leaked over just 7 turns).
- **`LogoHeader` blit-cache protection** ([components/Messages.tsx](../../components/Messages.tsx):55, and source comment): Because `LogoHeader` is the *first* sibling before all `MessageRow`s in main-screen mode, letting it become dirty on every message append tripped Ink's `seenDirtyChild` cascade ([Chapter 20](20-inside-ink-terminal-react-renderer.md)), disabling prev-screen blitting for all 2,800 subsequent rows and pegging CPU at 100%. Wrapping it in `React.memo` + `<OffscreenFreeze>` keeps it permanently clean.
- **Custom `Messages` `React.memo` comparator** ([components/Messages.tsx](../../components/Messages.tsx):741-778): Ignores stable refs/callbacks, compares `streamingToolUses` by `contentBlock` object identity (so `input_json_delta` chunks don't re-render the whole transcript), compares `inProgressToolUseIDs` by set equality, and compares `tools` by tool names.
- **`Notifications` uses `height={0}`, never unmount** ([components/PromptInput/PromptInput.tsx](../../components/PromptInput/PromptInput.tsx):2276-2295): In fullscreen mode, floating notifications sit in an `absolute` zero-layout-height box above the prompt border. When slash autocomplete opens, the box collapses via `height={0}` instead of unmounting—because unmounting `<Notifications>` re-fired `AutoUpdater`'s initial check effect on every slash-completion toggle (PR #22413).
- **Multiline arrow-key ownership** ([components/PromptInput/PromptInput.tsx](../../components/PromptInput/PromptInput.tsx):1656-1659, 2177-2182): `history:previous` and `history:next` are intentionally *not* bound via `useKeybindings` in `PromptInput`; they are passed as `onHistoryUp`/`onHistoryDown` props to `TextInput`/`VimTextInput` so `useTextInput` attempts intra-prompt cursor movement first and falls through to history only at the top/bottom boundary.

---

## 4. The Keybindings Subsystem: Stacked Contexts, Chords, and Terminal Quirks

### The Problem

An interactive coding terminal layers up to 18 UI contexts ([keybindings/schema.ts](../../keybindings/schema.ts):12-32): `Global`, `Chat`, `Autocomplete`, `Confirmation`, `Help`, `Transcript`, `HistorySearch`, `Task`, `ThemePicker`, `Settings`, `Tabs`, `Attachments`, `Footer`, `MessageSelector`, `DiffDialog`, `ModelPicker`, `Select`, and `Plugin` (plus `Scroll` and feature-gated `MessageActions` in `defaultBindings.ts`).

The same physical key means completely different things depending on what is open:
- `Ctrl+T` toggles todos in `Global`, but toggles syntax highlighting inside `ThemePicker`.
- `Escape` cancels a running query in `Chat`, dismisses autocomplete in `Autocomplete`, rejects a permission prompt in `Confirmation`, closes `/help` in `Help`, and exits `Transcript`.
- Multi-keystroke chords like `ctrl+x ctrl+k` (kill background agents) or `ctrl+x ctrl+e` (open `$EDITOR`) must swallow the first key (`ctrl+x`), wait up to 1 second, and intercept the second key (`k` or `e`) *before* `PromptInput` inserts a literal `'k'` into the prompt—and if the user aborts mid-chord with `ctrl+x ctrl+c`, that second key must cancel the chord without triggering `app:interrupt`.

### The Real Implementation

#### 1. Declarative Bindings, Platform Defaults, and Pure Chord Resolution

[keybindings/defaultBindings.ts](../../keybindings/defaultBindings.ts) defines `DEFAULT_BINDINGS` as an ordered array of `{ context, bindings }` blocks. Platform quirks are resolved at module load:
- `IMAGE_PASTE_KEY`: `'alt+v'` on Windows (`ctrl+v` is system paste), `'ctrl+v'` elsewhere.
- `MODE_CYCLE_KEY`: `'shift+tab'` when the terminal supports VT mode (`getPlatform() !== 'windows'`, or Bun `>=1.2.23` / Node `>=22.17.0 <23 || >=24.2.0`), otherwise `'meta+m'`.
- `chat:undo` binds *both* `'ctrl+_'` (legacy terminals sending `0x1f`) and `'ctrl+shift+-'` (Kitty protocol sending physical key + modifiers).
- Feature-gated defaults (`feature('QUICK_SEARCH')`, `feature('TERMINAL_PANEL')`, `feature('MESSAGE_ACTIONS')`, `feature('VOICE_MODE')`, `feature('KAIROS')`) spread conditionally into `DEFAULT_BINDINGS` so dead code elimination strips them cleanly.

[keybindings/parser.ts](../../keybindings/parser.ts) normalizes modifier aliases (`opt`/`option` → `alt`, `cmd`/`command`/`win` → `super`) and splits space-separated chords (preserving a lone `' '` as the `Space` key!). [keybindings/match.ts](../../keybindings/match.ts) maps Ink's `Key` flags to canonical names and collapses `alt` and `meta` into one logical modifier (because legacy terminals cannot distinguish them) while keeping `super` (`cmd`/`win`) distinct for Kitty-protocol terminals.

The heart of the resolver is the pure function `resolveKeyWithChordState()` in [keybindings/resolver.ts](../../keybindings/resolver.ts):166-244:

```ts
// keybindings/resolver.ts:192-236
const ctxSet = new Set(activeContexts)
const contextBindings = bindings.filter(b => ctxSet.has(b.context))

// Check if this could be a prefix for longer chords. Group by chord
// string so a later null-override shadows the default it unbinds —
// otherwise null-unbinding `ctrl+x ctrl+k` still makes `ctrl+x` enter
// chord-wait and the single-key binding on the prefix never fires.
const chordWinners = new Map<string, string | null>()
for (const binding of contextBindings) {
  if (
    binding.chord.length > testChord.length &&
    chordPrefixMatches(testChord, binding)
  ) {
    chordWinners.set(chordToString(binding.chord), binding.action)
  }
}
let hasLongerChords = false
for (const action of chordWinners.values()) {
  if (action !== null) {
    hasLongerChords = true
    break
  }
}
if (hasLongerChords) {
  return { type: 'chord_started', pending: testChord }
}

let exactMatch: ParsedBinding | undefined
for (const binding of contextBindings) {
  if (chordExactlyMatches(testChord, binding)) {
    exactMatch = binding
  }
}
if (exactMatch) {
  return exactMatch.action === null
    ? { type: 'unbound' }
    : { type: 'match', action: exactMatch.action }
}
```

#### 2. Two-Phase Dispatch: `ChordInterceptor` + `useKeybinding` / `useKeybindings`

[keybindings/KeybindingProviderSetup.tsx](../../keybindings/KeybindingProviderSetup.tsx):119-307 mounts `<KeybindingProvider>` and immediately renders `<ChordInterceptor>` as its **first child** before `{children}`:

```tsx
// keybindings/KeybindingProviderSetup.tsx:205-208 (logical structure)
<KeybindingProvider bindings={bindings} pendingChordRef={pendingChordRef} ...>
  <ChordInterceptor ... />
  {children}
</KeybindingProvider>
```

Because Ink dispatches `useInput` listeners in mount order, `ChordInterceptor` sees every keystroke first:

- **Synchronous ref + React state duality:** `pendingChordRef` and `activeContextsRef` (a `Set` mutated synchronously in `useLayoutEffect` by `useRegisterKeybindingContext()`, [KeybindingContext.tsx](../../keybindings/KeybindingContext.tsx):215-242) let `resolve()` observe rapid consecutive chord keystrokes and newly mounted modals without waiting for a React render flush. `setPendingChord()` updates both the ref and React state and resets a `CHORD_TIMEOUT_MS = 1000` cancellation timer.
- **Fast wheel skip:** `if ((key.wheelUp || key.wheelDown) && pendingChordRef.current === null) return` avoids scanning `handlerRegistryRef` on every mouse-wheel event, while still letting a wheel tick mid-chord cancel the pending chord.
- **Why `ChordInterceptor` only invokes handlers on chord completion (`wasInChord === true`):** On `chord_started`, `chord_cancelled`, `unbound`, or a completed multi-key chord (`match` with `wasInChord === true`), `ChordInterceptor` calls `event.stopImmediatePropagation()` (invoking the matching registered handler from `handlerRegistryRef` on chord completion). On a **single-keystroke** `match`, it intentionally *does not* invoke handlers or stop propagation—it clears `pendingChord` and lets the event flow down to per-component `useKeybinding()` / `useKeybindings()` hooks ([keybindings/useKeybinding.ts](../../keybindings/useKeybinding.ts):33-196) so component mount order and ordering-sensitive handlers like `useTypeahead` (Enter accepting autocomplete before submit) remain intact.
- **Fall-through convention:** In `useKeybinding` / `useKeybindings`, if a handler returns literal `false`, `event.stopImmediatePropagation()` is *not* called—allowing fall-through (for instance, `ScrollKeybindingHandler` returns `false` on `scroll:lineUp`/`lineDown` when the `ScrollBox` content already fits, letting a child list handle the wheel event instead).

#### 3. User Customization, Validation, and Hot-Reload

[keybindings/loadUserBindings.ts](../../keybindings/loadUserBindings.ts) loads `~/.claude/keybindings.json` synchronously on mount (`loadKeybindingsSyncWithWarnings`) and watches it with `chokidar` (`awaitWriteFinish: { stabilityThreshold: 500, pollInterval: 200 }`, `atomic: true`) for live hot-reload. User customization is currently runtime-gated behind GrowthBook `tengu_keybinding_customization_release` (`isKeybindingCustomizationEnabled()` at lines 41-46); external users without that flag get `DEFAULT_BINDINGS` only.

User blocks are appended *after* defaults (`[...defaultBindings, ...userParsed]`) and validated by [keybindings/validate.ts](../../keybindings/validate.ts) and [keybindings/reservedShortcuts.ts](../../keybindings/reservedShortcuts.ts):
- **`checkDuplicateKeysInJson(rawJson)`** scans the raw JSON text with regex *before* relying on `JSON.parse`, because `JSON.parse` silently overwrites earlier duplicate keys inside the same block.
- **Reserved shortcut checks** flag `NON_REBINDABLE` (`ctrl+c`, `ctrl+d`, and `ctrl+m`—which sends identical CR bytes to Enter in terminals), `TERMINAL_RESERVED` (`ctrl+z` SIGTSTP, `ctrl+\` SIGQUIT—explicitly *omitting* `ctrl+s`/`ctrl+q` because `ctrl+s` is prompt stash), and `MACOS_RESERVED` (`cmd+c/v/x/q/w/tab/space`). `normalizeKeyForComparison()` splits chords on whitespace *before* splitting steps on `+` so multi-key chords aren't mangled.
- Validation issues surface via a 60-second notification pointing to `/doctor` ([KeybindingProviderSetup.tsx](../../keybindings/KeybindingProviderSetup.tsx):59-112).

### Hidden Invariants & Failure Modes

> [!IMPORTANT]
> **How context precedence *actually* works:** Although comments in `useKeybinding.ts:59` suggest deduplicated `activeContexts` order determines priority, [keybindings/resolver.ts](../../keybindings/resolver.ts):193-229 converts `activeContexts` into an unordered `Set` (`ctxSet`) and scans `bindings` linearly, keeping the **last** matching entry. Context precedence therefore comes from the array order in `DEFAULT_BINDINGS` (`Global` at index 0, specific overlays like `Confirmation`, `ThemePicker`, and `Help` later) plus user overrides appended at the end.

- **Ink's Escape-sets-Meta quirk** ([keybindings/match.ts](../../keybindings/match.ts):96-102, [resolver.ts](../../keybindings/resolver.ts):86-89): Legacy VT escape parsing causes Ink to set `key.meta = true` whenever bare Escape is pressed. Both `matchesKeystroke` and `buildKeystroke` explicitly force `meta = false` when `key.escape` is true—otherwise `"escape"` bindings and chord cancellations would never match.
- **Direct `chat:submit` registration bypass** ([components/PromptInput/PromptInput.tsx](../../components/PromptInput/PromptInput.tsx):1637-1653): `PromptInput` registers `chat:submit` directly via `keybindingContext.registerHandler(...)` instead of `useKeybindings`. That lets `ChordInterceptor` invoke submit if a user binds a custom chord (e.g., `ctrl+e s`), while preventing `useKeybindings` from calling `stopImmediatePropagation()` on bare `Enter` before `useTypeahead` accepts autocomplete.
- **The `voice:pushToTalk` null-unbind trap** ([keybindings/defaultBindings.ts](../../keybindings/defaultBindings.ts):91-96): Under `feature('VOICE_MODE')`, `space` is registered as `voice:pushToTalk` so help displays can find it. If a user tries to disable it by setting `"space": null` in `keybindings.json`, `resolveKeyWithChordState` returns `{ type: 'unbound' }` and `ChordInterceptor`/`useKeybinding` calls `event.stopImmediatePropagation()`—making the spacebar completely dead for typing!
- **Handler mount-order contract in `REPL.tsx`** ([screens/REPL.tsx](../../screens/REPL.tsx):4550-4563): Inside `<KeybindingSetup>`, `<ScrollKeybindingHandler>` is deliberately mounted *before* `<CancelRequestHandler>` so `Ctrl+C` with an active terminal text selection copies the selection and stops propagation, whereas `Ctrl+C` without a selection falls through to cancel the running query.

---

## 5. Pure-Functional Vim Mode Inside the Prompt Editor

### The Problem

When a user enables Vim mode, `PromptInput` swaps `<TextInput>` for `<VimTextInput>` ([components/PromptInput/PromptInput.tsx](../../components/PromptInput/PromptInput.tsx):2243). Implementing Vim inside a React terminal input is deceptively hard:

1. **Multi-keystroke commands outrun React renders.** Typing `2d3w` or `ci"` delivers 3–4 keypress events faster than React commits state; if intermediate operator/count states lived in `useState`, fast bursts would read stale closures.
2. **Wrapped rows vs. logical lines.** A long prompt wraps across multiple terminal columns. `j`/`k` and `dd` operate on *logical* `\n`-delimited lines, whereas `gj`/`gk` move across *visual* wrapped rows (and per `:help gj`, `dgj` is characterwise exclusive, not linewise!).
3. **Grapheme clusters and inline pills.** Emoji and combining sequences span multiple UTF-16 code units, and `[Image #1]` is an atomic UI pill embedded inside plain text. Naive `offset + 1` splits surrogate pairs, and `dw` landing inside `[Image #1]` would leave broken `[Image` debris.

### The Real Implementation

The Vim engine separates a **pure, React-free TypeScript state machine** under `vim/` from a thin React hook adapter in [hooks/useVimInput.ts](../../hooks/useVimInput.ts).

#### 1. Discriminated State Machine (`vim/types.ts` + `vim/transitions.ts`)

[vim/types.ts](../../vim/types.ts):49-120 encodes every legal mode and partial-command state as discriminated unions:

- `VimState`: either `{ mode: 'INSERT'; insertedText: string }` (accumulating typed text for `.` repeat) or `{ mode: 'NORMAL'; command: CommandState }`.
- `CommandState`: **11 exhaustive variants**—`idle`, `count`, `operator`, `operatorCount`, `operatorFind`, `operatorTextObj`, `find`, `g`, `operatorG`, `replace`, and `indent`.
- `PersistentState`: survives across commands (`lastChange: RecordedChange | null`, `lastFind`, `register`, `registerIsLinewise`).
- `MAX_VIM_COUNT = 10000`: clamps numeric prefixes (`999999999x` cannot hang the event loop).

[vim/transitions.ts](../../vim/transitions.ts):59-460 is a pure transition table dispatching on `state.type` and returning `{ next?: CommandState; execute?: () => void }`:

```ts
// vim/transitions.ts:283-332 (operator + multiplicative operatorCount)
function fromOperator(
  state: { type: 'operator'; op: Operator; count: number },
  input: string,
  ctx: TransitionContext,
): TransitionResult {
  // dd, cc, yy = line operation
  if (input === state.op[0]) {
    return { execute: () => executeLineOp(state.op, state.count, ctx) }
  }
  if (/[0-9]/.test(input)) {
    return {
      next: { type: 'operatorCount', op: state.op, count: state.count, digits: input },
    }
  }
  return handleOperatorInput(state.op, state.count, input, ctx) ?? { next: { type: 'idle' } }
}

function fromOperatorCount(
  state: { type: 'operatorCount'; op: Operator; count: number; digits: string },
  input: string,
  ctx: TransitionContext,
): TransitionResult {
  if (/[0-9]/.test(input)) {
    const parsedDigits = Math.min(parseInt(state.digits + input, 10), MAX_VIM_COUNT)
    return { next: { ...state, digits: String(parsedDigits) } }
  }
  const effectiveCount = state.count * parseInt(state.digits, 10)
  return handleOperatorInput(state.op, effectiveCount, input, ctx) ?? { next: { type: 'idle' } }
}
```

Thus `2d3w` walks `idle` → `count("2")` → `operator('delete', 2)` → `operatorCount('delete', 2, "3")` → executes `executeOperatorMotion('delete', 'w', 6, ctx)`. Notice also how `0` is start-of-logical-line in `fromIdle` ([transitions.ts](../../vim/transitions.ts):253-257) but appends as a digit inside `fromCount` and `fromOperatorCount`.

#### 2. Motions, Text Objects, and Operators (`vim/motions.ts`, `textObjects.ts`, `operators.ts`)

- **Motions** ([vim/motions.ts](../../vim/motions.ts):13-82): `resolveMotion(key, cursor, count)` iterates up to `count` steps over immutable `Cursor` methods (`nextVimWord`, `downLogicalLine`, `down` for `gj`, etc.) and breaks early as soon as `next.equals(result)` (no wasted work at buffer boundaries). `isInclusiveMotion` marks `e`, `E`, `$`; `isLinewiseMotion` marks `j`, `k`, `G`, `gg` (explicitly excluding `gj`/`gk`).
- **Text objects** ([vim/textObjects.ts](../../vim/textObjects.ts):38-186): `findTextObject()` supports `w`/`W` (pre-segmenting the buffer via `Intl.Segmenter` from `getGraphemeSegmenter()` so emoji and accented characters never split), line-scoped quote objects (`"`, `'`, `` ` ``) paired strictly `0-1, 2-3, ...`, and nested depth-counting bracket objects (`()`, `[]`, `{}`, `<>`, `b`, `B`) spanning multiple lines.
- **Operators** ([vim/operators.ts](../../vim/operators.ts):42-556): `getOperatorRange()` handles three subtle Vim/harness rules in one place:
  1. `cw` / `cW` changes to the *end* of the word (matching Vim's classic `ce` exception) instead of deleting trailing whitespace up to the next word.
  2. Linewise motions (`dj`, `dk`, `dG`, `dgg`, and `dd` in `executeLineOp`) expand to full `\n`-bounded lines, absorbing the *preceding* newline when deleting the last line so no stray blank line remains, and normalize the yanked register to end with `\n` for linewise `p`/`P`.
  3. **Image-pill protection** ([vim/operators.ts](../../vim/operators.ts):469-473):
     ```ts
     // vim/operators.ts:469-473
     // Word motions can land inside an [Image #N] chip; extend the range to
     // cover the whole chip so dw/cw/yw never leave a partial placeholder.
     from = cursor.snapOutOfImageRef(from, 'start')
     to = cursor.snapOutOfImageRef(to, 'end')
     ```

#### 3. Bridging Into React (`hooks/useVimInput.ts` + `components/VimTextInput.tsx`)

[hooks/useVimInput.ts](../../hooks/useVimInput.ts):34-316 wraps `useTextInput` and intercepts its `onInput` handler:

- **Ref-backed machine, state-backed badge:** `vimStateRef` and `persistentRef` mutate synchronously on every keypress; only `mode` (`'INSERT' | 'NORMAL'`) triggers React `setMode` so the footer badge updates without re-rendering on `d` → `i` → `"`.
- **Dot-repeat without recursion:** Exiting INSERT mode snapshots `insertedText` into `persistentRef.current.lastChange = { type: 'insert', text }` (grapheme-safe on Backspace via `lastGrapheme`). Pressing `.` calls `replayLastChange()`, which constructs an `OperatorContext` with `isReplay = true` so `recordChange` becomes a no-op and replaying never overwrites `lastChange`.
- **Shared rendering:** `<VimTextInput>` ([components/VimTextInput.tsx](../../components/VimTextInput.tsx):13-136) passes the returned `vimInputState` straight into `<BaseTextInput>` alongside `useTerminalFocus()` (inverting the cursor cell only when the terminal window is focused) and `useClipboardImageHint()`.

### Hidden Invariants & Failure Modes

- **Why `inputFilter` is stripped from `useTextInput` and invoked manually** ([hooks/useVimInput.ts](../../hooks/useVimInput.ts):42-46, 177-181): `useVimInput` passes `inputFilter: undefined` to `useTextInput` and runs `inputFilter(rawInput, key)` itself at the top of `handleVimInput` in *both* modes—but only feeds the filtered string forward in `INSERT` mode (`const input = state.mode === 'INSERT' ? filtered : rawInput`). Otherwise, pasting an image pill (which arms `lazySpaceInputFilter`), hitting `Esc` to enter NORMAL mode, and returning to INSERT mode would leave the filter stale and prepend a surprise space—whereas applying the filtered string in NORMAL mode would turn `'w'` into `' w'` and break command dispatch.
- **Escape intentionally bypasses `keybindings/`** ([hooks/useVimInput.ts](../../hooks/useVimInput.ts):189-201): `Esc` in INSERT always calls `switchToNormalMode()` (stepping the cursor left by 1 unless at offset 0 or after `\n`), and `Esc` in NORMAL resets `command` to `{ type: 'idle' }`. Leaving it out of `keybindings.json` guarantees a user config can never trap them in INSERT mode.
- **Guarding Backspace/Delete in literal-character states** ([hooks/useVimInput.ts](../../hooks/useVimInput.ts):251-271, [vim/transitions.ts](../../vim/transitions.ts):438-448): Backspace maps to `h` and Delete maps to `x` *only* when `expectsMotion` is true (`idle`, `count`, `operator`, `operatorCount`—with Delete also excluded from `count` so `5<Del>` doesn't become a destructive `5x`). In `replace`, `find`, and `operatorFind`, mapping them would turn `r<BS>` into "replace with `h`" and `df<Del>` into "delete to `x`". Meanwhile `fromReplace` explicitly checks `if (input === '') return { next: { type: 'idle' } }` so `r<BS>` cancels cleanly instead of deleting the character under the cursor.
- **Logical vs. wrapped line asymmetry in `vim/operators.ts`:** Notice an instructive detail in the snapshot: `executeLineOp` ([vim/operators.ts](../../vim/operators.ts):109-111) carefully counts `\n` via `countCharInString` because `cursor.getPosition()` returns the *wrapped visual* row, whereas `executeJoin` (line 261), `executePaste` (line 308), `executeIndent` (line 355), and `executeOpenLine` (line 403) still index `text.split('\n')` using `cursor.getPosition().line`—a real subtle boundary where long wrapped prompts behave differently across operators.

---

## Putting the Layer Together

Here is how a keystroke travels from Ink's input pipeline through keybinding interception, Vim/prompt editing, `QueryGuard` + queue orchestration, `query()`, and back into bounded terminal frames:

```mermaid
flowchart TD
    MAIN["main.tsx (createRoot + showSetupScreens)"] --> LAUNCH["replLauncher.tsx (lazy import App + REPL)"]
    LAUNCH --> APP["components/App.tsx (FPS + Stats + AppState)"]
    APP --> REPL["screens/REPL.tsx"]

    REPL --> KB["KeybindingSetup (KeybindingProvider + ChordInterceptor)"]
    KB -->|"1st: chord / unbound / stopImmediatePropagation"| HANDLERS["Global / Scroll / CancelRequest / useKeybindings"]
    KB -->|"2nd: fall-through"| PI["PromptInput (pills, paste, stash, undo, history)"]
    PI -->|"vim enabled"| VIM["VimTextInput -> useVimInput -> vim/ transitions"]
    PI -->|"standard"| TI["TextInput -> useTextInput"]

    PI -->|"onSubmit"| HPS["handlePromptSubmit.ts"]
    HPS -->|"queryGuard.isActive"| Q["messageQueueManager (now > next > later)"]
    Q -->|"idle auto-drain (useQueueProcessor)"| HPS
    HPS -->|"queryGuard.reserve() -> processUserInput()"| ONQ["REPL.onQuery (queryGuard.tryStart)"]

    ONQ -->|"for await"| QGEN["query() AsyncGenerator (Chapter 07)"]
    QGEN -->|"StreamEvent / Message / Tombstone"| HMS["handleMessageFromStream()"]
    HMS --> STATE["messages + streamingText + streamingToolUses + streamMode"]
    QGEN -->|"canUseTool"| PERM["toolUseConfirmQueue -> getFocusedInputDialog()"]

    STATE --> MSG["Messages.tsx (split memo pipeline)"]
    MSG -->|"fullscreen"| VML["VirtualMessageList + useVirtualScroll (quantized 40-row bins)"]
    MSG -->|"main screen"| CAP["computeSliceStart (200+50 UUID SliceAnchor)"]
    PERM -->|"suppressed if isPromptInputActive"| OVERLAY["PermissionRequest / FullscreenLayout overlay"]
```

And underneath that loop sit two load-bearing state/dispatch invariants that keep concurrent input from tearing:

```text
1. QueryGuard lifecycle (utils/QueryGuard.ts - sync + useSyncExternalStore)
   +------+  reserve()     +-------------+  tryStart() [++gen]  +---------+
   | idle | -------------> | dispatching | -------------------> | running |
   +--+---+ <------------- +-------------+                      +----+----+
      |     cancelReservation()                                      |
      |                                                              |
      |     tryStart() [++gen] (direct submit)                       |
      +--------------------------------------------------------------+
      ^                                                              |
      +---------- end(gen) [if gen matches] / forceEnd() [++gen] ----+

2. Two-phase Keybinding dispatch (KeybindingProviderSetup + useKeybinding)
   Ink useInput
     +-> [1] ChordInterceptor (mounted FIRST inside KeybindingProvider)
     |        +- chord_started / chord_cancelled / unbound -> stopProp
     |        +- match (wasInChord=true)  -> invoke registry + stopProp
     |        +- match (wasInChord=false) -> clear pending, FALL THROUGH
     +-> [2] ScrollKeybindingHandler (mounted before CancelRequestHandler)
     |        +- Ctrl+C w/ selection copies + stops; no-op wheel -> false
     +-> [3] CancelRequestHandler / per-context useKeybindings
     +-> [4] PromptInput -> VimTextInput (Esc hardcoded) / TextInput
```

---

## How This Snaps Into the Next Layer

With Chapter 21 complete, we have rebuilt the entire agent harness from Layer 0 atoms ([Chapter 01](01-atoms-types-stores-and-primitives.md)) all the way to the interactive terminal workspace. Look at how the top of this chapter connects directly into `main.tsx`:

1. [main.tsx](../../main.tsx):2218-2242 calls `getRenderContext(false)` from [interactiveHelpers.tsx](../../interactiveHelpers.tsx), dynamically imports `createRoot` from [ink.ts](../../ink.ts), logs the `startup` timer *before* any blocking dialog renders (so p99 startup metrics aren't skewed by users sitting on trust dialogs), and awaits `showSetupScreens(...)`.
2. After resolving sessions, `--resume` pickers, bridge checks, and initial hook messages, [main.tsx](../../main.tsx):3798-3806 hands `root`, `{ getFpsMetrics, stats, initialState }`, `sessionConfig`, and `renderAndRun` straight to `launchRepl()` in [replLauncher.tsx](../../replLauncher.tsx).

In [Chapter 22](22-cold-start-mastery-cli-init-main.md), we step into Layer 8 and trace the cold-start funnel from the very first byte executed in `entrypoints/cli.tsx`, through `entrypoints/init.ts` (TLS/CA setup, preconnects, safe env vars), into `setup.ts` and `main.tsx`—seeing how Claude Code decides in milliseconds whether to branch into a zero-import fast path, headless `-p` / SDK mode, or the full interactive REPL we just dissected.

---

## Reading Exercises & Code Checkpoints

1. **Trace the context-precedence mechanics.** Open [keybindings/resolver.ts](../../keybindings/resolver.ts):187-236 alongside [keybindings/defaultBindings.ts](../../keybindings/defaultBindings.ts):32-194. Suppose `ThemePicker` mounts and calls `useRegisterKeybindingContext('ThemePicker')`, and the user presses `Ctrl+T`. Trace why `theme:toggleSyntaxHighlighting` wins over `Global`'s `app:toggleTodos`—and predict what would happen if a user's `keybindings.json` put a `Global` override for `ctrl+t` *after* a `ThemePicker` block.
2. **Audit every `QueryGuard` transition site.** Run:
   ```sh
   rg -n "queryGuard\.(reserve|cancelReservation|tryStart|end|forceEnd|isActive)" screens/ utils/ hooks/
   ```
   Verify how `executeUserInput()`'s `try/finally` cooperates with `onQuery()`'s `try/finally` and `onCancel()`'s `forceEnd()` when a user hits `Esc` during `processUserInput()` vs. mid-stream inside `query()`.
3. **Inspect all `Messages.tsx` memory and scrollback defenses.** Read [components/Messages.tsx](../../components/Messages.tsx):278-340 and [hooks/useVirtualScroll.ts](../../hooks/useVirtualScroll.ts):13-58. Why is `DEFAULT_ESTIMATE = 3` intentionally biased *low* while `PESSIMISTIC_HEIGHT = 1` is used for viewport coverage, and what specific bug does `SLIDE_STEP = 25` prevent during rapid scrolling?
4. **Trace a compound Vim edit across `useVimInput` and `vim/`.** Walk the exact state sequence of typing `2d3w` followed by `.` (dot-repeat) and then `r<Backspace>` starting from `useVimInput.ts:175` through `vim/transitions.ts` and `vim/operators.ts`. Where is the `[Image #N]` boundary protected during `2d3w`, and why doesn't `r<Backspace>` delete the character under the cursor?


---

<!-- chapters/22-cold-start-mastery-cli-init-main.md — https://reverseengineeringclaudecode.com/chapters/22-cold-start-mastery-cli-init-main -->

# Chapter 22 — Cold Start Mastery: From `entrypoints/cli.tsx` Through `init.ts` to `main.tsx`

> **Layer:** Layer 8 (Entrypoints, Startup, SDK & Remote Control)
> **Prerequisites:** [Chapter 01](01-atoms-types-stores-and-primitives.md), [Chapter 14](14-configuration-settings-and-enterprise-policy.md), [Chapter 21](21-the-interactive-repl-screens-keybindings-and-vim.md)
> **Primary Source Files:**
> - [`entrypoints/cli.tsx`](../../entrypoints/cli.tsx) — Zero-import bootstrapper, pre-import env fixes, fast-path command router, early stdin capture, and dynamic handoff to `main.tsx`.
> - [`entrypoints/init.ts`](../../entrypoints/init.ts) — Memoized core initializer enforcing config → safe env → CA certs → signal handlers → mTLS/proxy → API TCP+TLS preconnect ordering, plus post-trust OTLP telemetry.
> - [`setup.ts`](../../setup.ts) — Working-directory and hooks-snapshot lock-in, `--worktree`/`--tmux` provisioning, `tengu_started` crash-denominator beacon, and bypass-permission safety gates.
> - [`main.tsx`](../../main.tsx) — Top-of-file MDM/keychain prefetches, Commander setup (with `-p` subcommand skip), `preAction` hook, trust boundary orchestration, and interactive vs. headless dispatch.
> - [`interactiveHelpers.tsx`](../../interactiveHelpers.tsx) & [`replLauncher.tsx`](../../replLauncher.tsx) — Interactive onboarding/trust dialog pipeline (`showSetupScreens()`), lazy REPL mounting (`launchRepl()`), and Ink exit epilogue (`renderAndRun()`).
> - [`utils/startupProfiler.ts`](../../utils/startupProfiler.ts) & [`utils/profilerBase.ts`](../../utils/profilerBase.ts) — Sampled `perf_hooks` checkpointing, parallel memory snapshots, and `tengu_startup_perf` phase telemetry.
> - [`utils/gracefulShutdown.ts`](../../utils/gracefulShutdown.ts) & [`utils/cleanupRegistry.ts`](../../utils/cleanupRegistry.ts) — Cycle-free cleanup registry, Bun `signal-exit` workaround, synchronous terminal reset, bounded teardown phases, and `SIGKILL` fallback.

---

## Why This Layer Exists

By the end of [Chapter 21](21-the-interactive-repl-screens-keybindings-and-vim.md), every subsystem of Claude Code exists: stores, tools, prompt caches, `query()`, compaction, memory, permissions, hooks, settings, MCP, plugins, subagents, swarms, and a custom React/Ink terminal renderer. Now they all have to wake up inside a single CLI binary—fast enough to feel instantaneous when a user runs `claude --version` or pipes text into `claude -p`, yet disciplined enough to enforce enterprise security boundaries before a single untrusted byte executes.

Three hard systems constraints shape the boot path:

1. **Monolith import gravity.** [`main.tsx`](../../main.tsx) is 4,683 lines (~785 KB on disk, including its inline base64 source map) whose static import graph pulls in Commander, React, Ink, tools, commands, MCP config parsers, and eleven startup migrations (~135 ms of synchronous module evaluation). Paying that cost for `--version`, MCP helper servers, daemon workers, or `tmux` trampolines would destroy CLI responsiveness.
2. **Irreversible runtime latches.** Several process-level invariants lock in permanently on first use: BoringSSL caches the TLS certificate store on the first handshake; tool modules capture `DISABLE_BACKGROUND_TASKS` into module-level `const`s at import time; Windows `SearchPathW` searches the current directory unless blocked up front; and `.claude/settings.json` inside an untrusted git clone cannot be allowed to set `ANTHROPIC_BASE_URL`, `LD_PRELOAD`, or `NODE_EXTRA_CA_CERTS` until a human accepts the workspace trust dialog.
3. **Hostile teardown environments.** Processes exit on `SIGINT`, `SIGTERM`, `SIGHUP`, silent macOS TTY revocation, or declined trust dialogs—often with live MCP child processes, unflushed JSONL transcripts, pending 10-second analytics POSTs, and an Ink alternate screen waiting to overwrite the shell prompt.

> [!NOTE]
> **Snapshot & build-artifact transparency:** Compiled `.tsx` files in this checkout ([`entrypoints/cli.tsx`](../../entrypoints/cli.tsx), [`main.tsx`](../../main.tsx), [`interactiveHelpers.tsx`](../../interactiveHelpers.tsx), [`replLauncher.tsx`](../../replLauncher.tsx)) contain inline base64 source maps and constant-folded external-build literals such as `"external" === 'ant'` (`main.tsx:266,340,428,1137,1531,1763,2013,2223,2819,3064,3581,3816,4370,4381,4405`) and `"production" === 'test' || isEnvTruthy(false)` (`interactiveHelpers.tsx:105`). In addition, several `feature('...')`-gated targets referenced by the startup router are **absent from this snapshot** and observed only at their call sites: `daemon/workerRegistry.ts`, `daemon/main.ts`, `cli/bg.ts`, `cli/handlers/templateJobs.ts`, `environment-runner/main.ts`, `self-hosted-runner/main.ts`, `utils/udsMessaging.ts`, `services/contextCollapse/index.ts`, `utils/attributionHooks.ts`, `utils/sessionDataUploader.ts`, `utils/eventLoopStallDetector.ts`, `ssh/createSSHSession.ts`, `server/server.ts`, `assistant/index.ts`, and `proactive/index.ts`.

---

## 1. Zero-Import Bootstrap and Fast-Path Branching (`entrypoints/cli.tsx`)

### The Problem

In JavaScript runtimes (Bun and Node.js alike), static `import` declarations evaluate depth-first *before* line 1 of the entry module executes. If `cli.tsx` statically imported `config.ts`, `startupProfiler.ts`, or `main.tsx`, then `claude --version` would instantiate thousands of modules just to print a build-time version string. Conversely, certain environment fixes must execute *before* any downstream module evaluates—because waiting until `init()` is already too late for modules that read `process.env` at top level.

### The Real Implementation

[`entrypoints/cli.tsx`](../../entrypoints/cli.tsx) solves both halves by importing **only** `feature` from `'bun:bundle'` statically, running three surgical `process.env` patches at module top level, and making every other import inside `main()` dynamic:

```ts
// entrypoints/cli.tsx:1-48
import { feature } from 'bun:bundle';

// Bugfix for corepack auto-pinning, which adds yarnpkg to peoples' package.jsons
process.env.COREPACK_ENABLE_AUTO_PIN = '0';

// Set max heap size for child processes in CCR environments (containers have 16GB)
if (process.env.CLAUDE_CODE_REMOTE === 'true') {
  const existing = process.env.NODE_OPTIONS || '';
  process.env.NODE_OPTIONS = existing
    ? `${existing} --max-old-space-size=8192`
    : '--max-old-space-size=8192';
}

// Harness-science L0 ablation baseline. Inlined here (not init.ts) because
// BashTool/AgentTool/PowerShellTool capture DISABLE_BACKGROUND_TASKS into
// module-level consts at import time — init() runs too late.
if (feature('ABLATION_BASELINE') && process.env.CLAUDE_CODE_ABLATION_BASELINE) {
  for (const k of [
    'CLAUDE_CODE_SIMPLE', 'CLAUDE_CODE_DISABLE_THINKING',
    'DISABLE_INTERLEAVED_THINKING', 'DISABLE_COMPACT', 'DISABLE_AUTO_COMPACT',
    'CLAUDE_CODE_DISABLE_AUTO_MEMORY', 'CLAUDE_CODE_DISABLE_BACKGROUND_TASKS',
  ]) {
    process.env[k] ??= '1';
  }
}

async function main(): Promise<void> {
  const args = process.argv.slice(2);

  // Fast-path for --version/-v: zero module loading needed
  if (args.length === 1 && (args[0] === '--version' || args[0] === '-v' || args[0] === '-V')) {
    console.log(`${MACRO.VERSION} (Claude Code)`);
    return;
  }

  // For all other paths, load the startup profiler
  const { profileCheckpoint } = await import('../utils/startupProfiler.js');
  profileCheckpoint('cli_entry');
```

Immediately after `'cli_entry'`, `cli.tsx` walks a ladder of fast-path branches (`entrypoints/cli.tsx:53-274`). Notice that every `feature('...')` check is written inline—never wrapped in a helper—so Bun's bundler can dead-code-eliminate the dynamic `import()` target completely in builds where that flag is off:

| CLI Trigger | Gate / Scope | Loaded Target | Snapshot Status | Notable Startup Rule |
|---|---|---|---|---|
| `--version` / `-v` / `-V` | Always | None (`MACRO.VERSION`) | Inlined | Zero imports; exits before profiler |
| `--dump-system-prompt` | `feature('DUMP_SYSTEM_PROMPT')` | `config`, `model`, `constants/prompts` | Present | Ant-only prompt-eval extractor |
| `--claude-in-chrome-mcp` / `--chrome-native-host` | Always | `utils/claudeInChrome/*` | Present | Bypasses CLI & Ink completely |
| `--computer-use-mcp` | `feature('CHICAGO_MCP')` | `utils/computerUse/mcpServer.ts` | Present | Isolated MCP server process |
| `--daemon-worker` | `feature('DAEMON')` | `daemon/workerRegistry.js` | Absent | Precedes `daemon`; skips `enableConfigs()` & sinks so workers stay lean |
| `remote-control` / `rc` / `remote` / `sync` / `bridge` | `feature('BRIDGE_MODE')` | `bridge/bridgeMain.ts` | Present | Strict order: `enableConfigs` → OAuth check → GrowthBook gate → min version → policy limits |
| `daemon` | `feature('DAEMON')` | `daemon/main.js` | Absent | Calls `enableConfigs()` + `initSinks()` |
| `ps\|logs\|attach\|kill`, `--bg`/`--background` | `feature('BG_SESSIONS')` | `cli/bg.js` | Absent | Flag literals inlined so `bg.js` loads only on dispatch |
| `new\|list\|reply` | `feature('TEMPLATES')` | `cli/handlers/templateJobs.js` | Absent | Calls `process.exit(0)` because `mountFleetView`'s Ink TUI can leave dangling handles |
| `environment-runner` / `self-hosted-runner` | `feature('BYOC_ENVIRONMENT_RUNNER')` / `feature('SELF_HOSTED_RUNNER')` | `environment-runner/main.js`, `self-hosted-runner/main.js` | Absent | Headless cloud/BYOC worker loops |
| `--worktree` + `--tmux` (`--tmux=classic`) | Runtime `isWorktreeModeEnabled()` | `utils/worktree.ts` | Present | Execs into tmux before paying `main.tsx` load cost; falls through if unhandled |

If none of the fast-paths claim the invocation, `entrypoints/cli.tsx:277-298` runs three final pre-`main.tsx` steps:

1. **Flag normalization:** redirects single-arg `--update` / `--upgrade` into `process.argv = [..., 'update']`.
2. **Early `--bare` latch:** `if (args.includes('--bare')) process.env.CLAUDE_CODE_SIMPLE = '1'` so module-evaluation and Commander option-building gates fire *during* `main.tsx`'s import, not only inside the action handler.
3. **Early keystroke capture ([`utils/earlyInput.ts`](../../utils/earlyInput.ts)):** users frequently type `claude<Enter>` and start typing their prompt immediately while `main.tsx` is still loading. Calling `startCapturingEarlyInput()` right before `await import('../main.js')` puts TTY `stdin` into raw mode and buffers printable text, grapheme-aware backspaces (`lastGrapheme`), and newlines while ignoring ANSI escape sequences (`utils/earlyInput.ts:29-136`).

### Hidden Invariants & Failure Modes

- **Why `bridge` checks OAuth *before* GrowthBook (`entrypoints/cli.tsx:132-145`):** `getBridgeDisabledReason()` awaits live GrowthBook initialization so stale disk cache cannot override a server kill-switch, but without `getClaudeAIOAuthTokens()?.accessToken`, GrowthBook lacks user identity headers and silently returns default `false`. Checking auth first surfaces `BRIDGE_LOGIN_ERROR` instead of a misleading "feature disabled" message.
- **Why early input capture refuses `-p`/`--print` (`utils/earlyInput.ts:30-40`):** enabling `setRawMode(true)` disables terminal `ISIG` (kernel translation of `Ctrl+C` into `SIGINT`). In print mode, that would render the process uninterruptible. Even in interactive mode, raw mode means `earlyInput.ts` must explicitly intercept byte `3` (`Ctrl+C`) and call `process.exit(130)` (`utils/earlyInput.ts:81-86`) because `gracefulShutdown` has not been installed yet.
- **Why `stopCapturingEarlyInput()` never calls `setRawMode(false)` (`utils/earlyInput.ts:154-156`):** it only detaches the `'readable'` listener. Resetting raw mode right as Ink mounts would race with Ink's own stdin initialization and drop keystrokes.
- **Top-level `void main()` (`entrypoints/cli.tsx:302`):** because the entry promise is unawaited, any synchronous or async `throw` out of early CLI validation becomes an unhandled rejection—which in `stream-json` mode vanishes silently. That is why early validation failures in `main.tsx` write to `stderr` and call `process.exit(1)` explicitly (`main.tsx:1487-1490`).

---

## 2. The Strict Boot Sequence: `entrypoints/init.ts` and Startup Profiling

### The Problem

Once `main.tsx` is loaded and a command is actually executing (not `--help`), Claude Code must initialize configuration, environment variables, CA certificates, mTLS/proxy agents, TCP+TLS warmup, signal handlers, and telemetry. Every one of those subsystems can silently break another if ordered wrong:

- Fire any `fetch()` before `NODE_EXTRA_CA_CERTS` is populated from `settings.json`, and Bun's BoringSSL caches the default CA store without the corporate root certificate for the rest of the process lifetime.
- Load `config.ts` from inside `utils/caCerts.ts`, and `config.ts → file.ts → permissions/filesystem.ts → commands.ts` pulls ~5,300 modules (React, Ink, every slash command) into `proxy.ts`/`mtls.ts`—bloating the Agent SDK bundle from ~0.4 MB to ~10.8 MB (`utils/caCertsConfig.ts:1-14`).
- Apply project-level `.claude/settings.json` environment variables before the trust dialog, and a hostile repository can redirect `ANTHROPIC_BASE_URL` or inject `NODE_EXTRA_CA_CERTS` / `LD_PRELOAD` during onboarding.

### The Real Implementation

[`entrypoints/init.ts`](../../entrypoints/init.ts) wraps the entire boot sequence in `memoize(async () => ...)` so repeated callers share one idempotent initialization promise, and enforces a strict seven-step sequence:

```ts
// entrypoints/init.ts:63-160 (abridged for clarity)
enableConfigs()
profileCheckpoint('init_configs_enabled')

// 1. Safe env vars only before trust (full env applied post-trust)
applySafeConfigEnvironmentVariables()

// 2. Copy NODE_EXTRA_CA_CERTS from user config/settings BEFORE any TLS
//    handshake so Bun's BoringSSL cert store sees it at first init.
applyExtraCACertsFromConfig()
profileCheckpoint('init_safe_env_vars_applied')

// 3. Install signal handlers before spawning background work
setupGracefulShutdown()
profileCheckpoint('init_after_graceful_shutdown')

// 4. Fire-and-forget non-blocking warmups (1P logger deferred to skip OTel sdk-logs)
void Promise.all([
  import('../services/analytics/firstPartyEventLogger.js'),
  import('../services/analytics/growthbook.js'),
]).then(([fp, gb]) => {
  fp.initialize1PEventLogging()
  gb.onGrowthBookRefresh(() => { void fp.reinitialize1PEventLoggingIfConfigChanged() })
})
void populateOAuthAccountInfoIfNeeded()
void initJetBrainsDetection()
void detectCurrentRepository()
if (isEligibleForRemoteManagedSettings()) initializeRemoteManagedSettingsLoadingPromise()
if (isPolicyLimitsEligible()) initializePolicyLimitsLoadingPromise()
recordFirstStartTime()

// 5. Configure mTLS + HTTP/HTTPS proxy agents (NO_PROXY-aware)
configureGlobalMTLS()
configureGlobalAgents()
profileCheckpoint('init_network_configured')

// 6. Overlap Anthropic API TCP+TLS handshake (~100-200ms) with remaining startup
preconnectAnthropicApi()
```

Walk through the load-bearing engineering details behind each step:

1. **`enableConfigs()` ([`utils/config.ts:1334-1356`](../../utils/config.ts)):** flips `configReadingAllowed = true` and reads `~/.claude.json` with `throwOnInvalid = true`. Guarding config reads behind this latch catches accidental module-init disk reads during development. If `~/.claude.json` is malformed (`ConfigParseError`), `init.ts:216-233` branches on `getIsNonInteractiveSession()`: non-interactive callers write plain text to `stderr` and call `gracefulShutdownSync(1)` (never rendering an Ink dialog that would corrupt JSON consumers such as Desktop's `plugin marketplace list --json`), while interactive sessions dynamically import `InvalidConfigDialog`.
2. **Two-phase env loading ([`utils/managedEnv.ts:124-199`](../../utils/managedEnv.ts)):** before trust, `applySafeConfigEnvironmentVariables()` snapshots `ccdSpawnEnvKeys` once when `CLAUDE_CODE_ENTRYPOINT === 'claude-desktop'` (so user settings cannot override host-orchestrated vars like `OTEL_LOGS_EXPORTER=console` and corrupt stdio JSON-RPC), strips SSH-tunnel and host-managed-provider vars via `filterSettingsEnv()`, applies *all* env vars from trusted sources (`~/.claude.json`, `userSettings`, `flagSettings`), computes `isRemoteManagedSettingsEligible()`, applies `policySettings`, and applies only the `SAFE_ENV_VARS` allowlist from project-scoped settings.
3. **CA certs split across two modules ([`utils/caCertsConfig.ts`](../../utils/caCertsConfig.ts) & [`utils/caCerts.ts`](../../utils/caCerts.ts)):** `NODE_EXTRA_CA_CERTS` is intentionally excluded from `SAFE_ENV_VARS` because trusting an attacker's CA defeats TLS. Yet corporate users behind HTTPS proxies need their CA loaded *during `init()`*. `applyExtraCACertsFromConfig()` resolves this tension by reading `NODE_EXTRA_CA_CERTS` strictly from user-controlled `~/.claude/settings.json` and `~/.claude.json`—never project settings—and writing it to `process.env`. Meanwhile, [`utils/caCerts.ts:28-50`](../../utils/caCerts.ts) remains completely `config.ts`-free (preventing the 10.8 MB SDK bloat) and lazy-`require`s `'tls'` only when `--use-system-ca`, `--use-openssl-ca`, or `NODE_EXTRA_CA_CERTS` is actually set, because Bun's `node:tls` eagerly materializes ~150 Mozilla root certificates (~750 KB heap) on import.
4. **Proxy, mTLS, and `preconnectAnthropicApi()` ([`utils/mtls.ts`](../../utils/mtls.ts), [`utils/proxy.ts`](../../utils/proxy.ts), [`utils/apiPreconnect.ts`](../../utils/apiPreconnect.ts)):** `configureGlobalAgents()` ejects any previous axios request interceptor before installing a `NO_PROXY`-aware one, and lazy-`require`s `undici` (~1.5 MB deferred on the common no-proxy/no-mTLS path). Only *after* CA certs and agents are ready does `preconnectAnthropicApi()` fire a `HEAD` request with a 10-second `AbortSignal.timeout` to warm Bun's global keep-alive pool (`utils/apiPreconnect.ts:31-71`). It explicitly returns early for Bedrock/Vertex/Foundry (different endpoints) and for proxy/mTLS/`ANTHROPIC_UNIX_SOCKET` (where the SDK passes a custom dispatcher that never shares the global pool). A comment in [`utils/apiPreconnect.ts:15-18`](../../utils/apiPreconnect.ts) records the scar: an earlier call site in `cli.tsx` had to be removed because it ran before `settings.json` loaded, warming the wrong pool and locking BoringSSL before `NODE_EXTRA_CA_CERTS` landed.
5. **CCR upstream proxy & post-trust OTLP telemetry (`entrypoints/init.ts:167-210, 247-340`):** when `CLAUDE_CODE_REMOTE` is truthy, `init()` lazily boots `upstreamproxy/upstreamproxy.ts` (fail-open; covered in [Chapter 24](24-across-the-wire-remote-sessions-bridge-and-direct-connect.md)), sets up Windows git-bash, registers LSP and swarm-team (`gh-32730`) cleanups, and creates the scratchpad directory. Customer OpenTelemetry (`initializeTelemetryAfterTrust()`) stays completely dormant until after trust—deferring ~400 KB of OTel/protobuf in `utils/telemetry/instrumentation.ts` (and ~700 KB of `@grpc/grpc-js`) until `waitForRemoteManagedSettingsToLoad()` resolves and `applyConfigEnvironmentVariables()` re-applies remote OTEL env vars. Once the meter initializes, `setMeterState()` increments `getSessionCounter()?.add(1)` because the earlier startup path executed while the meter was still `null` (`entrypoints/init.ts:335-338`).

#### Measuring Every Millisecond: `utils/startupProfiler.ts`

Every checkpoint above feeds [`utils/startupProfiler.ts`](../../utils/startupProfiler.ts) and [`utils/profilerBase.ts`](../../utils/profilerBase.ts). To keep profiling cost at zero for 99.5% of external runs, sampling is decided once at module load:

```ts
// utils/startupProfiler.ts:26-54
const DETAILED_PROFILING = isEnvTruthy(process.env.CLAUDE_CODE_PROFILE_STARTUP)
const STATSIG_SAMPLE_RATE = 0.005
const STATSIG_LOGGING_SAMPLED =
  process.env.USER_TYPE === 'ant' || Math.random() < STATSIG_SAMPLE_RATE
const SHOULD_PROFILE = DETAILED_PROFILING || STATSIG_LOGGING_SAMPLED

const memorySnapshots: NodeJS.MemoryUsage[] = []

const PHASE_DEFINITIONS = {
  import_time: ['cli_entry', 'main_tsx_imports_loaded'],
  init_time: ['init_function_start', 'init_function_end'],
  settings_time: ['eagerLoadSettings_start', 'eagerLoadSettings_end'],
  total_time: ['cli_entry', 'main_after_run'],
} as const
```

Two subtle implementation details make the profiler trustworthy:
- `getPerformance()` ([`utils/profilerBase.ts:14-20`](../../utils/profilerBase.ts)) lazy-`require`s `perf_hooks` only when `SHOULD_PROFILE` is true.
- Under `CLAUDE_CODE_PROFILE_STARTUP=1`, heap/RSS readings are appended to a parallel `memorySnapshots[]` array indexed identically to `perf.getEntriesByType('mark')`—*not* a `Map<string, MemoryUsage>`—because checkpoints like `loadSettingsFromDisk_start` fire multiple times across plugin cache resets, and a `Map` would overwrite earlier snapshots (`utils/startupProfiler.ts:38-46`). Note also a minor doc drift in the file header (`0.1%` in comments vs. `STATSIG_SAMPLE_RATE = 0.005`, i.e., 0.5% in code).

### Hidden Invariants & Failure Modes

> [!IMPORTANT]
> **Post-trust transport invalidation:** When workspace trust is later accepted (or bypassed in `-p` mode), `applyConfigEnvironmentVariables()` ([`utils/managedEnv.ts:187-199`](../../utils/managedEnv.ts)) does not just call `Object.assign(process.env, ...)`. It explicitly invokes `clearCACertsCache()`, `clearMTLSCache()`, `clearProxyCache()`, and `configureGlobalAgents()` so any newly trusted proxy or mTLS settings replace the pre-trust transport agents cleanly without stacking duplicate axios interceptors.

- **Deadlock protection on remote-settings promises (`entrypoints/init.ts:120-128`):** `init()` initializes the loading promises for remote managed settings and policy limits *before* `loadRemoteManagedSettings()` is even called in `main.tsx`'s `preAction`. Those promises carry internal timeouts so callers (such as Agent SDK tests that never invoke `loadRemoteManagedSettings()`) never deadlock waiting for them.
- **Eager beta-tracing race guard (`entrypoints/init.ts:248-303`):** in non-interactive SDK sessions with `isBetaTracingEnabled()`, `initializeTelemetryAfterTrust()` kicks `doInitializeTelemetry()` eagerly without waiting for remote settings so the tracer is ready before the first query, while the remote-settings `.then()` path still calls `doInitializeTelemetry()` later—guarded against double-init by the `telemetryInitialized` latch (which resets to `false` on error to allow retries).

---

## 3. Winning the Import Race: Parallel Prefetches in `main.tsx` and `setup.ts`

### The Problem

Evaluating `main.tsx`'s static import graph takes ~135 ms on a warm machine. On macOS, enterprise MDM (`plutil`) plus two sequential `security find-generic-password` keychain lookups (`"Claude Code-credentials"` ~32 ms + `"Claude Code"` ~33 ms) would add another ~70 ms on top of that—followed by UDS socket binding (~20 ms), command/agent filesystem scans, and MCP config discovery. Running those sequentially turns cold start into a sluggish pause before the first frame even draws.

### The Real Implementation

Claude Code eliminates that serial chain by overlapping startup work across **four distinct waves**:

#### Wave 0 — Pre-Import Subprocess Launches (`main.tsx:1-20`)

The very first 20 lines of [`main.tsx`](../../main.tsx) interleave executable statements *above* line 21's heavy imports:

```ts
// main.tsx:9-21
import { profileCheckpoint, profileReport } from './utils/startupProfiler.js';
profileCheckpoint('main_tsx_entry');

import { startMdmRawRead } from './utils/settings/mdm/rawRead.js';
startMdmRawRead();

import { ensureKeychainPrefetchCompleted, startKeychainPrefetch } from './utils/secureStorage/keychainPrefetch.js';
startKeychainPrefetch();

import { feature } from 'bun:bundle'; // Heavy static imports begin here...
```

Look closely at the two leaf modules invoked here:
- [`utils/settings/mdm/rawRead.ts:55-123`](../../utils/settings/mdm/rawRead.ts) imports only `child_process`, `fs`, and `mdm/constants.ts`. On macOS, it checks `existsSync(path)` *synchronously* before calling `execFile('plutil', ...)`: non-MDM laptops skip the ~5 ms `plutil` spawn completely, while MDM machines guarantee `execFile` is the very first `await` so the OS spawns `plutil` before the event loop blocks on the remaining imports. On Windows, it fires `reg query` for `HKLM` and `HKCU` in parallel.
- [`utils/secureStorage/keychainPrefetch.ts:69-89`](../../utils/secureStorage/keychainPrefetch.ts) spawns both macOS `security` queries concurrently (skipped on non-darwin or under `isBareMode()`). Its comment captures a classic import-graph trap: it imports lightweight `macOsKeychainHelpers.ts` instead of `macOsKeychainStorage.ts`, because the latter pulls in `execa → human-signals → cross-spawn`—~58 ms of synchronous module init that would erase the entire savings! It also distinguishes `null` ("not started") from `{ stdout: null }` ("completed, exit 44 / no entry") and refuses to prime the cache on timeout so the synchronous fallback can retry rather than falsely caching "no key".

#### Wave 1 — Pre-Commander Normalization, Eager Settings, and `preAction` (`main.tsx:432-967`)

When `entrypoints/cli.tsx` invokes `cliMain()`, `main()` runs before Commander parses arguments:

1. **Windows PATH-hijack shield (`main.tsx:591`):** sets `process.env.NoDefaultCurrentDirectoryInExePath = '1'` before any child process can spawn, preventing Windows `SearchPathW` from executing malicious binaries dropped in an untrusted repository's cwd.
2. **Anti-debugging guard (`main.tsx:232-271`):** top-level `if ("external" !== 'ant' && isBeingDebugged()) process.exit(1)`. Under Bun single-file executables, application flags from `process.argv` leak into `process.execArgv` (Bun issue #11673), so the Bun branch skips matching `--debug` to avoid falsely killing `claude --debug`.
3. **Argv rewriting (`main.tsx:612-795`):** intercepts `cc://`/`cc+unix://` (`feature('DIRECT_CONNECT')`), OS protocol deep links `--handle-uri` and macOS LaunchServices `__CFBundleIdentifier === 'com.anthropic.claude-code-url-handler'` (`feature('LODESTONE')`), `claude assistant [sessionId]` (`feature('KAIROS')`), and `claude ssh <host> [dir]` (`feature('SSH_REMOTE')`). Stashing target parameters into module-level `_pendingConnect` / `_pendingAssistantChat` / `_pendingSSH` and rewriting `process.argv` routes interactive runs through the default action so they inherit the full REPL instead of a stripped-down subcommand.
4. **Interactive classification & `eagerLoadSettings()` (`main.tsx:799-855`):** detects `isNonInteractive = hasPrintFlag || hasInitOnlyFlag || hasSdkUrl || !process.stdout.isTTY`, stops early input capture for non-interactive runs, determines `CLAUDE_CODE_ENTRYPOINT` and `clientType`, and parses `--settings` and `--setting-sources` via [`utils/cliArgs.ts`](../../utils/cliArgs.ts) *before* `init()` runs.

> [!WARNING]
> **The 12x Prompt-Cache Scar (`main.tsx:445-457`):** When a caller passes inline JSON to `--settings '{...}'`, `loadSettingsFromFlag()` writes it to a temporary file so the settings loader can treat it uniformly. Crucially, the filename uses `contentHash: trimmedSettings`—*never* a random UUID. Why? Because the flag-settings file path lands inside the Bash tool's sandbox `denyWithinAllow` list, which is serialized into the tool definition sent to the Anthropic API. In Agent SDK loops where each `query()` spawns a fresh CLI subprocess, a random UUID mutated the tool schema on every call, invalidating the prompt-cache prefix and causing a 12x input token cost penalty.

5. **Commander `preAction` hook (`main.tsx:907-967`) & the `-p` subcommand skip (`main.tsx:3875-3890`):** attaching initialization to `program.hook('preAction')` guarantees `claude --help` never runs `init()` or migrations. When a real command executes, `preAction` joins Wave 0 via `await Promise.all([ensureMdmSettingsLoaded(), ensureKeychainPrefetchCompleted()])` (nearly free since both finished during imports), awaits `init()`, sets `process.title = 'claude'`, attaches logging/analytics sinks via [`utils/sinks.ts`](../../utils/sinks.ts) (so subcommands like `doctor` and `plugin` that bypass `setup()` don't silently drop queued events), wires repeatable `--plugin-dir` options (`gh-33508`), executes `runMigrations()` (`CURRENT_MIGRATION_VERSION = 11`, `main.tsx:325-352`), and kicks off non-blocking `loadRemoteManagedSettings()`, `loadPolicyLimits()`, and `feature('UPLOAD_USER_SETTINGS')` sync. Meanwhile, in `-p`/`--print` mode (unless a `cc://` URL was rewritten to `open`), `main.tsx:3883-3890` skips registering all 52 subcommands (`mcp`, `auth`, `plugin`, `doctor`, `update`, etc.) and jumps straight to `program.parseAsync(process.argv)`, saving ~65 ms on every headless invocation.

#### Wave 2 — Parallel `setup()`, Commands/Agents, and MCP Config Discovery (`main.tsx:1780-2031`, `setup.ts`)

Inside the default Commander action handler, `main.tsx` parses flags, validates tool permissions (`initializeToolPermissionContext()`), and kicks off read-only MCP config discovery (`mcpConfigPromise`, plus `claudeaiConfigPromise` in `-p` mode). Then it runs `setup()` in parallel with command and agent loading:

```ts
// main.tsx:1918-1936
const preSetupCwd = getCwd();
// Pure in-memory array pushes (<1ms). Previously ran inside setup() after
// ~20ms of awaits, causing parallel getCommands() to memoize an empty list.
if (process.env.CLAUDE_CODE_ENTRYPOINT !== 'local-agent') {
  initBuiltinPlugins();
  initBundledSkills();
}
const setupPromise = setup(
  preSetupCwd, permissionMode, allowDangerouslySkipPermissions,
  worktreeEnabled, worktreeName, tmuxEnabled,
  sessionId ? validateUuid(sessionId) : undefined,
  worktreePRNumber, messagingSocketPath,
);
const commandsPromise = worktreeEnabled ? null : getCommands(preSetupCwd);
const agentDefsPromise = worktreeEnabled ? null : getAgentDefinitionsWithOverrides(preSetupCwd);
commandsPromise?.catch(() => {});
agentDefsPromise?.catch(() => {});
await setupPromise;
```

Notice the two subtle guards in those 18 lines:
- **Preventing empty bundled-skills memoization:** `initBuiltinPlugins()` and `initBundledSkills()` were pulled *out* of `setup.ts` (`setup.ts:289-292`) because `setup()` awaits `startUdsMessaging()` (~20 ms socket bind, `feature('UDS_INBOX')`, absent from snapshot), allowing the concurrent `getCommands(preSetupCwd)` call to race ahead and memoize an empty bundled-skills list.
- **Worktree serialization & transient rejection suppression:** when `--worktree` is enabled, `commandsPromise` and `agentDefsPromise` stay `null` because `setup()` calls `process.chdir(worktreePath)`, changing the directory from which commands and agents must load. The `.catch(() => {})` calls suppress spurious global `unhandledRejection` events during the ~28 ms window before `Promise.all` joins them at `main.tsx:2029`.

Inside [`setup.ts`](../../setup.ts) (`setup.ts:56-477`), six load-bearing invariants execute in strict order:
1. **Runtime & identity prep (`setup.ts:69-158`):** enforces Node >= 18, applies custom `--session-id`, binds the UDS inbox socket *before* `SessionStart` hooks can snapshot `process.env`, captures the teammate-mode snapshot, and—in interactive sessions only—detects and restores interrupted iTerm2 or Terminal.app plist setups.
2. **CWD → Hooks Snapshot → Worktree (`setup.ts:160-285`):** `setCwd(cwd)` must precede `captureHooksConfigSnapshot()` and `initializeFileChangedWatcher(cwd)` so hooks snapshot from the real working directory. If `--worktree` is active, `setup()` checks for either a `WorktreeCreate` hook or git repo, resolves canonical repo root if invoked inside an existing worktree, creates the worktree (and optional `tmux` session), calls `process.chdir()`, updates `setOriginalCwd()` and `setProjectRoot()` (unlike mid-session `EnterWorktreeTool`, `--worktree` makes the worktree the session's project root), clears memory caches (`clearMemoryFileCaches()`), and re-runs `updateHooksConfigSnapshot()` against the worktree's `.claude/settings.json`.
3. **Background registrations & plugin prefetch (`setup.ts:293-370`):** synchronously registers `initSessionMemory()` and `feature('CONTEXT_COLLAPSE')` (`services/contextCollapse/index.js`, absent from snapshot), locks the binary version (`lockCurrentVersion()`), kicks off plugin hook prefetch + hot-reload (skipped when `CLAUDE_CODE_SYNC_PLUGIN_INSTALL` is set in headless mode to avoid racing `copyPluginToVersionedCache`, or under `--bare`), and registers ant undercover repo checks, `COMMIT_ATTRIBUTION` hooks (deferred via `setImmediate` to keep git spawns out of setup microtasks; module absent from snapshot), session file-access hooks, and `feature('TEAMMEM')` watchers.
4. **The `tengu_started` crash-denominator beacon (`setup.ts:371-378`):** `initSinks()` immediately followed by `logEvent('tengu_started', {})`. A comment documents `inc-3694`: a P0 crash inside `checkForReleaseNotes()` (line 387) killed the process before any downstream telemetry fired, hiding the outage from release-health dashboards. Placing `tengu_started` right after sink attachment establishes an honest denominator for session crash rates.
5. **Bypass-permissions safety gate (`setup.ts:396-442`):** if `permissionMode === 'bypassPermissions'` or `allowDangerouslySkipPermissions` is set, POSIX root (`process.getuid() === 0`) is rejected unless `IS_SANDBOX === '1'` or `CLAUDE_CODE_BUBBLEWRAP` is set. For `process.env.USER_TYPE === 'ant'` (exempting `local-agent` and `claude-desktop`), `setup()` also checks `envDynamic.getIsDocker()`, `envDynamic.getIsBubblewrapSandbox()`, and `env.hasInternetAccess()`—refusing to run unless sandboxed *with no internet access*.
6. **Prior-session exit telemetry (`setup.ts:449-476`):** emits `tengu_exit` carrying the *previous* session's persisted cost, durations, token counts, and FPS metrics from `projectConfig` without clearing them (they are still needed for cost restoration on `--resume`).

#### Wave 3 — Non-Interactive Overlap & Post-Render Deferred Prefetches (`main.tsx:388-431, 1952-1990`)

Right after `await setupPromise`, non-interactive (`-p`) sessions immediately call `applyConfigEnvironmentVariables()` (trust is implicit) and kick off `getSystemContext()`, `getUserContext()`, and `ensureModelStringsInitialized()` (overlapping Bedrock's 100–200 ms profile fetch with `commandsPromise`). Interactive sessions instead defer heavy process-spawning prefetches (`initUser`, `getUserContext`, `prefetchSystemContextIfSafe`, `getRelevantTips`, Bedrock/Vertex credential prefetches, `countFilesRoundedRg`, `initializeAnalyticsGates`, `settingsChangeDetector.initialize()`, `skillChangeDetector.initialize()`) into `startDeferredPrefetches()` (`main.tsx:388-431`), which runs *only after* `root.render(element)` in `renderAndRun()` (`interactiveHelpers.tsx:98-103`)—hiding child-process contention behind the user's thinking/typing window and skipping everything under `CLAUDE_CODE_EXIT_AFTER_FIRST_RENDER` or `--bare`.

### Hidden Invariants & Failure Modes

- **Why `--bare` (`CLAUDE_CODE_SIMPLE=1`) acts as a latency scalpel across all waves:** scripted `-p` calls have no "user is typing" window to hide background spawns. Passing `--bare` skips macOS keychain prefetch (`keychainPrefetch.ts:70`), UDS inbox & teammate snapshots (`setup.ts:89-110`), session memory & plugin/attribution/release-notes I/O (`setup.ts:293-393`), claude.ai & auto-discovered MCP configs (`main.tsx:1788,1809`), startup quota/bootstrap prefetches (`main.tsx:2346`), versioned plugin sync (`main.tsx:2555`), and `startDeferredPrefetches()` + `backgroundHousekeeping` (`main.tsx:399,2816`).
- **Cold GrowthBook alias crash-loop guard (`main.tsx:2001-2015`):** for ant builds (`"external" === 'ant'` in this snapshot), an explicit `--model` or `ANTHROPIC_MODEL` with an unpopulated `cachedGrowthBookFeatures['tengu_ant_model_override']` awaits `initializeGrowthBook()` before resolving model aliases—otherwise a cold container pod resolves an internal alias raw, hits a 404, and exits before the async disk cache write lands.

---

## 4. Trust Boundary, Mode Dispatch, and Interactive vs. Headless Handoff

### The Problem

After `setup()` and `commands`/`agents` complete, `main.tsx` faces a stark fork between two worlds:
- **Interactive sessions** run inside a user's terminal on potentially untrusted repositories. They must show onboarding/trust dialogs *before* executing `.claude/settings.json` env vars, LSP servers, `apiKeyHelper`, or `.mcp.json` commands; they must mount Ink (`createRoot`, whose `patchConsole` swallows `console.error`); and they must *never* block first paint on slow MCP servers or ~500 ms `SessionStart` hooks.
- **Headless (`-p` / SDK) sessions** have no terminal UI and treat workspace trust as implicit. They cannot create an Ink root, must materialize configured MCP tools *before* turn 1 (since `-p` is often single-turn), and must hand off an initialized `AppState` store to `cli/print.ts`.

### The Real Implementation

#### The Interactive Trust Gauntlet (`main.tsx:2211-2378`, `interactiveHelpers.tsx:104-298`)

When `!isNonInteractiveSession`, `main.tsx` constructs the Ink root (`createRoot(ctx.renderOptions)`), logs `tengu_timer` (`startup`) *before* any dialog renders—fixing an old bug where logging from REPL's first render measured user dialog-wait time and pushed p99 to ~70s (`main.tsx:2231-2238`)—and runs `showSetupScreens()`:

1. `Onboarding` (if `!config.theme || !config.hasCompletedOnboarding`).
2. `TrustDialog` (unless `CLAUBBIT` is set; fast-paths past dynamic import if `checkHasTrustDialogAccepted()` is already true).
3. **Post-trust unlock (`interactiveHelpers.tsx:144-190`):** marks `setSessionTrustAccepted(true)`, resets and re-initializes GrowthBook with fresh auth headers, prefetches `getSystemContext()`, approves `.mcp.json` servers and `CLAUDE.md` external includes, records the repo path for `--teleport` (`updateGithubRepoPathMapping()`), calls **`applyConfigEnvironmentVariables()`** (applying full project env vars and rebuilding CA/mTLS/proxy agents), and schedules `setImmediate(() => initializeTelemetryAfterTrust())` so OTel's dynamic import resolves after first render.
4. Conditional consent modals: `GroveDialog`, `ApproveApiKey` (for new `ANTHROPIC_API_KEY` outside homespace), `BypassPermissionsModeDialog`, `AutoModeOptInDialog` (`feature('TRANSCRIPT_CLASSIFIER')`), `DevChannelsDialog` (`feature('KAIROS') || feature('KAIROS_CHANNELS')`, blocking on `tengu_harbor` only if disk cache is cold/false to fix `gh#37026`), and `ClaudeInChromeOnboarding`.

Immediately after `showSetupScreens()` returns (and after `validateForceLoginOrg()`), `main.tsx` enforces a critical abort check:

```ts
// main.tsx:2308-2321
// If gracefulShutdown was initiated (e.g., user rejected trust dialog),
// process.exitCode will be set. Skip all subsequent operations that could
// trigger code execution before the process exits (e.g. apiKeyHelper).
if (process.exitCode !== undefined) {
  logForDebugging('Graceful shutdown initiated, skipping further initialization');
  return;
}

// Initialize LSP manager AFTER trust is established (or in non-interactive mode
// where trust is implicit). Prevents plugin LSP servers from executing code
// in untrusted directories before user consent.
initializeLspServerManager();
```

Next come post-trust settings validation (`launchInvalidSettingsDialog`), throttled background API prefetches (`checkQuotaStatus`, `fetchBootstrapData`, `prefetchPassesEligibility`, `prefetchFastModeStatus`—throttled across rapid restarts by GrowthBook `tengu_cicada_nap_ms` while still enforcing fast-mode org policy from cache via `resolveFastModeStatusFromCache()`, `main.tsx:2344-2375`), MCP config resolution (`await mcpConfigPromise`), and versioned plugin initialization (`await`ed in headless mode so sync completes before exit, fire-and-forget in interactive mode, skipped in `--bare`, `main.tsx:2555-2570`).

#### The Three Execution Exits from `main.tsx`

| Mode | Entry Condition (`main.tsx`) | MCP & Hook Strategy | State & Downstream Handoff |
|---|---|---|---|
| **1. `--init-only`** | `main.tsx:2572-2582` | Applies full env; runs `Setup` (`init`) + `SessionStart` (`startup`) with `forceSyncExecution: true` | `gracefulShutdownSync(0)` and return |
| **2. Headless / `-p` / SDK** | `isNonInteractiveSession` (`main.tsx:2585-2861`) | Awaits `connectMcpBatch(regularMcpConfigs)`; deduplicates `plugin:*` vs. `claude.ai` vs. manual `.mcp.json` (`gh-39974`) with a **5s cap** (`CLAUDE_AI_MCP_TIMEOUT_MS`); kicks `sessionStartHooksPromise` early | Creates `headlessStore = createStore(headlessInitialState, onChangeAppState)`, separates `sdkMcpConfigs` (`type === 'sdk'`), lazily imports and invokes `runHeadless(...)` in [`cli/print.ts:455`](../../cli/print.ts) |
| **3. Interactive REPL** | Default fallthrough (`main.tsx:2863-3807`) | **Never awaits** `mcpPromise` or `hooksPromise` before paint; `useManageMCPConnections` converges on memoized `connectToServer`, and `REPL` receives `pendingHookMessages` | Builds `initialState`, increments `numStartups` synchronously, dispatches across 6 flavors (`--continue`, `cc://` Direct Connect, `claude ssh`, `claude assistant` viewer, `--resume`/`--from-pr`/`--teleport`/`--remote`, or fresh session) into `launchRepl()` ([`replLauncher.tsx:12-22`](../../replLauncher.tsx)) → `renderAndRun()` ([`interactiveHelpers.tsx:98-103`](../../interactiveHelpers.tsx)) |

Look at two notable scars in the headless vs. interactive split:
- **The 5-second `claude.ai` MCP cap (`main.tsx:2733-2809`):** making `claude.ai` connectors blocking in `-p` mode fixed single-turn connector visibility, but users with 40+ slow connectors saw `tengu_startup_perf` p99 explode to **76 seconds**. Racing `claudeaiConnect` against `CLAUDE_AI_MCP_TIMEOUT_MS = 5_000` bounds turn-1 startup while letting slow connectors finish into `headlessStore` in the background for turn 2+.
- **Why `launchRepl()` lives in its own 23-line file ([`replLauncher.tsx`](../../replLauncher.tsx)):** it dynamically imports `./components/App.js` and `./screens/REPL.js` only after every setup screen and session-resolution branch completes, keeping the entire React REPL component tree off the `main.tsx` static import graph for subcommands and `-p` runs.

### Hidden Invariants & Failure Modes

- **Early trust gate for `KAIROS` assistant mode (`main.tsx:1043-1089`):** `.claude/settings.json` can declare `assistant: true` and append `.claude/agents/assistant.md` ~1,000 lines *before* `showSetupScreens()` runs. Therefore the `KAIROS` block checks `checkHasTrustDialogAccepted()` itself and refuses to activate in untrusted directories (and skips re-initializing the team when `--agent-id` indicates the process is already a spawned teammate).
- **Double `SessionStart` hook prevention on resume (`main.tsx:2432-2440`):** `hooksPromise` is explicitly `null` when `options.continue || options.resume` is set, because `conversationRecovery.ts` fires `'resume'` hooks; firing `'startup'` too caused hooks to run twice and clobber the first system message (`gh-30825`).
- **Preserving `type: 'sdk'` MCP entries (`main.tsx:1493-1503`):** the Python Agent SDK passes SDK-hosted MCP servers via `--mcp-config` rather than the `initialize` control message. Dropping `type: 'sdk'` during dynamic config parsing broke Coworker (`inc-5122`), so `main.tsx` preserves them through policy filtering and extracts them into `sdkMcpConfigs` for `runHeadless()`.

---

## 5. Bulletproof Teardown: `cleanupRegistry.ts` and `gracefulShutdown.ts`

### The Problem

Shutting down a terminal agent cleanly is an adversarial distributed-systems problem disguised as process exit:
- 25+ subsystems (`config.ts`, `sessionStorage.ts`, `mcp/client.ts`, `lsp/manager.ts`, `settings/changeDetector.ts`, `telemetry/instrumentation.ts`, `swarm/teamHelpers.ts`, etc.) must flush state or reap children—without creating circular imports with `gracefulShutdown.ts`.
- Under Bun, any short-lived `signal-exit` v4 subscriber (like `execa` finishing a child command) calling `removeListener` resets the kernel `sigaction`, silently nuking Claude Code's `SIGTERM` handler!
- On macOS, closing a terminal window often revokes the TTY file descriptors *without* delivering `SIGHUP`, stranding an orphaned process forever; and when a PTY *is* dead, `process.exit()` itself can throw `EIO` trying to flush stdout.
- Unmounting Ink at the wrong moment sends a duplicate `EXIT_ALT_SCREEN` (`1049l` / `DECRC`) *after* `claude --resume <id>` is printed, jumping the cursor backwards and clobbering the resume hint.

### The Real Implementation

First, [`utils/cleanupRegistry.ts`](../../utils/cleanupRegistry.ts) isolates the registration surface in a 25-line, zero-dependency leaf module (`const cleanupFunctions = new Set<() => Promise<void>>()`), returning an unregister thunk from `registerCleanup(fn)` and running all registered hooks concurrently via `runCleanupFunctions()`.

Second, `setupGracefulShutdown()` ([`utils/gracefulShutdown.ts:237-334`](../../utils/gracefulShutdown.ts)) installs process-wide survival armor once via `memoize`:

```ts
// utils/gracefulShutdown.ts:237-297 (abridged)
export const setupGracefulShutdown = memoize(() => {
  // Pin signal-exit v4 so its emitter count stays > 0 and v4.unload() never
  // calls removeListener — working around a Bun bug where removeListener
  // resets the kernel sigaction even when other JS listeners remain.
  onExit(() => {})

  process.on('SIGINT', () => {
    if (process.argv.includes('-p') || process.argv.includes('--print')) return
    logForDiagnosticsNoPII('info', 'shutdown_signal', { signal: 'SIGINT' })
    void gracefulShutdown(0)
  })
  process.on('SIGTERM', () => { void gracefulShutdown(143) })
  if (process.platform !== 'win32') {
    process.on('SIGHUP', () => { void gracefulShutdown(129) })
    if (process.stdin.isTTY) {
      orphanCheckInterval = setInterval(() => {
        if (getIsScrollDraining()) return // Never steal a scroll frame
        if (!process.stdout.writable || !process.stdin.readable) {
          clearInterval(orphanCheckInterval)
          void gracefulShutdown(129)
        }
      }, 30_000)
      orphanCheckInterval.unref()
    }
  }
  // Plus uncaughtException & unhandledRejection analytics/diagnostics listeners
})
```

Third, `gracefulShutdown()` ([`utils/gracefulShutdown.ts:391-523`](../../utils/gracefulShutdown.ts)) executes a strictly ordered, budget-bounded teardown pipeline:

1. **Re-entrancy latch & scaled failsafe timer (`gracefulShutdown.ts:401-429`):** if `shutdownInProgress` is already true, return immediately. Otherwise resolve `sessionEndTimeoutMs = getSessionEndHookTimeoutMs()` *before* arming the `.unref()`'d failsafe timer at `Math.max(5000, sessionEndTimeoutMs + 3500)`—fixing `gh-32712`, where a hardcoded 5-second failsafe silently truncated user-configured 10-second `SessionEnd` hooks.
2. **Synchronous terminal restoration & resume hint FIRST (`gracefulShutdown.ts:59-185, 431-438`):** runs *before* any async I/O so even a `SIGKILL` during macOS reboot leaves a usable terminal and visible resume command. Inside `cleanupTerminalModes()`, exact ordering matters:
   - `writeSync(1, DISABLE_MOUSE_TRACKING)` **first**, giving the terminal a round-trip to stop sending mouse bytes while React unmounts.
   - If `inst?.isAltScreenActive`, call `inst.unmount()` directly (falling back to `writeSync(1, EXIT_ALT_SCREEN)` only if unmount throws). Unmounting while `altScreenActive` is true keeps the final render on the alt buffer, unsubscribes Ink from `signal-exit`, and writes `1049l` exactly once.
   - `inst?.drainStdin()` then `inst?.detachForShutdown()` so deferred `signal-exit` handlers cannot emit redundant `EXIT_ALT_SCREEN` sequences after `printResumeHint()`.
   - Unconditionally `writeSync(1, ...)` `DISABLE_MODIFY_OTHER_KEYS`, `DISABLE_KITTY_KEYBOARD`, `DFE` (focus events), `DBP` (bracketed paste), `SHOW_CURSOR`, `CLEAR_ITERM2_PROGRESS`, optional `CLEAR_TAB_STATUS`, and `CLEAR_TERMINAL_TITLE` (respecting `CLAUDE_CODE_DISABLE_TERMINAL_TITLE`).
   - `printResumeHint()` prints `\nResume this session with:\nclaude --resume <title-or-id>\n` at most once (`resumeHintPrinted`) when TTY + interactive + session file exists.
3. **Phase 1 — Registered cleanups, capped at 2,000 ms (`gracefulShutdown.ts:439-467`):** races `runCleanupFunctions()` against a 2-second timeout. Running this *before* hooks and analytics guarantees session JSONL flush + `reAppendSessionMetadata()` ([`utils/sessionStorage.ts:449-462`](../../utils/sessionStorage.ts)—which re-appends custom titles into the last 64 KB tail window so `--resume` never loses `/rename`) completes even if the network or TTY is dead.
4. **Phase 2 — `SessionEnd` hooks, capped at `sessionEndTimeoutMs` (`gracefulShutdown.ts:469-480`):** default 1.5s, configurable via `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS`, bounded with `AbortSignal.timeout(sessionEndTimeoutMs)`.
5. **Phase 3 — `profileReport()` + `tengu_cache_eviction_hint` (`gracefulShutdown.ts:482-499`):** emits startup perf telemetry and signals inference (via `getLastMainRequestId()`) that this session's prompt cache can be evicted—both *before* analytics shutdown drains the queue.
6. **Phase 4 — Analytics flush, capped at 500 ms (`gracefulShutdown.ts:501-511`):** races `Promise.all([shutdown1PEventLogging(), shutdownDatadog()])` against `sleep(500)`. Previously unbounded, the 1P exporter awaited 10-second axios POSTs on stalled networks; losing late telemetry is acceptable, hanging exit is not.
7. **`forceExit(exitCode)` (`gracefulShutdown.ts:193-232`):** clears the failsafe timer, calls `instances.get(process.stdout)?.drainStdin()` one last time (using the Ink instance method so `/dev/tty` overrides are drained even when `process.stdin` was piped!), calls `process.exit(exitCode)`, and on `EIO` from a dead PTY falls back to `process.kill(process.pid, 'SIGKILL')`.

### Hidden Invariants & Failure Modes

- **Why `gracefulShutdownSync()` sets `process.exitCode` immediately (`gracefulShutdown.ts:344-359`):** `gracefulShutdownSync()` launches the async shutdown without awaiting it, but assigns `process.exitCode = exitCode` synchronously first. That single assignment is the contract `main.tsx:2312` checks right after `showSetupScreens()` to stop initialization dead in its tracks when a user rejects the trust dialog.
- **Dual `SIGINT` listener coordination (`main.tsx:598-606` vs. `gracefulShutdown.ts:256-267`):** `main.tsx` installs an early `SIGINT` listener (`process.exit(0)`) before `init()` runs so Ctrl+C works during pre-`init()` parsing, and both listeners explicitly `return` when `-p`/`--print` is in `process.argv` so [`cli/print.ts`](../../cli/print.ts) can abort in-flight queries and shut down cleanly without racing.

---

## Putting the Layer Together

The startup and shutdown architecture forms a single funnel: fast-paths peel off early in `cli.tsx`, normal executions overlap I/O across four waves into `init()` and `setup()`, branch sharply across the workspace trust boundary, and reconverge on `gracefulShutdown()`:

```mermaid
flowchart TD
    A["entrypoints/cli.tsx (1 static import: feature)"] --> B{"--version / -v / -V?"}
    B -->|"Yes"| Z1["Print MACRO.VERSION & return (0 imports)"]
    B -->|"No"| C{"Fast-path flag or subcommand? (MCP, bridge, daemon, bg, tmux...)"}
    C -->|"Yes"| Z2["Dynamic import & run isolated handler"]
    C -->|"No"| D["--bare -> SIMPLE=1; startCapturingEarlyInput()"]
    D --> E["Wave 0: main.tsx top-level startMdmRawRead() + startKeychainPrefetch()"]
    E --> F["main.tsx imports (~135ms) + main() argv rewrite + eagerLoadSettings()"]
    F --> G["Commander preAction: await MDM + Keychain -> await init() -> runMigrations()"]
    G --> H["init.ts: enableConfigs -> safeEnv -> CA certs -> signals -> mTLS/proxy -> preconnectAnthropicApi()"]
    H --> I["Wave 2: parallel setup() + getCommands() + getAgentDefinitionsWithOverrides() + mcpConfigPromise"]
    I --> J{"Execution Mode?"}
    J -->|"init-only"| K1["Sync Setup + SessionStart hooks -> gracefulShutdownSync(0)"]
    J -->|"Headless (-p / SDK / non-TTY)"| K2["applyConfigEnv -> headlessStore -> connectMcpBatch (5s claude.ai cap) -> runHeadless()"]
    J -->|"Interactive TTY"| K3["createRoot() -> showSetupScreens() -> TrustDialog -> applyConfigEnv -> launchRepl()"]
    K2 --> L["gracefulShutdown(): sync terminal reset + resume hint -> 2s cleanups -> SessionEnd -> 500ms analytics -> forceExit()"]
    K3 --> L
```

Zooming in on the **parallel overlap windows** that keep cold start fast:

```text
Stage A: Import Overlap (cli.tsx -> main.tsx preAction)
cli.tsx : [earlyInput]
Wave 0  : |--plutil / reg query (MDM)------|
        : |--security (OAuth + API key)----|
Imports : |======= main.tsx static imports (~135ms) =======|
preAct  :                                                  [join ~0ms]->init()

Stage B: Post-init() Overlap (init.ts -> Fork -> First Paint)
init()  : |-cfg->env->CA->sig->proxy-|
Preconn :                            |--TCP+TLS HEAD (~100-200ms)----|
Wave 2  :                            |--setup() (UDS/hooks/worktree)-|
        :                            |--getCommands() + getAgents()--|
        :                            |--mcpConfigPromise (file read)-|
Fork    :                                                            |-UI/-p-|
PostPnt :                                                              |-def-|
```

---

## How This Snaps Into the Next Layer

Every interactive session exiting `main.tsx` converges on `launchRepl()` ([`replLauncher.tsx:12-22`](../../replLauncher.tsx)) and the React/Ink REPL already dissected in [Chapter 21](21-the-interactive-repl-screens-keybindings-and-vim.md). Every non-interactive and Agent SDK session exits through two concrete handoffs that open **[Chapter 23 — Machine-Readable Modes: Headless CLI, Agent SDK, and Control Protocols](23-machine-readable-modes-headless-sdk-and-control-protocols.md)**:

1. **Headless & SDK execution (`main.tsx:2825-2860` → [`cli/print.ts:455`](../../cli/print.ts)):** `main.tsx` dynamically imports `runHeadless()` and hands it `inputPrompt` (either a string or the live `process.stdin` `AsyncIterable` when `--input-format=stream-json`), `headlessStore.getState`/`setState`, filtered `commandsHeadless`, `tools`, `sdkMcpConfigs`, `agentDefinitions.activeAgents`, and the already-in-flight `sessionStartHooksPromise`. Inside `cli/print.ts`, `StructuredIO` and `RemoteIO` take over NDJSON framing, stdout guarding, and SDK control-protocol round-trips.
2. **MCP server mode (`main.tsx:3894-3909` → `cli/handlers/mcp.ts` → `entrypoints/mcp.ts`):** `claude mcp serve` bypasses the default action and exposes Claude Code's own tool loop as an MCP server.

Finally, the remote and bridge branches that `cli.tsx` (`remote-control` → `bridge/bridgeMain.ts`), `init.ts` (`upstreamproxy/upstreamproxy.ts`), and `main.tsx` (`DIRECT_CONNECT`, `--remote`, `--teleport`, `--rc`) prepared will be unpacked end-to-end in [Chapter 24](24-across-the-wire-remote-sessions-bridge-and-direct-connect.md).

---

## Reading Exercises & Code Checkpoints

1. **Trace every `--bare` latency cut across the startup path:**
   Run:
   ```sh
   rg -n "isBareMode|CLAUDE_CODE_SIMPLE" entrypoints/cli.tsx main.tsx setup.ts utils/secureStorage/keychainPrefetch.ts
   ```
   Verify which subsystems `--bare` bypasses at module-eval time versus inside `setup()` versus inside `main.tsx`, and explain why `setup.ts:334-335` refuses to early-return out of `setup()` under `--bare`.

2. **Audit every checkpoint feeding `tengu_startup_perf`:**
   Run:
   ```sh
   rg -n "profileCheckpoint\(" entrypoints/ main.tsx setup.ts
   ```
   Match the checkpoint names against `PHASE_DEFINITIONS` in [`utils/startupProfiler.ts:49-54`](../../utils/startupProfiler.ts). Which checkpoint is missing if a user passes `--help`, and why does `init_time` stay undefined in that case?

3. **Verify the trust-boundary invariant on environment variables and CA certs:**
   Read [`utils/managedEnv.ts:93-199`](../../utils/managedEnv.ts) alongside [`utils/caCertsConfig.ts:34-88`](../../utils/caCertsConfig.ts). Identify exactly which config sources can set `ANTHROPIC_BASE_URL` and `NODE_EXTRA_CA_CERTS` *before* `TrustDialog` runs, and trace how `applyConfigEnvironmentVariables()` invalidates cached TLS/proxy state after trust is granted.

4. **Inspect the distributed cleanup registry:**
   Run:
   ```sh
   rg -n "registerCleanup\(" entrypoints/ utils/ services/ main.tsx
   ```
   Pick three callers (including [`utils/sessionStorage.ts:448-464`](../../utils/sessionStorage.ts)) and trace what happens if one cleanup hangs for 10 seconds during `gracefulShutdown()` while `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` is set to `8000`. What are the exact timeout budgets for Phase 1, Phase 2, Phase 4, and the outer failsafe timer?


---

<!-- chapters/23-machine-readable-modes-headless-sdk-and-control-protocols.md — https://reverseengineeringclaudecode.com/chapters/23-machine-readable-modes-headless-sdk-and-control-protocols -->

# Chapter 23 — Machine-Readable Modes: Headless CLI, Agent SDK, and Control Protocols

> **Layer:** Layer 8 (Entrypoints, Startup, SDK & Remote Control)
> **Prerequisites:** [Chapter 08](08-session-envelope-query-engine-and-transcripts.md), [Chapter 11](11-the-permission-engine.md), [Chapter 15](15-model-context-protocol-mcp.md), [Chapter 22](22-cold-start-mastery-cli-init-main.md)
> **Primary Source Files:**
> - [cli/print.ts](../../cli/print.ts) — headless runner (`runHeadless`), full-duplex streaming engine (`runHeadlessStreaming`), control-request dispatcher, and resume/replay orchestration
> - [cli/structuredIO.ts](../../cli/structuredIO.ts) — NDJSON line framer, bidirectional RPC multiplexer (`StructuredIO`), and permission/hook/elicitation/SDK-MCP bridges
> - [cli/ndjsonSafeStringify.ts](../../cli/ndjsonSafeStringify.ts) — ECMA-262 `U+2028`/`U+2029` line-terminator sanitizer for NDJSON wire framing
> - [utils/streamJsonStdoutGuard.ts](../../utils/streamJsonStdoutGuard.ts) — runtime `process.stdout.write` interceptor diverting stray non-JSON output to `stderr`
> - [entrypoints/agentSdkTypes.ts](../../entrypoints/agentSdkTypes.ts) — public Agent SDK surface declarations and re-export hub
> - [entrypoints/sdk/coreSchemas.ts](../../entrypoints/sdk/coreSchemas.ts) & [entrypoints/sdk/coreTypes.ts](../../entrypoints/sdk/coreTypes.ts) — Zod single source of truth for serializable `SDKMessage` wire types
> - [entrypoints/sdk/controlSchemas.ts](../../entrypoints/sdk/controlSchemas.ts) — Zod schemas for bidirectional `control_request` / `control_response` envelopes
> - [entrypoints/mcp.ts](../../entrypoints/mcp.ts) — inverted entrypoint exposing built-in tools as an MCP stdio server (`claude mcp serve`)
> - [services/mcp/SdkControlTransport.ts](../../services/mcp/SdkControlTransport.ts) — MCP transport tunneling JSON-RPC over `mcp_message` control frames
> - [cli/remoteIO.ts](../../cli/remoteIO.ts) — `StructuredIO` subclass bridging the control protocol onto remote WebSocket/SSE transports

---

## Why This Layer Exists

In [Chapter 22](22-cold-start-mastery-cli-init-main.md), `main.tsx` finishes startup and hits a fork in the road. Interactive users mount the Ink React tree (`screens/REPL.tsx`), where a human watches ANSI spinners, hits Shift+Tab to toggle permission modes, and clicks through permission dialogs. Non-interactive callers have none of that—no TTY, no React tree, no modal UI, and often another program sitting on both ends of `stdin` and `stdout`.

Those programmatic consumers span four very different workloads:

1. **One-shot shell pipes** (`git diff | claude -p "summarize"`), expecting plain text and a clean exit code.
2. **Structured batch automation** (`-p --output-format=json --json-schema=...`), expecting a single machine-validated JSON payload.
3. **Full-duplex Agent SDK hosts** (the TypeScript and Python SDKs, VS Code, Desktop, and CI orchestrators) spawning Claude Code as a long-lived child process with `--input-format=stream-json --output-format=stream-json --verbose`, exchanging multi-turn prompts, partial token streams, mid-turn permission prompts, host-side hooks, and in-process MCP tool calls over one pair of pipes.
4. **Inverted tool hosting** (`claude mcp serve`), where another agent owns the LLM loop and wants to call Claude Code's workspace tools over standard MCP JSON-RPC.

The architectural insight of this layer is that **workloads 1, 2, and 3 share a single streaming engine**: `runHeadlessStreaming()` driven by `StructuredIO`. A plain string passed to `-p` is wrapped into a one-element `AsyncIterable` containing one JSON `user` line (`getStructuredIO` in [cli/print.ts](../../cli/print.ts)), then executed through the exact same pipeline as a multi-hour bidirectional SDK session. Only workload 4 steps outside `QueryEngine` entirely, mounting `getTools()` directly onto an MCP server.

We build this layer from the bytes up: wire hygiene first, then wire schemas, then full-duplex RPC multiplexing, then the headless coordinator in `cli/print.ts`, and finally the inverted MCP server.

---

## 1. The Wire Discipline: Keeping `stdout` Pure NDJSON

### The Problem

When `--output-format=stream-json` is active, file descriptor 1 (`stdout`) is no longer a human terminal—it is a framed binary-adjacent RPC channel parsed line-by-line as NDJSON by the parent SDK process. Two production failure modes routinely destroy NDJSON streams in Node/Bun applications:

1. **Unicode line-terminator truncation (`gh-28405`):** `JSON.stringify` emits raw `U+2028` (LINE SEPARATOR) and `U+2029` (PARAGRAPH SEPARATOR) inside strings, which is legal JSON per ECMA-404. Any receiver that splits lines using JavaScript line-terminator semantics (ECMA-262 §11.3: `\n`, `\r`, `U+2028`, `U+2029`) slices the JSON object in half mid-string. Even if the receiver skips malformed lines instead of crashing, the message is silently lost.
2. **Stray `stdout` writes:** A single stray `console.log`, third-party library startup banner, or forgotten debug print anywhere in ~1,900 source files or `node_modules` lands on `stdout` mid-stream and breaks the SDK client's JSON parser with no recovery path.

### The Real Implementation

Two small, surgical modules eliminate both failure classes. First, every NDJSON serializer routes through `ndjsonSafeStringify()` instead of raw `JSON.stringify`:

```ts
// cli/ndjsonSafeStringify.ts:16-32
const JS_LINE_TERMINATORS = /\u2028|\u2029/g

function escapeJsLineTerminators(json: string): string {
  return json.replace(JS_LINE_TERMINATORS, c =>
    c === '\u2028' ? '\\u2028' : '\\u2029',
  )
}

export function ndjsonSafeStringify(value: unknown): string {
  return escapeJsLineTerminators(jsonStringify(value))
}
```

A single alternating regex avoids scanning large serialized tool outputs twice; the `\u2028`/`\u2029` escape sequences parse back to identical strings under every JSON parser while being invisible to every line splitter.

Second, before `runHeadless()` emits a single message in `stream-json` mode ([cli/print.ts](../../cli/print.ts):594–596), it installs a runtime gate on `process.stdout.write`:

```ts
// utils/streamJsonStdoutGuard.ts:59-91
process.stdout.write = function (
  chunk: string | Uint8Array,
  encodingOrCb?: BufferEncoding | ((err?: Error) => void),
  cb?: (err?: Error) => void,
): boolean {
  const text =
    typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf-8')

  buffer += text
  let newlineIdx: number
  let wrote = true
  while ((newlineIdx = buffer.indexOf('\n')) !== -1) {
    const line = buffer.slice(0, newlineIdx)
    buffer = buffer.slice(newlineIdx + 1)
    if (isJsonLine(line)) {
      wrote = originalWrite!(line + '\n')
    } else {
      process.stderr.write(`${STDOUT_GUARD_MARKER} ${line}\n`)
      logForDebugging(
        `streamJsonStdoutGuard diverted non-JSON stdout line: ${line.slice(0, 200)}`,
      )
    }
  }

  const callback = typeof encodingOrCb === 'function' ? encodingOrCb : cb
  if (callback) {
    queueMicrotask(() => callback())
  }
  return wrote
} as typeof process.stdout.write
```

`isJsonLine()` ([utils/streamJsonStdoutGuard.ts](../../utils/streamJsonStdoutGuard.ts):14–26) treats empty lines as valid (blank separators are tolerated in NDJSON) and tests every non-empty complete line with `JSON.parse(line)`. Anything that fails to parse is diverted to `stderr` prefixed with `STDOUT_GUARD_MARKER` (`'[stdout-guard]'`) so it stays debuggable in logs without poisoning the wire.

### Hidden Invariants & Failure Modes

- **Shutdown flush:** `installStreamJsonStdoutGuard()` registers a cleanup hook via `registerCleanup()` ([utils/streamJsonStdoutGuard.ts](../../utils/streamJsonStdoutGuard.ts):93–109). Any partial line sitting in `buffer` at exit without a trailing `\n` is flushed to `stdout` if valid JSON, or diverted to `stderr` with `[stdout-guard]` if it is a fragment, before restoring `originalWrite`.
- **Callback liveness:** Notice lines 86–89: even when a write is diverted to `stderr`, the caller's completion callback still fires via `queueMicrotask(() => callback())`. Skipping the callback would deadlock callers awaiting stream drain.
- **One extra `JSON.parse` per frame:** The blessed path (`structuredIO.write` → `writeToStdout` → `process.stdout.write`) always emits `ndjsonSafeStringify(msg) + '\n'`, so it passes straight through—at the deliberate cost of one `JSON.parse` validation pass per outbound message in `stream-json` mode.
- **Non-TTY `stdin` hygiene ([main.tsx](../../main.tsx):857–883):** On the input side, `getInputPrompt()` guards against two classic pipe traps. First, it checks `!process.argv.includes('mcp')` before touching `process.stdin`—reading stdin during startup would steal bytes from MCP's JSON-RPC framing. Second, in `text` input mode with a non-TTY `stdin`, it waits at most 3 seconds via `peekForStdinData(process.stdin, 3000)` before warning on `stderr` and proceeding, preventing silent hangs when a parent spawns Claude Code with an inherited, open, silent pipe.

---

## 2. Schema-First Contracts and the Snapshot Boundary

### The Problem

At least five independent codebases consume Claude Code's NDJSON wire format: the CLI itself, the TypeScript Agent SDK (`@anthropic-ai/claude-agent-sdk`), the Python SDK, the VS Code extension, and the `claude.ai` remote bridge. Hand-maintaining duplicate type declarations and runtime validators across those boundaries guarantees schema drift—especially across 24+ message types and 20+ control request subtypes.

### The Real Implementation

The repository treats Zod v4 schemas in `entrypoints/sdk/` as the **single source of truth**:

- [entrypoints/sdk/coreSchemas.ts](../../entrypoints/sdk/coreSchemas.ts) (1,889 lines) defines every serializable SDK data type (`ModelUsageSchema`, `PermissionUpdateSchema`, `PermissionResultSchema`, `HookInputSchema`, `SDKResultSuccessSchema`, `SDKResultErrorSchema`, `SDKSystemMessageSchema`, `SDKPartialAssistantMessageSchema`, `SDKSessionStateChangedMessageSchema`, and the 24-variant `SDKMessageSchema` union at lines 1854–1881). Every schema is wrapped in `lazySchema()` ([Chapter 01](01-atoms-types-stores-and-primitives.md)) so importing schema modules incurs zero startup allocation.
- [entrypoints/sdk/controlSchemas.ts](../../entrypoints/sdk/controlSchemas.ts) (663 lines) defines the bidirectional control protocol layered on top of `coreSchemas.ts`, culminating in the two aggregate wire schemas:

```ts
// entrypoints/sdk/controlSchemas.ts:642-663
export const StdoutMessageSchema = lazySchema(() =>
  z.union([
    SDKMessageSchema(),
    SDKStreamlinedTextMessageSchema(),
    SDKStreamlinedToolUseSummaryMessageSchema(),
    SDKPostTurnSummaryMessageSchema(),
    SDKControlResponseSchema(),
    SDKControlRequestSchema(),
    SDKControlCancelRequestSchema(),
    SDKKeepAliveMessageSchema(),
  ]),
)

export const StdinMessageSchema = lazySchema(() =>
  z.union([
    SDKUserMessageSchema(),
    SDKControlRequestSchema(),
    SDKControlResponseSchema(),
    SDKKeepAliveMessageSchema(),
    SDKUpdateEnvironmentVariablesMessageSchema(),
  ]),
)
```

- [entrypoints/sdk/coreTypes.ts](../../entrypoints/sdk/coreTypes.ts) re-exports generated TypeScript types derived from `coreSchemas.ts` via `bun scripts/generate-sdk-types.ts`, alongside runtime `const` arrays (`HOOK_EVENTS`—27 lifecycle events—and `EXIT_REASONS`).
- [entrypoints/agentSdkTypes.ts](../../entrypoints/agentSdkTypes.ts) is the public SDK declaration barrel: it re-exports core types, runtime callback interfaces, generated settings types, tool types, and `@alpha` control types (`SDKControlRequest`, `SDKControlResponse`). Its exported functions (`query()`, `tool()`, `createSdkMcpServer()`, the `@alpha` V2 session API `unstable_v2_createSession`/`resumeSession`/`prompt`, transcript utilities like `listSessions`/`forkSession`, and `@internal` daemon helpers `watchScheduledTasks`/`connectRemoteControl`) all throw `'not implemented'` stubs here—this file is the type-checked contract against which the external SDK package is built and published.

> [!NOTE]
> **Snapshot Absences in `entrypoints/sdk/`:** This source checkout contains `coreSchemas.ts`, `controlSchemas.ts`, `coreTypes.ts`, `entrypoints/agentSdkTypes.ts`, and `entrypoints/sandboxTypes.ts`, but **six imported sibling modules are absent from the snapshot**:
> - `entrypoints/sdk/coreTypes.generated.ts` (generated from `coreSchemas.ts`)
> - `entrypoints/sdk/controlTypes.ts` (TypeScript types corresponding to `controlSchemas.ts`)
> - `entrypoints/sdk/runtimeTypes.ts` (non-serializable SDK callback and `Query`/`SDKSession` interfaces)
> - `entrypoints/sdk/settingsTypes.generated.ts` (generated from settings JSON schema)
> - `entrypoints/sdk/toolTypes.ts` (`@internal` per-tool input/output types)
> - `entrypoints/sdk/sdkUtilityTypes.ts` (`NonNullableUsage`)
>
> Because `coreSchemas.ts` and `controlSchemas.ts` *are* present in full, every serializable wire type is directly inspectable, and the missing runtime/control TypeScript interfaces are unambiguously observed at call sites in `cli/structuredIO.ts`, `cli/print.ts`, and `entrypoints/agentSdkTypes.ts`.

### Hidden Invariants & Failure Modes

- **A second hidden code generator (Zod → Protobuf):** Look at the comment on `SDKControlGetSettingsResponseSchema` in [entrypoints/sdk/controlSchemas.ts](../../entrypoints/sdk/controlSchemas.ts):506–510:
  `// String levels only — numeric effort is ant-only and the Zod→proto generator can't emit enum∪number unions.`
  The Zod schemas aren't only generating TypeScript `.d.ts` files; they also feed a Protobuf generator for web/mobile clients, constraining schema authors away from heterogeneous unions.
- **`StdinMessageSchema` vs. runtime `processLine()`:** While `StdinMessageSchema` lists five inbound message types, `StructuredIO.processLine()` ([cli/structuredIO.ts](../../cli/structuredIO.ts):431–450) also accepts `assistant` and `system` messages on `stdin` so the remote bridge can inject prior conversation history directly into `mutableMessages` during replay (`cli/print.ts:4042–4052`).
- **Internal control subtypes beyond `controlSchemas.ts`:** `controlSchemas.ts` specifies 21 public/builder `SDKControlRequestInnerSchema` subtypes, while `cli/print.ts` dispatches additional internal/IDE subtypes (`end_session`, `channel_enable`, `mcp_authenticate`, `mcp_oauth_callback_url`, `claude_authenticate`, `claude_oauth_callback`, `claude_oauth_wait_for_completion`, `mcp_clear_auth`, `generate_session_title`, `side_question`, `set_proactive`, `remote_control`). Any unknown subtype gets an explicit `control_response` error ([cli/print.ts](../../cli/print.ts):4021–4028) so callers never hang waiting for an unrecognized request.

---

## 3. `StructuredIO`: Full-Duplex RPC Multiplexing Over `stdin`/`stdout`

### The Problem

A single pair of unidirectional pipes (`stdin` in, `stdout` out) has to carry two asymmetric protocols simultaneously:

1. **Event streaming:** User turns flow in; `assistant` messages, `stream_event` deltas, `tool_progress`, `system` events, and `result` summaries flow out.
2. **Bidirectional RPC:**
   - **Host → CLI:** The host sends `control_request` frames (`initialize`, `interrupt`, `set_model`, `set_permission_mode`, `rewind_files`, etc.) and awaits matching `control_response` frames—even *while* a turn is blocked mid-tool.
   - **CLI → Host:** Mid-turn, Claude Code sends blocking `control_request` frames (`can_use_tool`, `hook_callback`, `mcp_message`, `elicitation`) and must park the calling tool coroutine until a `control_response` with the matching `request_id` arrives on `stdin`—even while other concurrent tools are also blocked on their own prompts.

Without careful framing, two nasty bugs appear immediately:
- **Reordering:** If `sendRequest()` writes directly to `stdout` while `print.ts` drains `QueryEngine` through a separate queue, a `can_use_tool` permission prompt can overtake the `assistant` message that announced the `tool_use` block, confusing host UIs.
- **Duplicate / orphaned `control_response` corruption:** If a WebSocket reconnect or worker restart redelivers an already-handled `can_use_tool` response after its `pendingRequests` entry was removed, treating it as a new orphaned approval re-executes the tool and appends duplicate `tool_use` IDs into `mutableMessages`—causing an unrecoverable Anthropic API `400 "tool_use ids must be unique"` error.

### The Real Implementation

`StructuredIO` ([cli/structuredIO.ts](../../cli/structuredIO.ts):135–774) solves multiplexing with four interlocking primitives.

#### 1. One Shared Outbound FIFO (`outbound: Stream<StdoutMessage>`)

```ts
// cli/structuredIO.ts:160-162
// sendRequest() and print.ts both enqueue here; the drain loop is the
// only writer. Prevents control_request from overtaking queued stream_events.
readonly outbound = new Stream<StdoutMessage>()
```

`Stream<T>` ([utils/stream.ts](../../utils/stream.ts):1–76) is a minimal single-consumer async FIFO queue (`enqueue()`, `done()`, `error()`). Both `StructuredIO.sendRequest()` and `runHeadlessStreaming()` enqueue into `structuredIO.outbound`, and `runHeadless()`'s outer `for await` loop is the *only* code that calls `structuredIO.write()`. Every `stream_event`, `assistant` frame, `control_request`, and `control_response` hits `stdout` in strict causal order.

#### 2. Line Framing, `prependedLines`, and Inline Response Interception

`StructuredIO.read()` ([cli/structuredIO.ts](../../cli/structuredIO.ts):215–261) splits chunks from `this.input` on `\n`, calling `processLine()` on each line. Notice the subtle `prependedLines` mechanism (`cli/structuredIO.ts:204–242`): `SessionStart` hooks (`takeInitialUserMessage()`) and SDK-defined `--agent` `initialPrompt` values can call `structuredIO.prependUserMessage(text)` before iteration starts *or mid-stream*. `splitAndProcess()` checks `this.prependedLines` on every iteration of its inner `for (;;)` loop, so a prepended turn lands ahead of the next message even when two messages arrived in the same read buffer. When `this.input` reaches EOF, `read()` sets `this.inputClosed = true` and rejects every promise still waiting in `this.pendingRequests` with `'Tool permission stream closed before response received'`.

Inside `processLine()` ([cli/structuredIO.ts](../../cli/structuredIO.ts):333–463), incoming frames are classified *before* yielding to `cli/print.ts`:

```ts
// cli/structuredIO.ts:341-429 (abridged for clarity)
const message = normalizeControlMessageKeys(jsonParse(line)) as
  | StdinMessage
  | SDKMessage
if (message.type === 'keep_alive') {
  return undefined
}
if (message.type === 'update_environment_variables') {
  for (const [key, value] of Object.entries(message.variables)) {
    process.env[key] = value
  }
  return undefined
}
if (message.type === 'control_response') {
  // ... notifyCommandLifecycle(uuid, 'completed') ...
  const request = this.pendingRequests.get(message.response.request_id)
  if (!request) {
    const responsePayload =
      message.response.subtype === 'success'
        ? message.response.response
        : undefined
    const toolUseID = responsePayload?.toolUseID
    if (
      typeof toolUseID === 'string' &&
      this.resolvedToolUseIds.has(toolUseID)
    ) {
      return undefined // Duplicate delivery — do not re-process as orphan!
    }
    if (this.unexpectedResponseCallback) {
      await this.unexpectedResponseCallback(message)
    }
    return undefined
  }
  this.trackResolvedToolUseId(request.request)
  this.pendingRequests.delete(message.response.request_id)
  if (
    request.request.request.subtype === 'can_use_tool' &&
    this.onControlRequestResolved
  ) {
    this.onControlRequestResolved(message.response.request_id)
  }
  if (message.response.subtype === 'error') {
    request.reject(new Error(message.response.error))
    return undefined
  }
  // Zod-validate response payload against request.schema, then resolve
  // Yield message only if this.replayUserMessages is enabled
}
```

Two real battle scars sit right at the top of `processLine()`:
- **`normalizeControlMessageKeys()` ([utils/controlMessageCompat.ts](../../utils/controlMessageCompat.ts):13–32):** Older iOS app builds lacked a Swift `CodingKeys` mapping and emitted camelCase `requestId` instead of snake_case `request_id` on both top-level control requests and nested `response` objects. Without this in-place normalizer, `structuredIO.ts` read `message.response.request_id` as `undefined` and silently dropped mobile permission approvals.
- **`update_environment_variables`:** Mutates `process.env` directly inside the CLI process—not just child shells—because bridge session runners use it to rotate `CLAUDE_CODE_SESSION_ACCESS_TOKEN` in-flight for the running agent itself.

#### 3. Five Outbound RPC Bridges Built on `sendRequest()`

`sendRequest<Response>()` ([cli/structuredIO.ts](../../cli/structuredIO.ts):469–531) generates a `requestId = randomUUID()`, enqueues `{ type: 'control_request', request_id, request }` onto `this.outbound`, stores `{ resolve, reject, schema, request }` in `this.pendingRequests`, and attaches a one-shot `AbortSignal` listener. If the signal aborts, it enqueues `{ type: 'control_cancel_request', request_id }`, records the `tool_use_id` in `resolvedToolUseIds` *before* rejecting (so a late reply from the host won't trip the orphan handler), and rejects immediately with `AbortError` without waiting for host acknowledgment.

All five CLI→Host RPC capabilities build directly on `sendRequest()`:

1. **Tool Permissions (`createCanUseTool`, [cli/structuredIO.ts](../../cli/structuredIO.ts):533–659):**
   First evaluates local rules and modes via `hasPermissionsToUseTool()` ([Chapter 11](11-the-permission-engine.md)). Only when the local engine returns `'ask'` does `StructuredIO` go over the wire—and it **races** local `PermissionRequest` hooks against the remote SDK prompt in parallel:

```ts
// cli/structuredIO.ts:576-638 (abridged)
const hookPromise = executePermissionRequestHooksForSDK(
  tool.name, toolUseID, input, toolUseContext, mainPermissionResult.suggestions,
).then(decision => ({ source: 'hook' as const, decision }))

const requestId = randomUUID()
onPermissionPrompt?.(buildRequiresActionDetails(tool, input, toolUseID, requestId))
const sdkPromise = this.sendRequest<PermissionToolOutput>(
  {
    subtype: 'can_use_tool',
    tool_name: tool.name,
    input,
    permission_suggestions: mainPermissionResult.suggestions,
    blocked_path: mainPermissionResult.blockedPath,
    decision_reason: serializeDecisionReason(mainPermissionResult.decisionReason),
    tool_use_id: toolUseID,
    agent_id: toolUseContext.agentId,
  },
  permissionToolOutputSchema(),
  hookAbortController.signal,
  requestId,
).then(result => ({ source: 'sdk' as const, result }))

const winner = await Promise.race([hookPromise, sdkPromise])
if (winner.source === 'hook') {
  if (winner.decision) {
    sdkPromise.catch(() => {})
    hookAbortController.abort() // emits control_cancel_request to dismiss host UI
    return winner.decision
  }
  const sdkResult = await sdkPromise
  return permissionPromptToolResultToPermissionDecision(
    sdkResult.result, tool, input, toolUseContext,
  )
}
return permissionPromptToolResultToPermissionDecision(
  winner.result, tool, input, toolUseContext,
)
```

   Why race instead of awaiting hooks first? A slow `PermissionRequest` hook (e.g., an external approval service taking 20 seconds) would freeze the VS Code or Desktop permission dialog. Racing lets the host show the prompt immediately and dismiss it via `control_cancel_request` if the hook decides first.

   When the SDK host responds, `permissionPromptToolResultToPermissionDecision()` ([utils/permissions/PermissionPromptToolResultSchema.ts](../../utils/permissions/PermissionPromptToolResultSchema.ts):84–127) applies and persists any `updatedPermissions`, aborts `toolUseContext.abortController` if `behavior === 'deny' && result.interrupt`, and embeds two production scars:
   - **Mobile empty-object fallback (lines 107–111):** Mobile push notifications don't carry the full tool input payload, so they send `updatedInput: {}` to satisfy the schema. An empty `updatedInput` object is silently replaced with the original `input` so the tool isn't invoked with stripped arguments.
   - **Lenient telemetry/permission-update parsing (lines 37–62, `#29440`):** Both `decisionClassification` and `updatedPermissions` use Zod `.catch(undefined)` so a malformed permission suggestion from an older SDK host degrades gracefully instead of rejecting an entire `allow` decision.

2. **Sandbox Network Approval (`createSandboxAskCallback`, [cli/structuredIO.ts](../../cli/structuredIO.ts):731–753):**
   Piggybacks OS-level sandbox network prompts onto the existing `can_use_tool` protocol using a synthetic tool name: `SANDBOX_NETWORK_ACCESS_TOOL_NAME = 'SandboxNetworkAccess'`. SDK hosts already know how to render `can_use_tool`, so they get network approval dialogs with zero new protocol subtypes. Failure or stream closure fails closed (`return false`).
3. **Host-Side Hooks (`createHookCallback`, [cli/structuredIO.ts](../../cli/structuredIO.ts):661–689):**
   When the host sends `hooks` in `initialize`, each `callbackId` is wrapped in a `HookCallback` (`type: 'callback'`) that calls `sendRequest({ subtype: 'hook_callback', callback_id, input, tool_use_id }, hookJSONOutputSchema(), abort)`. Transport errors log to `stderr` and fail open to `{}`.
4. **MCP Elicitations (`handleElicitation`, [cli/structuredIO.ts](../../cli/structuredIO.ts):694–721):**
   Wired into connected non-SDK MCP clients by `registerElicitationHandlers()` ([cli/print.ts](../../cli/print.ts):1263–1387). Local `Elicitation` hooks get first crack; if none respond, `structuredIO.handleElicitation()` emits `{ subtype: 'elicitation', mcp_server_name, message, mode, url, elicitation_id, requested_schema }` validated against `SDKControlElicitationResponseSchema()`, then passes the result through `runElicitationResultHooks()`. Transport failures return `{ action: 'cancel' }`. URL-mode completion notifications (`ElicitationCompleteNotificationSchema`) are surfaced outbound as `system` / `elicitation_complete` SDK events.
5. **In-Process SDK MCP Tunneling (`sendMcpMessage`, [cli/structuredIO.ts](../../cli/structuredIO.ts):758–773 + [services/mcp/SdkControlTransport.ts](../../services/mcp/SdkControlTransport.ts)):**
   When an SDK caller creates an in-process MCP server via `createSdkMcpServer()` (living inside the host's own Node/Python process rather than a separate child binary), the CLI connects to it using `SdkControlClientTransport`. Every JSON-RPC request from the CLI's MCP client is wrapped by `sendMcpMessage()` into `{ subtype: 'mcp_message', server_name, message }`, shipped over `stdout`, handled by the host's `SdkControlServerTransport`, and returned in `{ mcp_response }`. Unsolicited MCP server notifications travel the opposite direction as host→CLI `mcp_message` control requests, which `cli/print.ts:2979–2994` injects into `sdkClient.client.transport.onmessage`.

### Hidden Invariants & Failure Modes

> [!IMPORTANT]
> **Bounded Deduplication Against Orphaned Permission Replay:** `resolvedToolUseIds` is capped at `MAX_RESOLVED_TOOL_USE_IDS = 1000` (`cli/structuredIO.ts:133, 176–187`), evicting the oldest entry via `Set` insertion order. It is updated on *all three* resolution paths: normal `control_response`, bridge `injectControlResponse()`, and `AbortSignal` cancellation. Together with `handledOrphanedToolUseIds` in `cli/print.ts:2766, 5272`, this guarantees a redelivered `control_response` never triggers duplicate tool execution. Meanwhile, a *genuine* orphan (e.g., user clicked Approve on `claude.ai` after the worker restarted and lost its in-memory `pendingRequests` map) falls through `unexpectedResponseCallback` → `handleOrphanedPermissionResponse()` (`cli/print.ts:5241–5304`), locates the unresolved `tool_use` block in the persisted transcript via `findUnresolvedToolUse(toolUseID)`, and enqueues a synthetic `mode: 'orphaned-permission'` command to complete the turn.

- **Concurrent permission state transition (`cli/structuredIO.ts:653–655`):** In `createCanUseTool()`'s `finally` block, `notifySessionStateChanged('running')` fires *only* if `this.getPendingPermissionRequests().length === 0`. Because parallel tool execution ([Chapter 06](06-executing-tools.md)) can have multiple `can_use_tool` prompts in flight at once, prematurely emitting `'running'` while another prompt is still open would hide the host's remaining approval UI.
- **Dual-host permission race (`injectControlResponse`, `cli/structuredIO.ts:283–331`):** When a local SDK session activates `remote_control`, `onControlRequestSent` mirrors every `can_use_tool` request to the `claude.ai` bridge. If the remote web/mobile user answers first, `injectControlResponse()` resolves the local promise *and* sends `control_cancel_request` on `stdout` so the local SDK host's `canUseTool` callback aborts cleanly; if the local SDK host answers first, `onControlRequestResolved` tells the bridge to cancel the remote prompt.

---

## 4. `cli/print.ts`: Driving `QueryEngine` Across Text, JSON, and `stream-json`

### The Problem

Headless execution looks deceptively simple until you remove the React REPL. Every concern that lived in React hooks in `screens/REPL.tsx` (`useSettingsChange`, `useManageMCPConnections`, `useQueueProcessor`, `useInboxPoller`, `useScheduledTasks`, `useReplBridge`) still has to work in a 5,594-line non-React module—while simultaneously supporting three output formats, two input formats, structured JSON output enforcement, background agent completion hold-back, session resume/rewind, and ~30 control request subtypes.

### The Real Implementation

#### Step 1: Mode Validation and Unified Stream Normalization

Before calling `runHeadless()`, [main.tsx](../../main.tsx):1237–1243 and 1818–1861 enforce the CLI flag invariants:
- `--sdk-url` automatically sets both `--input-format=stream-json` and `--output-format=stream-json`.
- `--input-format=stream-json` requires `--output-format=stream-json`; `--replay-user-messages` requires both; `--include-partial-messages` (or env `CLAUDE_CODE_INCLUDE_PARTIAL_MESSAGES`) requires `--print` and `--output-format=stream-json`.
- Inside `runHeadless()` ([cli/print.ts](../../cli/print.ts):787–793), `--output-format=stream-json` additionally requires `--verbose`.

Then `getStructuredIO()` ([cli/print.ts](../../cli/print.ts):5199–5233) collapses single-shot and streaming inputs into one abstraction:

```ts
// cli/print.ts:5199-5233
function getStructuredIO(
  inputPrompt: string | AsyncIterable<string>,
  options: {
    sdkUrl: string | undefined
    replayUserMessages?: boolean
  },
): StructuredIO {
  let inputStream: AsyncIterable<string>
  if (typeof inputPrompt === 'string') {
    if (inputPrompt.trim() !== '') {
      inputStream = fromArray([
        jsonStringify({
          type: 'user',
          session_id: '',
          message: { role: 'user', content: inputPrompt },
          parent_tool_use_id: null,
        } satisfies SDKUserMessage),
      ])
    } else {
      inputStream = fromArray([])
    }
  } else {
    inputStream = inputPrompt
  }

  return options.sdkUrl
    ? new RemoteIO(options.sdkUrl, inputStream, options.replayUserMessages)
    : new StructuredIO(inputStream, options.replayUserMessages)
}
```

#### Step 2: `runHeadless()` — Process Setup and Output-Format Dispatch

`runHeadless()` ([cli/print.ts](../../cli/print.ts):455–974) prepares the non-React runtime before draining `runHeadlessStreaming()`:
- **Headless subscriptions & GC:** Subscribes directly to `settingsChangeDetector` (`lines 520–532`), triggers `downloadUserSettings()` if `feature('DOWNLOAD_USER_SETTINGS')` in remote mode, initializes GrowthBook (`void initializeGrowthBook()`), and starts `setInterval(Bun.gc, 1000).unref()` under Bun to keep memory bounded in long-lived workers.
- **Guard, sandbox, and hook events:** Installs `installStreamJsonStdoutGuard()` for `stream-json`; initializes `SandboxManager.initialize(structuredIO.createSandboxAskCallback())` (or exits if `isSandboxRequired()` and unavailable, `#34044`); and registers `registerHookEventHandler()` to emit `hook_started` / `hook_progress` / `hook_response` NDJSON frames when `stream-json` + `verbose`.
- **Resume / Rewind (`loadInitialMessages`, `cli/print.ts:4893–5197`):** Loads prior history for `--continue`, `--teleport` (checked against `isPolicyAllowed('allow_remote_sessions')`), or `--resume <uuid|.jsonl|url>` (URL resume is `[ANT-ONLY]`; hydrates remote logs under `CLAUDE_CODE_USE_CCR_V2` or `ENABLE_SESSION_PERSISTENCE`). Supports `--resume-session-at <uuid>` (slices loaded messages to `index + 1`), `--fork-session` (keeps a fresh session ID), and standalone `--rewind-files <user-uuid>` (rewinds disk via `handleRewindFiles()` and exits immediately).
- **Output format switching (`cli/print.ts:851–973`):** Consumes every `StdoutMessage` yielded by `runHeadlessStreaming()`:
  - **`stream-json`:** Writes each frame immediately via `await structuredIO.write(message)`. When `feature('STREAMLINED_OUTPUT')` is compiled in and `CLAUDE_CODE_STREAMLINED_OUTPUT=true`, frames pass through `createStreamlinedTransformer()` ([utils/streamlinedTransform.ts](../../utils/streamlinedTransform.ts):130–193), a "distillation-resistant" filter that strips thinking blocks, system/init metadata, and raw tool calls, replacing consecutive tool-only turns with cumulative counts (`streamlined_tool_use_summary`, e.g., `"Searched 2 patterns, read 3 files"`) and emitting text as `streamlined_text` while preserving `result`.
  - **`json`:** Only accumulates `messages[]` when `options.outputFormat === 'json' && options.verbose` (`needsFullArray`), avoiding O(session) RAM retention in `text` and `stream-json` modes. At stream end, writes either `jsonStringify(messages)` (`--verbose`) or `jsonStringify(lastMessage)`.
  - **`text` (default):** Writes `lastMessage.result` on `'success'`, or a human-readable diagnostic for `'error_during_execution'`, `'error_max_turns'`, `'error_max_budget_usd'`, or `'error_max_structured_output_retries'`.
  - **Exit code & cleanup:** Drains pending background memory extraction (`feature('EXTRACT_MEMORIES') && isExtractModeActive()`), then calls `gracefulShutdownSync(lastMessage?.type === 'result' && lastMessage.is_error ? 1 : 0)`. Note lines 892–909: `lastMessage` explicitly ignores `control_*`, `stream_event`, `session_state_changed`, `task_*`, `post_turn_summary`, and `prompt_suggestion` so late tail events after `result` never clobber the exit code.

#### Step 3: `runHeadlessStreaming()` — Dual-Loop Concurrency Over `QueryEngine`

Inside `runHeadlessStreaming()` ([cli/print.ts](../../cli/print.ts):976–4143), two asynchronous loops run concurrently against `messageQueueManager` and `output = structuredIO.outbound`:

1. **The Inbound Reader IIFE (`cli/print.ts:2813–4140`):** Iterates `for await (const message of structuredIO.structuredInput)`:
   - **`control_request`:** Handled inline without waiting for an active turn to finish. Long-running auxiliary requests (`generate_session_title`, `side_question`) spawn fire-and-forget IIFEs (`lines 3783–3874`) specifically so their Haiku/forked-agent API round-trips don't block subsequent `interrupt` frames on `stdin`.
   - **`user`:** Marks `initialized = true`, deduplicates `message.uuid` against both disk (`doesMessageExistInSession`) and an in-memory 10,000-entry ring (`receivedMessageUuids`, emitting an `isReplay: true` ack for duplicates if `replayUserMessages` is set), resolves any web-composer `file_attachments`, enqueues a `prompt` command, and calls `void run()`.
   - **`assistant` / `system`:** History replay from bridge; converts via `toInternalMessages()` and pushes straight into `mutableMessages`.
   - **`control_response`:** Only arrives here when `replayUserMessages` is enabled; re-enqueued onto `output` for logging/UI parity.
   - **Stream close (`lines 4124–4139`):** Sets `inputClosed = true`, stops the `cronScheduler` (if `feature('AGENT_TRIGGERS')`), and—if `!running`—waits up to 5 seconds for any in-flight `prompt_suggestion`, finalizes pending async hooks, removes listeners, and closes `output.done()`.

2. **The Turn Consumer `run()` (`cli/print.ts:1865–2681`):** Guarded by a boolean mutex (`if (running) return; running = true`).
   - Ensures SDK MCP servers are synced (`updateSdkMcp()`) and optionally awaits synchronous plugin installation (`CLAUDE_CODE_SYNC_PLUGIN_INSTALL`, raced against `CLAUDE_CODE_SYNC_PLUGIN_INSTALL_TIMEOUT_MS`).
   - Enters a `do { ... } while (waitingForAgents)` loop calling `drainCommandQueue()`:
     - Dequeues main-thread commands (`cmd.agentId === undefined`). Consecutive `prompt` commands with matching `workload` and `isMeta` coalesce via `canBatchWith()` + `joinPromptValues()` (`cli/print.ts:428–453, 1949–1982`) into one `ask()` call; when `replayUserMessages` is enabled, merged intermediate UUIDs still receive synthetic `SDKUserMessageReplay` acks so hosts tracking per-UUID delivery don't stall.
     - Calls `ask()` ([QueryEngine.ts](../../QueryEngine.ts):1185–1295), which constructs a fresh `QueryEngine` sharing `mutableMessages` by reference and cloning `readFileState`, yields `engine.submitMessage(prompt, { uuid, isMeta })`, and writes back `engine.getReadFileState()` in `finally`.
     - Streams yielded `SDKMessage` records into `output`, flushing `drainSdkEvents()` before every message and `result`.

#### Step 4: The Control Protocol Surface

The inbound reader dispatches the full host→CLI control grammar. Grouping the handlers reveals how an external host treats Claude Code as a controllable stateful engine:

| Category | Subtypes (`request.subtype`) | Key Implementation Details & Scars |
| :--- | :--- | :--- |
| **Lifecycle** | `initialize`, `interrupt`, `end_session` | `initialize` accepts `systemPrompt`, `appendSystemPrompt`, `agents`, and `jsonSchema` over `stdin` to **avoid OS `ARG_MAX` limits** (`cli/print.ts:4369–4384`), registers SDK hook callbacks, and returns commands, agents, models, account info, output styles, and `pid`. Re-initializing returns an error carrying `pending_permission_requests`. `end_session` aborts and breaks the `stdin` loop. |
| **Runtime Config** | `set_permission_mode`, `set_model`, `set_max_thinking_tokens`, `apply_flag_settings`, `get_settings` | `set_permission_mode` enforces policy/launch gates for `bypassPermissions` and `feature('TRANSCRIPT_CLASSIFIER')` `auto` (`cli/print.ts:4568–4642`). `set_model` updates `setMainLoopModelOverride()` and injects model-switch breadcrumbs. `apply_flag_settings` converts JSON `null` values to key deletions, fans out via `settingsChangeDetector.notifyChange('flagSettings')` (post-`#20625` cache reset), and syncs model override (`lines 3700–3755`). |
| **History & State** | `rewind_files`, `seed_read_state`, `cancel_async_message`, `get_context_usage`, `stop_task` | `rewind_files` supports `dry_run` diff stats via `fileHistory.ts`. `cancel_async_message` removes an unstarted prompt from `messageQueueManager` by UUID. `seed_read_state` restores `readFileState` entries removed by snip/compaction (see invariant below). |
| **MCP & Plugins** | `mcp_status`, `mcp_message`, `mcp_set_servers`, `mcp_reconnect`, `mcp_toggle`, `reload_plugins`, plus internal IDE OAuth/channel subtypes (`mcp_authenticate`, `mcp_oauth_callback_url`, `mcp_clear_auth`, `claude_authenticate`, `channel_enable`) | `mcp_set_servers` serializes mutations through a promise chain (`mcpChangesPromise`) and **sends `control_response` *before* calling `void updateSdkMcp()`** (`lines 3059–3064`)—otherwise connecting new SDK MCP servers over `stdout` deadlocks while the host is still awaiting `mcp_set_servers`! |
| **Remote & Auxiliary** | `remote_control`, `side_question`, `generate_session_title`, `set_proactive` (`PROACTIVE`/`KAIROS`) | `side_question` forks from `getLastCacheSafeParams()` (swapping in a fresh `AbortController` if the prior turn was aborted!) for prompt-cache hits (`lines 3815–3874`). `remote_control` dynamically imports `initReplBridge` (`lines 3892–4020`). |

#### Step 5: Partial Messages, Structured Output, and Permission Delegation

Three headless features cross the boundary between `cli/print.ts` and `QueryEngine.ts`:

- **Partial Messages (`--include-partial-messages`):** When enabled, `QueryEngine.ts:818–826` wraps every raw Anthropic SSE `stream_event` into `{ type: 'stream_event', event, parent_tool_use_id: null, uuid, session_id }`, letting SDK UIs render token-by-token deltas without waiting for complete `assistant` blocks.
- **Structured Output (`--json-schema` or `initialize.jsonSchema`):** Rather than relying on raw constrained decoding alone, the harness injects a synthetic built-in tool named `'StructuredOutput'` (`createSyntheticOutputTool()` in [tools/SyntheticOutputTool/SyntheticOutputTool.ts](../../tools/SyntheticOutputTool/SyntheticOutputTool.ts):20–120, cached in a `WeakMap<object, CreateResult>` so repeated workflow invocations skip ~1.4 ms of Ajv JIT compilation). It is appended *after* `getTools()` filtering (`main.tsx:1885–1892` for CLI flags; `buildAllTools()` in `cli/print.ts:1492–1498` for `initialize.jsonSchema`). `QueryEngine.ts:331–333` registers a stop-hook enforcement guard (`registerStructuredOutputEnforcement`), captures the tool's output via a `structured_output` attachment (`QueryEngine.ts:838–840`), caps retries at `MAX_STRUCTURED_OUTPUT_RETRIES` (default `5`, emitting `error_max_structured_output_retries` at `QueryEngine.ts:1005–1048`), and surfaces the validated object on `SDKResultSuccess.structured_output` (`QueryEngine.ts:1149`).
- **Three Permission Modes (`getCanUseToolFn`, [cli/print.ts](../../cli/print.ts):4267–4334):**
  1. `permissionPromptToolName === 'stdio'` (forced whenever `--sdk-url` is set) → `structuredIO.createCanUseTool(onPermissionPrompt)`.
  2. Unset → pure static `hasPermissionsToUseTool()` with no interactive fallback.
  3. Custom MCP tool name (`--permission-prompt-tool`) → **lazily resolved on first prompt** (`lines 4294–4333`) because MCP servers connect incrementally in print mode and aren't in `appState.mcp.tools` at startup; `createCanUseToolWithPermissionPrompt()` races the MCP tool call against `createCombinedAbortSignal()` so `Ctrl+C`/interrupts break out of blocking permission tools immediately (`lines 4149–4263`).

### Hidden Invariants & Failure Modes

> [!WARNING]
> **`heldBackResult` and the Teammate Deadlock (`gh-30008`):** When `ask()` yields a `result` while a background `local_agent` or `local_workflow` is still running, `cli/print.ts:2222–2236` captures the message in `heldBackResult` (and defers any `prompt_suggestion`) until the `do { drainCommandQueue(); ... } while (waitingForAgents)` loop finishes draining background task completions. Critically, lines 2392–2394 explicitly exclude `in_process_teammate` tasks:
> ```ts
> // cli/print.ts:2392-2394
> const hasRunningBg = getRunningTasks(state).some(
>   t => isBackgroundTask(t) && t.type !== 'in_process_teammate',
> )
> ```
> Teammates remain `running` until explicitly shut down—waiting on them inside `waitingForAgents` looped forever. Instead, once `inputClosed` is true with an active swarm (`lines 2617–2667`), `print.ts` injects `SHUTDOWN_TEAM_PROMPT` so the team lead tears down its workers cleanly before closing `output.done()`.

- **Lost-wakeup guard on the `run()` mutex (`cli/print.ts:2487–2495`):** If a user message arrives between the last `dequeue()` returning `undefined` and `running = false` in `finally`, the producer's `void run()` sees `running === true` and returns. `run()` closes this race by checking `if (peek(isMainThread) !== undefined) { void run(); return }` *after* releasing `running = false`.
- **Authoritative turn-over boundary (`session_state_changed: 'idle'`):** In `run()`'s `finally` block (`cli/print.ts:2453–2469`), `print.ts` flushes `structuredIO.flushInternalEvents()`, emits `notifySessionStateChanged('idle')`, and runs one final `drainSdkEvents()` loop *before* blocking on the next command. Because `heldBackResult` flushed before `finally`, `'idle'` is the authoritative signal that a turn (and all its background agents) is completely finished.
- **Surviving `ask()`'s clone-and-replace on `seed_read_state` (`cli/print.ts:1157–1167, 2168–2181, 3017–3054`):** Because the `stdin` IIFE runs concurrently with `ask()`, writing a `seed_read_state` entry directly into `readFileState` mid-turn would be overwritten when `ask()`'s `finally` replaces `readFileState` with its clone. Seeds instead buffer in `pendingSeeds` (one-shot survival across one clone-replace cycle), normalize paths with `expandPath()` plus BOM/CRLF stripping, and **skip seeding if `Math.floor(stat.mtimeMs) > request.mtime`**—otherwise caching current disk bytes under an older client timestamp would cause `getChangedFiles()` to diff current-vs-current, emit no change notification, and hide an external edit!
- **Auto-resume of interrupted turns (`cli/print.ts:1171–1192`):** When `CLAUDE_CODE_RESUME_INTERRUPTED_TURN` is set and `loadInitialMessages()` detects an interrupted turn (`turnInterruptionState.kind !== 'none'`), `print.ts` splices out the interrupted message and its sentinel via `removeInterruptedMessage()` and pre-enqueues it—waiting until after `initialize` completes (`lines 2913–2917`) before calling `run()` so SDK system prompts, agents, and hooks are wired first.

---

## 5. Inverting the Architecture: The Harness as an MCP Server (`entrypoints/mcp.ts`)

### The Problem

Everything above assumes Claude Code owns the agentic loop—calling Claude, streaming tokens, deciding which tools to invoke. Sometimes the architecture flips inside out: another agent harness, desktop host, or IDE already owns the LLM loop and wants to consume Claude Code's built-in tools (`Read`, `Edit`, `Write`, `Bash`, `Glob`, `Grep`, etc.) over standard MCP stdio JSON-RPC.

### The Real Implementation

When invoked as `claude mcp serve`, [main.tsx](../../main.tsx):524–527 stamps `process.env.CLAUDE_CODE_ENTRYPOINT = 'mcp'`, registers the Commander subcommand (`main.tsx:3895–3906`), and lazily imports `mcpServeHandler()` ([cli/handlers/mcp.tsx](../../cli/handlers/mcp.tsx):42–71), which validates `cwd`, calls `setup(providedCwd, 'default', ...)`, and delegates to `startMCPServer()` in [entrypoints/mcp.ts](../../entrypoints/mcp.ts).

Unlike `cli/print.ts`, `entrypoints/mcp.ts` touches neither `QueryEngine` nor `StructuredIO`. It instantiates an `@modelcontextprotocol/sdk` `Server` named `'claude/tengu'` bound to `StdioServerTransport` and registers exactly two request handlers:

```ts
// entrypoints/mcp.ts:59-97 (abridged)
server.setRequestHandler(ListToolsRequestSchema, async () => {
  const toolPermissionContext = getEmptyToolPermissionContext()
  const tools = getTools(toolPermissionContext)
  return {
    tools: await Promise.all(
      tools.map(async tool => {
        let outputSchema: ToolOutput | undefined
        if (tool.outputSchema) {
          const convertedSchema = zodToJsonSchema(tool.outputSchema)
          // MCP SDK requires outputSchema to have type: "object" at root level
          // Skip schemas with anyOf/oneOf at root (issues/8014)
          if (
            typeof convertedSchema === 'object' &&
            convertedSchema !== null &&
            'type' in convertedSchema &&
            convertedSchema.type === 'object'
          ) {
            outputSchema = convertedSchema as ToolOutput
          }
        }
        return {
          ...tool,
          description: await tool.prompt({
            getToolPermissionContext: async () => toolPermissionContext,
            tools,
            agents: [],
          }),
          inputSchema: zodToJsonSchema(tool.inputSchema) as ToolInput,
          outputSchema,
        }
      }),
    ),
  }
})
```

On `CallToolRequestSchema` ([entrypoints/mcp.ts](../../entrypoints/mcp.ts):99–188), the server looks up the tool by name, constructs a minimal stub `ToolUseContext` (with `getAppState: () => getDefaultAppState()`, no-op state mutators, `isNonInteractiveSession: true`, `thinkingConfig: { type: 'disabled' }`, `commands: [review]`, and the shared 100-file LRU `readFileStateCache`), checks `tool.isEnabled()` and `tool.validateInput?.()`, and invokes `tool.call()` directly:

```ts
// entrypoints/mcp.ts:136-169
// TODO: validate input types with zod
try {
  if (!tool.isEnabled()) {
    throw new Error(`Tool ${name} is not enabled`)
  }
  const validationResult = await tool.validateInput?.(
    (args as never) ?? {},
    toolUseContext,
  )
  if (validationResult && !validationResult.result) {
    throw new Error(
      `Tool ${name} input is invalid: ${validationResult.message}`,
    )
  }
  const finalResult = await tool.call(
    (args ?? {}) as never,
    toolUseContext,
    hasPermissionsToUseTool,
    createAssistantMessage({ content: [] }),
  )

  return {
    content: [
      {
        type: 'text' as const,
        text:
          typeof finalResult === 'string'
            ? finalResult
            : jsonStringify(finalResult.data),
      },
    ],
  }
}
```

### Hidden Invariants & Failure Modes

Reading `entrypoints/mcp.ts` alongside `services/tools/toolExecution.ts` ([Chapter 06](06-executing-tools.md)) exposes five load-bearing differences caused by bypassing `runToolUse()`:

1. **Permission enforcement shifts to the MCP host:** `CallToolRequestSchema` *passes* `hasPermissionsToUseTool` as `tool.call()`'s `canUseTool` parameter, rather than calling `canUseTool()` *before* invoking `tool.call()`. Built-in leaf tools that rely on `runToolUse()` to check permissions ahead of time will execute directly once the MCP client sends `tools/call`—meaning **the calling MCP client is the permission boundary**, not `entrypoints/mcp.ts`.
2. **No Zod input parsing or hooks (`entrypoints/mcp.ts:136`):** The inline `// TODO: validate input types with zod` comment is literal: `tool.inputSchema.safeParse()` is skipped, and neither `PreToolUse` nor `PostToolUse` hooks run. Only `tool.validateInput()` executes before `tool.call()`.
3. **Cross-call `FileStateCache` bounded by LRU (`lines 40–45`):** Sharing a single 100-file (25 MB) `FileStateCache` across all `tools/call` requests preserves `FileEditTool`'s "must read before edit" and staleness invariants across sequential MCP tool calls while preventing unbounded memory growth in a long-lived server process.
4. **Root-object `outputSchema` filter (`issues/8014`, `lines 69–82`):** The MCP specification requires tool `outputSchema` to declare `type: "object"` at root. Tools whose Zod output schema is a `z.union` or `z.discriminatedUnion` convert to top-level `anyOf`/`oneOf`, which crashes strict MCP clients; `entrypoints/mcp.ts` drops `outputSchema` to `undefined` for those tools.
5. **No upstream MCP re-export & different startup path:** Note the `// TODO: Also re-expose any MCP tools` comments (`lines 62, 103`)—only built-in tools from `getTools()` are exposed. And unlike the specialized fast-path MCP servers in [entrypoints/cli.tsx](../../entrypoints/cli.tsx):72–95 (`--claude-in-chrome-mcp` and `feature('CHICAGO_MCP')` `--computer-use-mcp`) that bypass `main.tsx` completely, `claude mcp serve` routes through `main.tsx` Commander dispatch and runs full `setup()`.

---

## Putting the Layer Together

### The Three Machine-Readable Topologies

```
(1) Single-Shot (-p text / json)      (2) Bidirectional SDK (stream-json)
    prompt string / piped stdin           Host (TS/Py SDK, IDE, Bridge)
                 |                             |                 ^
         getStructuredIO()            stdin    |  NDJSON lines   | stdout
      (wraps into 1 user JSON)        (raw)    v                 | (guarded)
                 |                     +-------+-----------------+-------+
                 v                     | StructuredIO  <-> outbound FIFO |
    +-------------------------+        |  - processLine()                |
    |  runHeadlessStreaming() | <----> |  - pendingRequests Map          |
    |  (cli/print.ts)         |        |  - ndjsonSafeStringify()        |
    +------------+------------+        |  - streamJsonStdoutGuard        |
                 |                     +---------------------------------+
                 v
           QueryEngine.ask()           (3) Inverted Server (claude mcp serve)
                                           External MCP Host
                                                 |  StdioServerTransport
                                                 v  (JSON-RPC)
                                           entrypoints/mcp.ts ('claude/tengu')
                                                 |  direct tool.call()
                                                 v
                                           getTools() + 100-file cache
```

### Full-Duplex Multiplexing During a Single SDK Turn

```mermaid
sequenceDiagram
    participant Host as "SDK Host (TS/Py/IDE)"
    participant Guard as "stdout Guard + ndjsonSafeStringify"
    participant SIO as "StructuredIO (stdin/outbound FIFO)"
    participant Print as "cli/print.ts (stdin IIFE + run())"
    participant QE as "QueryEngine.ask()"
    participant MCP as "SdkControlClientTransport"

    Host->>SIO: "control_request (initialize: hooks, agents, jsonSchema, sdkMcpServers)"
    SIO->>Print: "yield control_request"
    Print->>SIO: "outbound.enqueue(control_response: commands, models, pid)"
    SIO->>Guard: "write(control_response)"
    Guard->>Host: "valid NDJSON line (non-JSON -> stderr [stdout-guard])"

    Host->>SIO: "user message (uuid)"
    SIO->>Print: "enqueue(prompt) -> void run()"
    Print->>QE: "ask(prompt, mutableMessages, readFileState)"
    QE-->>Print: "stream_event / assistant (tool_use)"
    Print->>SIO: "outbound.enqueue(assistant)"
    SIO->>Host: "assistant line (strict FIFO before permission prompt)"

    QE->>SIO: "canUseTool() -> races PermissionRequest hooks vs sendRequest()"
    SIO->>Host: "control_request (can_use_tool, request_id)"
    Host->>SIO: "control_response (allow + updatedInput, request_id)"
    SIO-->>QE: "processLine() resolves pendingRequests[request_id]"

    QE->>MCP: "SDK MCP tool call -> sendMcpMessage()"
    MCP->>SIO: "sendRequest(mcp_message, server_name, jsonrpc)"
    SIO->>Host: "control_request (mcp_message)"
    Host->>SIO: "control_response (mcp_response)"
    SIO-->>MCP: "transport.onmessage(mcp_response)"

    QE-->>Print: "result (usage, cost, structured_output)"
    Print->>SIO: "outbound.enqueue(result) + session_state_changed(idle)"
    SIO->>Host: "result + idle lines"
```

---

## How This Snaps Into the Next Layer

Notice that nothing in `cli/print.ts` assumes the SDK host sits on local `stdin`/`stdout` pipes—everything speaks to the `StructuredIO` interface. That abstraction is the exact hinge into [Chapter 24](24-across-the-wire-remote-sessions-bridge-and-direct-connect.md), snapping in at two concrete seams:

1. **Outbound worker transport (`cli/print.ts:5229–5232` → [cli/remoteIO.ts](../../cli/remoteIO.ts)):** When `--sdk-url` is passed, `getStructuredIO()` swaps `new StructuredIO(...)` for `new RemoteIO(options.sdkUrl, inputStream, options.replayUserMessages)`. `RemoteIO extends StructuredIO` replaces `stdin` with a `PassThrough` stream fed by `getTransportForUrl()` ([cli/transports/transportUtils.ts](../../cli/transports/transportUtils.ts):16–45)—selecting `SSETransport` (+ `CCRClient` lifecycle/heartbeats/internal-event persistence) under `CLAUDE_CODE_USE_CCR_V2`, `HybridTransport` under `CLAUDE_CODE_POST_FOR_SESSION_INGRESS_V2`, or `WebSocketTransport` by default. `RemoteIO.write()` ships frames over the network transport (still echoing `control_request` frames to `stdout` when `CLAUDE_CODE_ENVIRONMENT_KIND === 'bridge'` so a supervising bridge process detects permission prompts) and adds an Envoy idle keep-alive timer (`#21931`).
2. **Mid-session remote control (`cli/print.ts:3892–4020`):** Even a local stdio SDK session can dynamically attach a `claude.ai` remote-control bridge by sending `{ subtype: 'remote_control', enabled: true }`, which imports `src/bridge/initReplBridge.js` and wires `structuredIO.setOnControlRequestSent`, `setOnControlRequestResolved`, and `injectControlResponse` so local SDK and remote web/mobile clients race safely over the same session.

[Chapter 24](24-across-the-wire-remote-sessions-bridge-and-direct-connect.md) picks up directly on the far side of `RemoteIO` and `initReplBridge` to dissect the remote transports, always-on bridge daemons, Direct Connect, and the upstream credential proxy.

---

## Reading Exercises & Code Checkpoints

1. **Audit every control subtype handled in `cli/print.ts` vs. `controlSchemas.ts`:**
   Run:
   ```sh
   rg -n "request\.subtype ===" cli/print.ts
   rg -n "subtype: z\.literal\(" entrypoints/sdk/controlSchemas.ts
   ```
   Compare the two lists. Which subtypes exist in `cli/print.ts` (for IDE extensions, OAuth flows, or internal daemons) that are intentionally omitted from `SDKControlRequestInnerSchema`?
2. **Trace the `mcp_set_servers` deadlock prevention:**
   Inspect `cli/print.ts:3055–3065` alongside `cli/print.ts:1389–1461` (`updateSdkMcp`) and `cli/structuredIO.ts:758–773` (`sendMcpMessage`). Explain why awaiting `updateSdkMcp()` *before* sending `sendControlResponseSuccess(message)` would deadlock a synchronous SDK host.
3. **Verify the two-layer duplicate-response shield:**
   Read `cli/structuredIO.ts:176–187`, `374–401`, and `490–504`, then `cli/print.ts:5241–5304`. Trace what happens when a `PermissionRequest` hook wins the race against a slow host (`hookAbortController.abort()`), and the host's stale `control_response` arrives 200 ms later on `stdin`. Which data structure catches it and prevents `handleOrphanedPermissionResponse()` from running?
4. **Contrast `entrypoints/mcp.ts` with `services/tools/toolExecution.ts`:**
   Read `entrypoints/mcp.ts:99–188` and list every step from Chapter 06's `runToolUse()` lifecycle (Zod parse, `PreToolUse` hooks, `canUseTool` pre-check, `toolResultStorage` budgeting, `PostToolUse` hooks) that is *absent* when a tool is invoked via `claude mcp serve`. What security implication does this carry for an MCP host mounting `claude mcp serve`?


---

<!-- chapters/24-across-the-wire-remote-sessions-bridge-and-direct-connect.md — https://reverseengineeringclaudecode.com/chapters/24-across-the-wire-remote-sessions-bridge-and-direct-connect -->

# Chapter 24 — Across the Wire: Remote Sessions, Always-On Bridge, and Direct Connect

> **Layer:** Layer 8 (Entrypoints, Startup, SDK & Remote Control)
> **Prerequisites:** [Chapter 08](08-session-envelope-query-engine-and-transcripts.md), [Chapter 11](11-the-permission-engine.md), [Chapter 22](22-cold-start-mastery-cli-init-main.md), [Chapter 23](23-machine-readable-modes-headless-sdk-and-control-protocols.md)
> **Primary Source Files:**
> - [cli/transports/WebSocketTransport.ts](../../cli/transports/WebSocketTransport.ts) — WebSocket transport with UUID ring-buffer replay, suspension detection, and idle keep-alives
> - [cli/transports/HybridTransport.ts](../../cli/transports/HybridTransport.ts) — WebSocket reads paired with serialized HTTP POST writes
> - [cli/transports/SSETransport.ts](../../cli/transports/SSETransport.ts) — CCR v2 Server-Sent Events reader with sequence-number resumption and liveness watchdog
> - [cli/transports/SerialBatchEventUploader.ts](../../cli/transports/SerialBatchEventUploader.ts) — single-flight batched HTTP uploader with backpressure and `Retry-After` jitter
> - [cli/transports/WorkerStateUploader.ts](../../cli/transports/WorkerStateUploader.ts) — 2-slot RFC 7396 coalescing uploader for `PUT /worker`
> - [cli/transports/ccrClient.ts](../../cli/transports/ccrClient.ts) — CCR v2 worker lifecycle, epoch enforcement, full-so-far text coalescing, and internal-event persistence
> - [cli/transports/transportUtils.ts](../../cli/transports/transportUtils.ts) — environment-driven transport selector (`SSETransport` vs. `HybridTransport` vs. `WebSocketTransport`)
> - [cli/remoteIO.ts](../../cli/remoteIO.ts) — `StructuredIO` subclass wiring remote transports and `CCRClient` into `--sdk-url` print workers
> - [bridge/initReplBridge.ts](../../bridge/initReplBridge.ts) — REPL Remote Control entitlement gates, cross-process OAuth backoff, title derivation, and v1/v2 dispatch
> - [bridge/replBridge.ts](../../bridge/replBridge.ts) — env-based REPL bridge core (register/poll/ack/heartbeat loop and transport lifecycle)
> - [bridge/remoteBridgeCore.ts](../../bridge/remoteBridgeCore.ts) — env-less REPL bridge core (`POST /bridge` direct JWT exchange, proactive epoch refresh)
> - [bridge/replBridgeTransport.ts](../../bridge/replBridgeTransport.ts) — unified `ReplBridgeTransport` adapter over v1 `HybridTransport` and v2 `SSETransport + CCRClient`
> - [bridge/bridgeMessaging.ts](../../bridge/bridgeMessaging.ts) — ingress routing, server control-request responder, and `BoundedUUIDSet` echo filter
> - [bridge/bridgePermissionCallbacks.ts](../../bridge/bridgePermissionCallbacks.ts) — callback contract connecting the permission engine to remote approvals
> - [bridge/bridgeMain.ts](../../bridge/bridgeMain.ts) — standalone always-on `claude remote-control` daemon and multi-session worktree spawner
> - [bridge/sessionRunner.ts](../../bridge/sessionRunner.ts) — child `--sdk-url` process spawner, stdout activity/permission watcher, and stdin token refresh
> - [bridge/inboundAttachments.ts](../../bridge/inboundAttachments.ts) & [bridge/inboundMessages.ts](../../bridge/inboundMessages.ts) — remote `file_uuid` download-to-`@path` resolution and iOS/web image block normalization
> - [bridge/flushGate.ts](../../bridge/flushGate.ts), [bridge/capacityWake.ts](../../bridge/capacityWake.ts), [bridge/bridgePointer.ts](../../bridge/bridgePointer.ts), [bridge/sessionIdCompat.ts](../../bridge/sessionIdCompat.ts), [bridge/trustedDevice.ts](../../bridge/trustedDevice.ts) — ordering, wake, crash-recovery, ID-retag, and elevated-auth primitives
> - [remote/RemoteSessionManager.ts](../../remote/RemoteSessionManager.ts), [remote/SessionsWebSocket.ts](../../remote/SessionsWebSocket.ts), [remote/sdkMessageAdapter.ts](../../remote/sdkMessageAdapter.ts), [remote/remotePermissionBridge.ts](../../remote/remotePermissionBridge.ts) — local REPL client attaching to remote CCR sessions
> - [server/directConnectManager.ts](../../server/directConnectManager.ts), [server/createDirectConnectSession.ts](../../server/createDirectConnectSession.ts), [server/types.ts](../../server/types.ts) — direct WebSocket client for self-hosted `claude server`
> - [upstreamproxy/upstreamproxy.ts](../../upstreamproxy/upstreamproxy.ts) & [upstreamproxy/relay.ts](../../upstreamproxy/relay.ts) — non-dumpable container-side HTTP `CONNECT`-over-WebSocket credential-injection relay
> - [hooks/useReplBridge.tsx](../../hooks/useReplBridge.tsx), [hooks/useRemoteSession.ts](../../hooks/useRemoteSession.ts), [hooks/useDirectConnect.ts](../../hooks/useDirectConnect.ts), [hooks/toolPermission/handlers/interactiveHandler.ts](../../hooks/toolPermission/handlers/interactiveHandler.ts) — React/permission-engine integration points

---

## Why This Layer Exists

In [Chapter 23](23-machine-readable-modes-headless-sdk-and-control-protocols.md), `StructuredIO` turned a local process's `stdin` and `stdout` into a multiplexed NDJSON channel for prompts, assistant streams, and `control_request` permission round-trips. That solves single-machine automation. Real users immediately demand three harder network topologies:

1. **Local agent, remote human (Remote Control & Always-On Bridge):** You start an interactive session on your laptop—or leave `claude remote-control` running on a workstation—and drive it from `claude.ai` or your phone. Prompts, file uploads, and tool-approval prompts must cross NATs, laptop lid closes, and token expirations without duplicating messages or hanging the terminal.
2. **Remote agent, local terminal (CCR Remote Sessions & Direct Connect):** The agent executes inside a cloud container (Claude Code Remote, **CCR**) or a self-hosted `claude server`, while your local Ink REPL attaches over WebSocket to stream output and answer permission modals.
3. **Untrusted container subprocess, org-scoped credentials (`upstreamproxy/`):** Inside a CCR container, shell tools (`curl`, `gh`, `kubectl`) need org API keys (such as `DD-API-KEY`) to talk to internal services. Exposing those keys in `process.env` or on disk turns any prompt injection into instant secret exfiltration.

Every one of these topologies reuses the exact NDJSON SDK and control-protocol vocabulary from Chapter 23. What changes across the wire is **transport reliability, ordering, identity, and trust boundaries**.

> [!NOTE]
> **Snapshot boundaries in this chapter:** Several imported type or host-server files referenced by this layer are absent from this checkout and reconstructed strictly from their call sites:
> - `cli/transports/Transport.ts` (interface implemented by `WebSocketTransport` and `SSETransport`, consumed by `cli/remoteIO.ts` and `transportUtils.ts`)
> - `entrypoints/sdk/controlTypes.ts` (type companion to the present [entrypoints/sdk/controlSchemas.ts](../../entrypoints/sdk/controlSchemas.ts))
> - `types/message.ts` (internal REPL message union)
> - `bridge/webhookSanitizer.ts` (conditionally required under `feature('KAIROS_GITHUB_WEBHOOKS')` in [hooks/useReplBridge.tsx:193-200](../../hooks/useReplBridge.tsx))
> - Server-side Direct Connect host modules (`server/server.ts`, `server/sessionManager.ts`, `server/backends/dangerousBackend.ts`, `server/lockfile.ts`, `server/parseConnectUrl.ts`, `server/connectHeadless.ts`), whose dynamic imports and CLI wiring are observed in [main.tsx:3961-4095](../../main.tsx) while only the client-side files (`directConnectManager.ts`, `createDirectConnectSession.ts`, `types.ts`) are present on disk.

---

## 1. The Transport Substrate: WebSocket, Hybrid, SSE, and `CCRClient`

### The Problem

A naive WebSocket wrapper breaks under four production realities:

- **Silent proxy and NAT drops:** Edge proxies (Cloudflare's 5-minute idle timeout, Envoy sidecars) reset idle WebSockets even when RFC 6455 `ping`/`pong` control frames flow, because proxies only reset idle timers on *data* frames. Worse, after a laptop sleeps, `ws.ping()` on a dead NAT-mapped socket writes into the kernel send buffer and returns with zero error.
- **Write amplification and Firestore contention:** Bridge callers fire outbound messages via fire-and-forget `void transport.write()`. Sending concurrent HTTP POSTs for token-by-token `stream_event` deltas triggers concurrent Firestore writes to the same session document—producing write collisions, retry storms, and oncall pages ([cli/transports/HybridTransport.ts:50-52](../../cli/transports/HybridTransport.ts)).
- **Dual-runtime divergence (Bun vs. Node):** Compiled binaries run Bun's native `globalThis.WebSocket` (which hides HTTP upgrade response headers and takes a `proxy` URL string), while npm installs and CCR containers run Node's `ws` package (which exposes `upgradeReq.headers` and requires an `http.Agent`).
- **Mid-stream reconnect gaps:** If a phone or browser reconnects mid-generation, raw `text_delta` fragments leave the client missing earlier tokens, and overlapping worker restarts can interleave events from two processes unless fenced by a monotonic epoch.

### The Real Implementation

[cli/transports/transportUtils.ts:16-44](../../cli/transports/transportUtils.ts) selects among three concrete transports in strict priority order:

| Priority | Activation | Read Channel | Write Channel | Ordering / Replay Primitive |
| :--- | :--- | :--- | :--- | :--- |
| **1. `SSETransport` + `CCRClient`** | `CLAUDE_CODE_USE_CCR_V2` | HTTP `fetch` SSE (`/worker/events/stream`) | `CCRClient` batched POST (`/worker/events`, `/worker/internal-events`, `PUT /worker`) | `from_sequence_num` + `Last-Event-ID`, `worker_epoch` fencing, full-so-far text snapshots |
| **2. `HybridTransport`** | `CLAUDE_CODE_POST_FOR_SESSION_INGRESS_V2` | WebSocket (`extends WebSocketTransport`) | `SerialBatchEventUploader` → `POST .../session/<id>/events` | 100ms `stream_event` batching, single in-flight POST, UUID dedup |
| **3. `WebSocketTransport`** | Default (`ws://` / `wss://`) | WebSocket | WebSocket NDJSON frames | 1,000-msg `CircularBuffer` + `X-Last-Request-Id` replay |

#### `WebSocketTransport`: Replay, Suspension Detection, and Leak-Free Reconnects

[cli/transports/WebSocketTransport.ts](../../cli/transports/WebSocketTransport.ts) owns the low-level WebSocket state machine (`idle` → `reconnecting` ↔ `connected` → `closing` → `closed`). Every outbound message carrying a `uuid` is appended to a 1,000-entry `CircularBuffer<StdoutMessage>` (`DEFAULT_MAX_BUFFER_SIZE = 1000`) and updates `lastSentId`. On reconnect, `connect()` sends `X-Last-Request-Id: <lastSentId>` ([WebSocketTransport.ts:152-157](../../cli/transports/WebSocketTransport.ts)). Under Node, `onNodeOpen` reads the server's `upgradeReq.headers['x-last-request-id']`, evicts confirmed entries, and replays only the tail. Under Bun—whose WebSocket hides upgrade response headers—`onBunOpen` replays the entire buffer and relies on server-side UUID deduplication ([WebSocketTransport.ts:201-208](../../cli/transports/WebSocketTransport.ts)). Crucially, `replayBufferedMessages()` never clears the buffer after replay; messages stay buffered until confirmed on a *subsequent* handshake so a drop mid-replay cannot lose them.

Two production scars live in `startPingInterval()` and `startKeepaliveInterval()`:

```ts
// cli/transports/WebSocketTransport.ts:706-745
this.pingInterval = setInterval(() => {
  if (this.state === 'connected' && this.ws) {
    const now = Date.now()
    const gap = now - lastTickTime
    lastTickTime = now

    // Process-suspension detector: setInterval coalesces missed ticks on wake.
    // ws.ping() on a dead NAT-expired socket returns immediately with no error,
    // so assume dead and force reconnect rather than waiting a full ping cycle.
    if (gap > SLEEP_DETECTION_THRESHOLD_MS) {
      logForDebugging(
        `WebSocketTransport: ${Math.round(gap / 1000)}s tick gap detected — process was suspended, forcing reconnect`,
      )
      this.handleConnectionError()
      return
    }

    if (!this.pongReceived) {
      this.handleConnectionError()
      return
    }
    this.pongReceived = false
    this.ws.ping?.()
  }
}, DEFAULT_PING_INTERVAL)
```

Notice the dual liveness design:
1. A 10-second `ping`/`pong` loop catches half-open links and detects laptop sleep (`gap > 60s`), while `handleConnectionError()` separately detects sleep gaps *between* reconnect attempts and resets the 10-minute `DEFAULT_RECONNECT_GIVE_UP_MS` budget ([WebSocketTransport.ts:476-488](../../cli/transports/WebSocketTransport.ts)).
2. A 5-minute data-frame keep-alive (`{"type":"keep_alive"}\n`, skipped when `CLAUDE_CODE_REMOTE` is set because CCR heartbeats take over) resets proxy idle timers, and `lastActivityTime` explicitly excludes ping/pong frames so `tengu_ws_transport_closed` telemetry can diagnose Cloudflare 300s RST clusters ([WebSocketTransport.ts:92-96, 403-418, 767-792](../../cli/transports/WebSocketTransport.ts)).
3. Close codes `1002` (session reaped), `4001` (session expired), and `4003` (unauthorized) terminate retries immediately—with one escape hatch: on `4003`, if `refreshHeaders()` returns a different `Authorization` value (parent refreshed the token), the transport retries instead of dying ([WebSocketTransport.ts:42-46, 427-455](../../cli/transports/WebSocketTransport.ts)).
4. All five socket listeners (`onBunOpen`…`onNodeClose`, `onPong`) are bound class-property arrow functions detached in `removeWsListeners()` *before* `ws.close()` so reconnect storms don't leak orphaned sockets and closures ([WebSocketTransport.ts:195-200, 360-395](../../cli/transports/WebSocketTransport.ts)).

#### `HybridTransport` and `SerialBatchEventUploader`: Serializing Writes Without Head-of-Line Poisoning

`HybridTransport` subclasses `WebSocketTransport` for reads and overrides `write()` to POST batches through [cli/transports/SerialBatchEventUploader.ts](../../cli/transports/SerialBatchEventUploader.ts) (`maxBatchSize: 500`, `maxQueueSize: 100_000`, `POST_TIMEOUT_MS = 15_000`). High-frequency `stream_event` frames accumulate in a 100ms delay buffer (`BATCH_FLUSH_INTERVAL_MS = 100`); any non-stream message calls `takeStreamEvents()` first and enqueues `[...buffered, message]` atomically so ordering never inverts ([HybridTransport.ts:117-133](../../cli/transports/HybridTransport.ts)).

`SerialBatchEventUploader` enforces **at most one POST in flight** while new events batch behind it:

```ts
// cli/transports/SerialBatchEventUploader.ts:162-189
while (this.pending.length > 0 && !this.closed) {
  const batch = this.takeBatch()
  if (batch.length === 0) continue

  try {
    await this.config.send(batch)
    failures = 0
  } catch (err) {
    failures++
    if (
      this.config.maxConsecutiveFailures !== undefined &&
      failures >= this.config.maxConsecutiveFailures
    ) {
      this.droppedBatches++
      this.config.onBatchDropped?.(batch.length, failures)
      failures = 0
      this.releaseBackpressure()
      continue
    }
    this.pending = batch.concat(this.pending)
    const retryAfterMs =
      err instanceof RetryableError ? err.retryAfterMs : undefined
    await this.sleep(this.retryDelay(failures, retryAfterMs))
    continue
  }
  this.releaseBackpressure()
}
```

Three subtle invariants live inside `SerialBatchEventUploader`:
- **Poison-item eviction:** When `maxBatchBytes` is configured (`CCRClient` sets `10 * 1024 * 1024`), `takeBatch()` measures `Buffer.byteLength(jsonStringify(item))`. If serialization throws (BigInt, circular reference, throwing `toJSON`), it splices the bad item out in place—leaving it at `pending[0]` would hang `flush()` forever ([SerialBatchEventUploader.ts:209-233](../../cli/transports/SerialBatchEventUploader.ts)).
- **Clamped, jittered `Retry-After`:** Throwing `RetryableError(msg, retryAfterMs)` overrides exponential backoff with the server's 429 hint, *clamped* to `[baseDelayMs, maxDelayMs]` and spread by `+ Math.random() * jitterMs` so neither a bad header nor a synchronized fleet can hot-loop or stampede ([SerialBatchEventUploader.ts:235-253](../../cli/transports/SerialBatchEventUploader.ts)).
- **Backpressure deadlock hazard:** `enqueue()` blocks while `pending.length + items.length > maxQueueSize`. Passing a single batch larger than `maxQueueSize` would deadlock forever—which is why both `HybridTransport` and `CCRClient.eventUploader` raise `maxQueueSize` to `100_000` ([HybridTransport.ts:80-85](../../cli/transports/HybridTransport.ts), [ccrClient.ts:362-367](../../cli/transports/ccrClient.ts)).

#### `SSETransport`, `CCRClient`, and `WorkerStateUploader`: The CCR v2 Protocol

CCR v2 replaces Session-Ingress WebSockets with standard HTTP endpoints under `/v1/code/sessions/{id}/worker/*`. [cli/transports/SSETransport.ts](../../cli/transports/SSETransport.ts) streams `GET .../worker/events/stream` via `fetch()` and parses frames incrementally with `parseSSEFrames()` (splitting on `\n\n`, treating `:keepalive` comments as liveness proofs, and aborting if 45 seconds pass without any frame—`LIVENESS_TIMEOUT_MS = 45_000` against a 15-second server keepalive). Each `event: client_event` frame carries a `StreamClientEvent` whose `payload` is unwrapped into NDJSON for `onData`. Sequence numbers are tracked in `lastSequenceNum` and sent back via *both* `?from_sequence_num=` and `Last-Event-ID` on reconnect; a `seenSequenceNums` set catches duplicates and self-prunes entries below `lastSequenceNum - 200` once size exceeds 1,000 ([SSETransport.ts:245-266, 357-384](../../cli/transports/SSETransport.ts)). Permanent HTTP statuses (`401`, `403`, `404`) close immediately without burning the 10-minute backoff budget.

[cli/transports/ccrClient.ts](../../cli/transports/ccrClient.ts) sits alongside `SSETransport` as the worker control plane:

1. **Epoch fencing:** Every `PUT /worker`, heartbeat (`POST /worker/heartbeat`, every 20s against a 60s server TTL), and event POST carries `worker_epoch`. A `409 Conflict` means a newer worker superseded this process and fires `onEpochMismatch()`—which defaults to `process.exit(1)` for spawned container/bridge children, but **must** be overridden by in-process REPL callers so a superseded bridge closes gracefully instead of killing the user's terminal ([ccrClient.ts:294-300, 586-588](../../cli/transports/ccrClient.ts)).
2. **Deterministic vs. transient auth failure:** On `401`/`403`, `CCRClient` decodes the JWT's `exp` claim via `decodeJwtExpiry()`. If the token is genuinely expired, it exits immediately rather than wasting retries; if `exp` is still in the future (e.g., KMS hiccup or clock skew), it tolerates up to `MAX_CONSECUTIVE_AUTH_FAILURES = 10` (~200s across heartbeats) before giving up ([ccrClient.ts:589-614](../../cli/transports/ccrClient.ts)).
3. **Full-so-far `text_delta` coalescing:** Rather than forwarding raw token deltas, `accumulateStreamEvents()` holds a per-message chunk array (`byMessage: Map<messageId, string[][]>`) and flushes one `ephemeral: true` snapshot per touched block containing the *entire accumulated text from block start* (`chunks.join('')`), reusing the first delta's UUID for retry idempotency. A client connecting mid-stream immediately renders complete text. Entries are evicted only when the final `SDKAssistantMessage` arrives—never on `content_block_stop`, which abort/error paths skip ([ccrClient.ts:98-223, 747-786](../../cli/transports/ccrClient.ts)).
4. **Coalescing metadata updates (`WorkerStateUploader`):** Status and metadata updates (`PUT /worker`) don't need an unbounded queue. [cli/transports/WorkerStateUploader.ts](../../cli/transports/WorkerStateUploader.ts) bounds storage to exactly **two slots** (`inflight` + `pending`), merging new patches using RFC 7396 semantics one level deep inside `external_metadata` / `internal_metadata` (preserving `null` values so the server deletes keys) and absorbing any arriving patches before each retry.
5. **Four separate channels in `CCRClient`:** `eventUploader` (frontend-visible client events), `internalEventUploader` (transcript + compaction markers for `hydrateFromCCRv2InternalEvents` on resume), `deliveryUploader` (`received`/`processing`/`processed` ACKs), and `workerState` (`PUT /worker`).

In spawned `--sdk-url` worker mode, [cli/remoteIO.ts](../../cli/remoteIO.ts) bridges this stack into `StructuredIO`: it pipes `transport.setOnData` into an internal `PassThrough` input stream, wires `new CCRClient(this.transport, this.url)` **synchronously before `this.transport.connect()`** so the earliest SSE catch-up frames don't hit an unwired `onEventCallback` and miss their `received` ACKs ([remoteIO.ts:111-172](../../cli/remoteIO.ts)), and registers internal-event writers/readers plus command-lifecycle hooks (`started` → `processing`, `completed` → `processed`).

### Hidden Invariants & Failure Modes

> [!IMPORTANT]
> **Per-instance auth closures prevent cross-session and MCP token leaks.** Both `SSETransport` and `CCRClient` accept an optional `getAuthHeaders` callback rather than reading the process-global `CLAUDE_CODE_SESSION_ACCESS_TOKEN`. Multi-session daemons require this to avoid stomping tokens across sessions; the env-less REPL bridge *also* uses it because `mcp/client.ts` reads `CLAUDE_CODE_SESSION_ACCESS_TOKEN` ungatedly and would otherwise leak the bridge's worker JWT to user-configured HTTP/WebSocket MCP servers ([bridge/remoteBridgeCore.ts:229-234](../../bridge/remoteBridgeCore.ts)).

- **Cookie vs. Bearer collision:** In `SSETransport.connect()`, when `authHeaders` supplies a `Cookie` header (session-key auth), `delete headers['Authorization']` explicitly strips any stale Bearer header because sending both confuses the auth interceptor ([SSETransport.ts:250-263](../../cli/transports/SSETransport.ts)).
- **`close()` drops queued writes unless preceded by `flush()`:** `HybridTransport.close()` races `uploader.flush()` against a 3-second `CLOSE_GRACE_MS` fallback, whereas `CCRClient.close()` immediately abandons pending queues. Callers that need a terminal `result` event delivered must issue it before an awaited teardown HTTP call (such as session archival) or call `flush()` explicitly.

---

## 2. Exposing the Local REPL: Bridge Cores, Flush Gates, Attachments, and the Permission Race

### The Problem

Connecting an already-running local terminal REPL to `claude.ai` and mobile apps—via `/remote-control`, `claude --rc`, or ant-only auto-connect (`feature('CCR_AUTO_CONNECT')` / `tengu_cobalt_harbor`)—presents five nasty distributed-systems hazards:

1. **History vs. live ordering:** When you run `/remote-control` mid-conversation, 200 historical messages must POST to the server before new live turns stream, or the web UI renders out-of-order transcripts—and echoing our own posted messages back from the read stream would re-inject them as fake user prompts!
2. **Dead OAuth retry storms:** Because `useReplBridge` mounts on startup before the first `/v1/messages` call, expired unrefreshable keychain tokens once caused a single stuck client to hammer `POST /v1/environments/bridge` **2,879 times in one day** (17% of all 401s on the route; [hooks/useReplBridge.tsx:31-39](../../hooks/useReplBridge.tsx)).
3. **Two generations of bridge protocol:** Originally, REPL sessions had to register an *Environment* and run an Environments API poll/ack/heartbeat loop just to mint a `session_id`+`role=worker` JWT. A newer direct `/bridge` endpoint eliminates the Environments layer entirely—so the codebase must cleanly branch both paths while sharing message parsing, dedup, and transport adapters.
4. **Cross-client input quirks:** Web users attach files uploaded out-of-band (`file_uuid`), and iOS/web clients sometimes serialize base64 image blocks with camelCase `mediaType` instead of snake_case `media_type`—a single malformed block permanently poisons every subsequent Anthropic API request with `"media_type: Field required"` ([bridge/inboundMessages.ts:43-47](../../bridge/inboundMessages.ts)).
5. **Dual-control permission racing:** When a tool asks for approval, the modal appears simultaneously in the local Ink terminal and on the user's phone. Whichever human (or hook, or classifier, or MCP channel) responds first must win atomically and dismiss the *other* side's prompt.

### The Real Implementation

#### Entitlement, Trusted Device, and Cross-Process OAuth Backoff

Every bridge UI hook and entrypoint wraps its checks in the **positive ternary** `feature('BRIDGE_MODE') ? ... : false` pattern so Bun's dead-code eliminator strips GrowthBook flag names and dynamic imports from builds without bridge mode ([bridge/bridgeEnabled.ts:28-36](../../bridge/bridgeEnabled.ts)). Runtime eligibility in `getBridgeDisabledReason()` checks four layers in order: `isClaudeAISubscriber()` (excludes Bedrock/Vertex/Foundry/API-key users), `hasProfileScope()` (excludes inference-only `setup-token` / `CLAUDE_CODE_OAUTH_TOKEN`), `organizationUuid`, and the blocking GrowthBook gate `tengu_ccr_bridge` ([bridgeEnabled.ts:70-87](../../bridge/bridgeEnabled.ts)).

[bridge/initReplBridge.ts](../../bridge/initReplBridge.ts) layers on organization policy (`allow_remote_control`), proactive OAuth refresh (`checkAndRefreshOAuthTokenIfNeeded()`), and **content-addressed cross-process backoff**: if a token is still past `expiresAt` after refresh, it increments `bridgeOauthDeadFailCount` keyed by `bridgeOauthDeadExpiresAt` in global config. Once three processes observe the same dead `expiresAt`, future launches skip silently without hitting the network—and running `/login` produces a new `expiresAt` that automatically clears the backoff ([initReplBridge.ts:169-240](../../bridge/initReplBridge.ts)). In-process, `useReplBridge` pairs this with a `MAX_CONSECUTIVE_INIT_FAILURES = 3` circuit-breaker fuse.

For CCR v2's `SecurityTier=ELEVATED` enforcement, [bridge/trustedDevice.ts](../../bridge/trustedDevice.ts) enrolls a persistent 90-day `X-Trusted-Device-Token` in secure keychain storage immediately after `/login` (gated by GrowthBook `tengu_sessions_elevated_auth_enforcement`; enrollment must run within 10 minutes of login or the server rejects with `403 stale_session`). Reads are `memoize()`d because macOS keychain lookups spawn a ~40ms `security` subprocess, while the GrowthBook gate itself stays unmemoized so live flag flips take effect immediately.

#### Env-Based (`replBridge.ts`) vs. Env-Less (`remoteBridgeCore.ts`) Bridge

> [!IMPORTANT]
> **Don't conflate "env-less" with "CCR v2 transport."** As [bridge/remoteBridgeCore.ts:5-8](../../bridge/remoteBridgeCore.ts) warns, *env-less* (`tengu_bridge_repl_v2` in `initReplBridge.ts:410`) removes the Environments API register/poll/ack/heartbeat loop by calling `POST /v1/code/sessions/{id}/bridge` directly. The legacy *env-based* core ([bridge/replBridge.ts](../../bridge/replBridge.ts)) can **also** use the CCR v2 transport (`SSETransport` + `CCRClient`) whenever the work secret sets `use_code_sessions: true` (or ant-dev sets `CLAUDE_BRIDGE_USE_CCR_V2`).

[bridge/initReplBridge.ts:410-544](../../bridge/initReplBridge.ts) splits into the two cores (staying on env-based when `perpetual` is true for KAIROS assistant continuity):

1. **Env-less core ([bridge/remoteBridgeCore.ts](../../bridge/remoteBridgeCore.ts)):**
   - `POST /v1/code/sessions` (with `{ title, bridge: {} }`) → `cse_*` session ID ([bridge/codeSessionApi.ts:26-80](../../bridge/codeSessionApi.ts)).
   - `POST /v1/code/sessions/{id}/bridge` (OAuth + optional `X-Trusted-Device-Token`) → `{ worker_jwt, expires_in, api_base_url, worker_epoch }`. Each `/bridge` call bumps `worker_epoch` server-side—no separate `/worker/register` call is needed.
   - Connects via `createV2ReplTransport()` ([bridge/replBridgeTransport.ts:119-370](../../bridge/replBridgeTransport.ts)).
   - Schedules proactive refresh 5 minutes before `expires_in` via `createTokenRefreshScheduler` ([bridge/jwtUtils.ts:147-163](../../bridge/jwtUtils.ts)). Because every `/bridge` call bumps `worker_epoch`, a JWT-only header swap would cause the old `CCRClient` heartbeat to `409` within 20 seconds; instead, `rebuildTransport()` gates live writes behind `FlushGate`, captures `transport.getLastSequenceNum()`, closes the old transport, constructs a fresh `createV2ReplTransport` seeded with `initialSequenceNum`, and drains queued messages ([remoteBridgeCore.ts:477-527](../../bridge/remoteBridgeCore.ts)).
   - An `authRecoveryInFlight` boolean claimed **synchronously before any `await`** serializes proactive refresh against SSE `401` recovery—preventing a laptop-wake race where both fire simultaneously and cause a double epoch bump ([remoteBridgeCore.ts:330-340, 530-535](../../bridge/remoteBridgeCore.ts)).

2. **Env-based core ([bridge/replBridge.ts](../../bridge/replBridge.ts)):**
   - Registers a bridge environment (`POST /v1/environments/bridge`) and creates a session (`createBridgeSession`), writing a crash-recovery pointer (`bridge-pointer.json`).
   - Runs `startWorkPollLoop()` ([replBridge.ts:1851-2180](../../bridge/replBridge.ts)): fast-polls every 2s when idle (`poll_interval_ms_not_at_capacity`), then enters an at-capacity heartbeat/poll loop (`600_000`ms default, woken immediately by `CapacityWake` if the transport drops, plus a 60s sleep-overrun detector that forces one fast-poll cycle on wake).
   - When work arrives (`onWorkReceived`), it validates session ownership via `sameSessionId()` (comparing UUID bodies after the last `_` because CCR v2 compat returns `session_*` to v1 clients while the work queue delivers `cse_*`; [bridge/workSecret.ts:50-73](../../bridge/workSecret.ts)), picks `createV2ReplTransport` vs. `createV1ReplTransport(new HybridTransport(...))` with a `v2Generation` counter to discard stale async handshakes, and caps Hybrid retries at `maxConsecutiveFailures: 50` (~20 minutes) so a dead Session-Ingress cannot pin the drain loop forever.

Both cores share three load-bearing primitives:
- **`FlushGate<Message>` ([bridge/flushGate.ts](../../bridge/flushGate.ts)):** Activated *before* `transport.connect()`. Live `writeMessages()` calls queue inside the gate until the initial history `writeBatch()` (capped by `tengu_bridge_initial_history_cap`, default 200) finishes; `drainFlushGate()` then flushes queued live messages in order and only then emits `onStateChange('connected')`.
- **Two-layer echo & re-delivery dedup ([bridge/bridgeMessaging.ts](../../bridge/bridgeMessaging.ts)):** `recentPostedUUIDs` (a FIFO ring-backed `BoundedUUIDSet`, default 2,000) plus unbounded `initialMessageUUIDs` drop server echoes of our own outbound messages; `recentInboundUUIDs` drops duplicate inbound prompts if sequence-number negotiation falls back to history replay.
- **Teardown inside a 2-second shutdown budget:** `gracefulShutdown` races cleanup functions against a 2-second cap. Both cores fire `makeResultMessage()` *without* closing the transport first, then `await archiveSession()` (1.5s timeout, retagging `cse_*` → `session_*` via [bridge/sessionIdCompat.ts](../../bridge/sessionIdCompat.ts) for `/v1/sessions/{compatId}/archive`), letting archive round-trip latency serve as the uploader's drain window before `transport.close()` ([remoteBridgeCore.ts:658-717](../../bridge/remoteBridgeCore.ts)).

#### Inbound Messages, Attachments, and the Phantom-Prompt Scar

When `createV2ReplTransport` wires `SSETransport` for bridge/daemon sessions, it deliberately **overwrites** `CCRClient`'s `received`-only callback to ACK *both* `received` and `processed` immediately on SSE arrival ([bridge/replBridgeTransport.ts:234-252](../../bridge/replBridgeTransport.ts)). Why? In REPL/daemon bridge mode, `notifyCommandLifecycle` either never fires or runs in a separate child process; leaving events stuck at `received` caused `reconnectSession` to re-queue 21–25 already-answered prompts as phantom system-reminders on every restart!

Inbound user messages flow into `handleInboundMessage()` in [hooks/useReplBridge.tsx:180-221](../../hooks/useReplBridge.tsx):
1. `extractInboundMessageFields()` ([bridge/inboundMessages.ts](../../bridge/inboundMessages.ts)) normalizes malformed base64 image blocks (recovering `mediaType` or sniffing format via `detectImageFormatFromBase64()`) with a zero-allocation fast path when clean.
2. Under `feature('KAIROS_GITHUB_WEBHOOKS')`, `sanitizeInboundWebhookContent()` sanitizes webhook payloads (module absent from snapshot; observed at `useReplBridge.tsx:193-200`).
3. `resolveAndPrepend()` ([bridge/inboundAttachments.ts](../../bridge/inboundAttachments.ts)) extracts `file_attachments: [{ file_uuid, file_name }]`, fetches each via OAuth-authenticated `GET /api/oauth/files/{uuid}/content` (30s timeout), sanitizes `basename(file_name)` to `[a-zA-Z0-9._-]`, writes `~/.claude/uploads/{sessionId}/{uuid8}-{safeName}`, and prepends quoted `@"<path>" ` refs to the **last** text block (`content.findLastIndex(b => b.type === 'text')`). Two subtle bugs forced those exact details: unquoted `@refs` truncate at the first space in home directories like `/Users/John Smith/`, and `processUserInputBase` reads `inputString` from the *last* block—so prepending to `block[0]` silently dropped attachments on `[text, image]` prompts ([inboundAttachments.ts:131-161](../../bridge/inboundAttachments.ts)).
4. Finally, `enqueue()` injects the prompt into the REPL queue with `uuid` preserved (so the echoed turn matches the web UI's bubble), `skipSlashCommands: true`, and `bridgeOrigin: true` (allowing only `isBridgeSafeCommand` commands).

#### Race 4: Bidirectional Remote Permission Approvals

When `useReplBridge` finishes connecting (and is not in `outboundOnly` mirror mode), it constructs a [BridgePermissionCallbacks](../../bridge/bridgePermissionCallbacks.ts) object backed by a `pendingPermissionHandlers: Map<requestId, handler>` and stores it in `AppState.replBridgePermissionCallbacks` ([hooks/useReplBridge.tsx:369-386, 540-586](../../hooks/useReplBridge.tsx)). In [hooks/toolPermission/handlers/interactiveHandler.ts](../../hooks/toolPermission/handlers/interactiveHandler.ts), every interactive permission check creates an atomic `createResolveOnce()` gate (`claim()`) and launches local UI, hooks, bash classifier, MCP channel relay, and **Race 4 (CCR bridge)** concurrently:

```ts
// hooks/toolPermission/handlers/interactiveHandler.ts:244-281
if (bridgeCallbacks && bridgeRequestId) {
  bridgeCallbacks.sendRequest(
    bridgeRequestId, ctx.tool.name, displayInput,
    ctx.toolUseID, description, result.suggestions, result.blockedPath,
  )

  const signal = ctx.toolUseContext.abortController.signal
  const unsubscribe = bridgeCallbacks.onResponse(bridgeRequestId, response => {
    if (!claim()) return // Local user/hook/classifier already responded
    signal.removeEventListener('abort', unsubscribe)
    clearClassifierChecking(ctx.toolUseID)
    clearClassifierIndicator()
    ctx.removeFromQueue()
    channelUnsubscribe?.()

    if (response.behavior === 'allow') {
      if (response.updatedPermissions?.length) {
        void ctx.persistPermissions(response.updatedPermissions)
      }
      resolveOnce(ctx.buildAllow(response.updatedInput ?? displayInput))
    } else {
      resolveOnce(ctx.cancelAndAbort(response.message))
    }
  })
  signal.addEventListener('abort', unsubscribe, { once: true })
}
```

Symmetrically, when the local user approves, rejects, or aborts in Ink (`onAllow`/`onReject`/`onAbort`), the handler wins `claim()` and calls *both* `bridgeCallbacks.sendResponse()` and `bridgeCallbacks.cancelRequest(bridgeRequestId)` so `claude.ai` dismisses its modal and clears `requires_action` back to `running` ([interactiveHandler.ts:137-170](../../hooks/toolPermission/handlers/interactiveHandler.ts), [remoteBridgeCore.ts:832-872](../../bridge/remoteBridgeCore.ts)). If a hook, classifier, or MCP channel resolves locally instead, `cancelRequest()` alone notifies CCR.

### Hidden Invariants & Failure Modes

- **Always reply to server `control_request`—even in `outboundOnly` mirror mode (`feature('CCR_MIRROR')`):** `handleServerControlRequest()` rejects mutable requests (`interrupt`, `set_model`, `set_permission_mode`, `set_max_thinking_tokens`) with an error when `outboundOnly` is true, *except* `initialize`, which must still return `success` or the server kills the connection after 10–14 seconds ([bridge/bridgeMessaging.ts:265-283](../../bridge/bridgeMessaging.ts)).
- **Policy checks before `transitionPermissionMode`:** In `useReplBridge.tsx:416-447`, `onSetPermissionMode` checks `isBypassPermissionsModeDisabled()`, `isBypassPermissionsModeAvailable`, and `isAutoModeGateEnabled()` *before* invoking `transitionPermissionMode()`, because the latter sets `STATE.autoModeActive = true` before throwing—which would both violate the 3-way auto-mode invariant and skip sending a `control_response`.
- **Privacy redaction in `system/init`:** When `tengu_bridge_system_init` is on, `useReplBridge.tsx:297-319` sends `tools: []`, `mcpClients: []`, and `plugins: []` intentionally so local filesystem paths and MCP server names are not persisted to CCR v2's Spanner store.
- **Teardown serialization:** `useReplBridge` awaits `teardownPromiseRef.current` before re-initializing so a previous environment's `DELETE /v1/environments/bridge/{id}` cannot race and destroy a newly registered environment ([hooks/useReplBridge.tsx:135-144](../../hooks/useReplBridge.tsx)).

---

## 3. Always-On Multi-Session Bridge: `bridgeMain.ts`, `sessionRunner.ts`, and Crash Recovery

### The Problem

The in-process REPL bridge ends the moment you close your terminal. Users also need a persistent listener (`claude remote-control`, `claude rc`, or a supervised `claude daemon` worker) that stays online for days, spawns up to 32 concurrent remote sessions on a machine without letting them trample each other's working tree, rotates 5-hour session JWTs into live child processes without restarting them, and recovers cleanly if the machine crashes or sleeps.

### The Real Implementation

[entrypoints/cli.tsx:112-162](../../entrypoints/cli.tsx) intercepts `claude remote-control` (and aliases `rc`, `remote`, `sync`, `bridge`) on the **zero-bloat fast path**—validating OAuth, `getBridgeDisabledReason()`, `checkBridgeMinVersion()`, and `allow_remote_control` policy, then dynamically importing `bridgeMain()` from [bridge/bridgeMain.ts](../../bridge/bridgeMain.ts) without ever touching the 800 KB `main.tsx`. Daemon supervisors invoke the non-interactive sibling `runBridgeHeadless()` ([bridgeMain.ts:2810-2960](../../bridge/bridgeMain.ts)), which skips readline dialogs/TUI and throws `BridgeHeadlessPermanentError` on non-retryable misconfigurations (untrusted workspace, HTTP non-localhost URL, or `worktree` mode outside a git repo) so the supervisor parks the worker instead of backoff-thrashing.

#### `runBridgeLoop()` and Multi-Session Spawn Modes

Behind GrowthBook gate `tengu_ccr_bridge_multi_session`, `bridgeMain()` supports three `SpawnMode`s ([bridge/types.ts:63-69](../../bridge/types.ts), [bridgeMain.ts:2278-2310](../../bridge/bridgeMain.ts)):

- `single-session` (`maxSessions = 1`): legacy mode; tears down when the one session exits. Also forced when resuming via `--continue` / `--session-id`.
- `same-dir` (`maxSessions = 32` default via `SPAWN_SESSIONS_DEFAULT`): persistent server; all spawned children share `config.dir`.
- `worktree` (`maxSessions = 32` default): persistent server; every on-demand session gets an isolated git worktree via `createAgentWorktree('bridge-<safeId>')` ([bridgeMain.ts:976-1015](../../bridge/bridgeMain.ts)), removed on exit via `removeAgentWorktree()` tracked in `pendingCleanups`. A pre-created initial session is exempted from worktree isolation so the user's first prompt lands in their launch directory.

When `pollForWork()` returns a `WorkResponse` (using `reclaim_older_than_ms: 5000` so un-ACK'd work items from a crashed prior worker are reclaimed promptly), `runBridgeLoop()` executes a strict commit order ([bridgeMain.ts:753-962](../../bridge/bridgeMain.ts)):
1. Skip if `work.id` is in `completedWorkIds` (sleeping if at capacity so stale redeliveries cannot tight-loop).
2. `decodeWorkSecret(work.secret)` (base64url JSON, `version === 1`). On decode failure, call OAuth-authed `stopWorkWithRetry()` so Redis `XAUTOCLAIM` doesn't redeliver the poisoned work item every 5 seconds!
3. If `activeSessions.get(sessionId)` already exists, deliver the rotated JWT to the running child (`existingHandle.updateAccessToken(...)`), update `sessionIngressTokens` and `sessionWorkIds`, reschedule `tokenRefresh`, and `ackWork()`.
4. Check capacity (`activeSessions.size >= config.maxSessions`) **before** calling `ackWork()`—acking before the capacity check would permanently drop overflow work ([bridgeMain.ts:832-836, 891-898](../../bridge/bridgeMain.ts)).
5. If `secret.use_code_sessions === true` (or `CLAUDE_BRIDGE_USE_CCR_V2`), call `registerWorker()` (2 attempts) to obtain `workerEpoch` and point the child at `/v1/code/sessions/{id}`; otherwise build a v1 `ws(s)://` Session-Ingress URL via `buildSdkUrl()`.

#### `createSessionSpawner()`: Child Process Isolation and In-Flight Token Rotation

[bridge/sessionRunner.ts:248-548](../../bridge/sessionRunner.ts) spawns each session as an isolated headless worker:

```ts
// bridge/sessionRunner.ts:287-323 (abridged)
const args = [
  ...deps.scriptArgs, // process.argv[1] for npm installs; [] for compiled binary
  '--print', '--sdk-url', opts.sdkUrl, '--session-id', opts.sessionId,
  '--input-format', 'stream-json', '--output-format', 'stream-json',
  '--replay-user-messages',
  ...(deps.permissionMode ? ['--permission-mode', deps.permissionMode] : []),
]
const env: NodeJS.ProcessEnv = {
  ...deps.env,
  CLAUDE_CODE_OAUTH_TOKEN: undefined, // force child onto session ingress token
  CLAUDE_CODE_ENVIRONMENT_KIND: 'bridge',
  ...(deps.sandbox && { CLAUDE_CODE_FORCE_SANDBOX: '1' }),
  CLAUDE_CODE_SESSION_ACCESS_TOKEN: opts.accessToken,
  CLAUDE_CODE_POST_FOR_SESSION_INGRESS_V2: '1',
  ...(opts.useCcrV2 && {
    CLAUDE_CODE_USE_CCR_V2: '1',
    CLAUDE_CODE_WORKER_EPOCH: String(opts.workerEpoch),
  }),
}
```

Look closely at two clever mechanisms in `sessionRunner.ts`:
- **Dual-path stdout snooping:** Because `RemoteIO.write()` echoes `control_request` (and all lines in debug mode) to child `stdout` when `CLAUDE_CODE_ENVIRONMENT_KIND === 'bridge'` ([cli/remoteIO.ts:237-241](../../cli/remoteIO.ts)), the bridge parent parses child `stdout` NDJSON to maintain a 10-entry `activities` ring buffer for the live TUI, derive a session title from the first real human `--replay-user-messages` line, and detect `can_use_tool` prompts.
- **In-flight token rotation via `stdin`:** Five minutes before a session JWT expires, `createTokenRefreshScheduler` wakes up. For **v1** children, `handle.updateAccessToken(token)` writes a single control frame into child `stdin`:
  ```ts
  // bridge/sessionRunner.ts:533-538
  handle.writeStdin(
    jsonStringify({
      type: 'update_environment_variables',
      variables: { CLAUDE_CODE_SESSION_ACCESS_TOKEN: token },
    }) + '\n',
  )
  ```
  The child's `StructuredIO` updates `process.env` in place so its transport's `refreshHeaders()` picks up the new token on the next reconnect ([sessionRunner.ts:527-542](../../bridge/sessionRunner.ts)). For **v2** children (`v2Sessions.has(sessionId)`), OAuth tokens lack the `session_id` JWT claim required by `/worker/*`—so `onRefresh` instead calls `api.reconnectSession(environmentId, sessionId)`, triggering server re-dispatch of fresh work with a brand-new JWT that then flows through the `existingHandle` path ([bridgeMain.ts:272-310](../../bridge/bridgeMain.ts)).

#### Crash-Recovery Pointer (`bridgePointer.ts`) and `CapacityWake`

[bridge/bridgePointer.ts](../../bridge/bridgePointer.ts) persists `{ sessionId, environmentId, source }` to `~/.claude/projects/<sanitizedDir>/bridge-pointer.json`. Instead of embedding a timestamp, staleness is anchored directly on the file's **`mtime`** against `BRIDGE_POINTER_TTL_MS` (4 hours, matching the server's rolling `BRIDGE_LAST_POLL_TTL`). Rewriting identical JSON on every work dispatch cheaply bumps the clock. On unclean death (`kill -9`, closed terminal), `claude remote-control --continue` runs `readBridgePointerAcrossWorktrees()`—fast-pathing the current directory (zero `git` exec) and fanning out in parallel across up to `MAX_WORKTREE_FANOUT = 50` git worktree siblings to pick the freshest pointer. In `perpetual` mode (`feature('KAIROS')`), teardown deliberately skips archiving, deregistering, and clearing the pointer so an assistant session resumes continuously across clean restarts ([hooks/useReplBridge.tsx:155-163](../../hooks/useReplBridge.tsx)).

Meanwhile, [bridge/capacityWake.ts](../../bridge/capacityWake.ts) solves the at-capacity responsiveness problem shared by both `replBridge.ts` and `bridgeMain.ts`: merging the outer shutdown `AbortSignal` with a rotatable internal `wakeController` so that the instant a session exits or a transport closes, a 10-minute at-capacity sleep aborts immediately without leaking event listeners.

### Hidden Invariants & Failure Modes

- **`spawnScriptArgs()` prevents Node CLI crashes:** Under compiled binaries, `process.execPath` is `claude` itself; under npm installs, `process.execPath` is `node`, so `spawnScriptArgs()` prepends `process.argv[1]`—otherwise `node --print --sdk-url ...` exits immediately with `bad option: --sdk-url` ([bridgeMain.ts:111-124](../../bridge/bridgeMain.ts)).
- **Capturing `spawnMode` before `await`:** Because the interactive `w` hotkey mutates `config.spawnMode` live while `createAgentWorktree()` takes 1–2 seconds, `runBridgeLoop()` snapshots `const spawnModeAtDecision = config.spawnMode` *before* awaiting so worktree creation and analytics never disagree ([bridgeMain.ts:969-973](../../bridge/bridgeMain.ts)).
- **Caching `compatSessionId` per session:** `sessionCompatIds` caches `toCompatSessionId(sessionId)` once at spawn so a mid-session flip of GrowthBook `tengu_bridge_repl_v2_cse_shim_enabled` cannot orphan logger/title keys ([bridgeMain.ts:166-169](../../bridge/bridgeMain.ts)).

---

## 4. Looking the Other Way: Remote CCR Client (`remote/`) and Direct Connect (`server/`)

### The Problem

Now invert the roles: the agent loop runs remotely—either inside a cloud CCR container (`claude --teleport`, `claude assistant`) or inside a self-hosted `claude server` (`cc://` URLs)—and your local Ink REPL acts as a pure terminal frontend. The local REPL already has rich message rendering, streaming tool-use spinners, and `ToolUseConfirm` permission modals, but it is **not** running `query()`, does not own the remote session's MCP tools, and can silently lose sync across container restarts or compaction pauses.

### The Real Implementation

#### Remote CCR Client (`remote/` + `hooks/useRemoteSession.ts`)

[remote/RemoteSessionManager.ts](../../remote/RemoteSessionManager.ts) splits reads and writes across two protocols:
- **Inbound stream (`SessionsWebSocket`):** [remote/SessionsWebSocket.ts](../../remote/SessionsWebSocket.ts) connects to `wss://.../v1/sessions/ws/{sessionId}/subscribe?organization_uuid={orgUuid}` with OAuth `Authorization: Bearer` headers (fetching a fresh token on every connect attempt), 30s WebSocket pings, and a deliberately open type guard (`isSessionsMessage` accepts any object with a string `type` so new backend message types aren't silently dropped before client upgrades). Its close-code policy captures a subtle server scar:

```ts
// remote/SessionsWebSocket.ts:246-272
if (PERMANENT_CLOSE_CODES.has(closeCode)) { // 4003 unauthorized
  this.callbacks.onClose?.()
  return
}

// 4001 (session not found) can be transient during compaction: the server
// may briefly consider the session stale while the CLI worker is busy with
// the compaction API call and not emitting events.
if (closeCode === 4001) {
  this.sessionNotFoundRetries++
  if (this.sessionNotFoundRetries > MAX_SESSION_NOT_FOUND_RETRIES) { // 3
    this.callbacks.onClose?.()
    return
  }
  this.scheduleReconnect(
    RECONNECT_DELAY_MS * this.sessionNotFoundRetries,
    `4001 attempt ${this.sessionNotFoundRetries}/${MAX_SESSION_NOT_FOUND_RETRIES}`,
  )
  return
}
```

- **Outbound prompts (`HTTP POST`) and control replies (`WebSocket`):** User messages go via `sendEventToRemoteSession()` ([utils/teleport/api.ts:361-386](../../utils/teleport/api.ts)) to `POST /v1/sessions/{sessionId}/events` with `anthropic-beta: ccr-byoc-2025-07-29` and `x-organization-uuid`. Permission responses (`control_response`) and interrupts (`control_request` with `subtype: 'interrupt'`) go back over `SessionsWebSocket`. Unrecognized `control_request` subtypes always receive a `control_response` with `subtype: 'error'` so the remote container never hangs waiting ([RemoteSessionManager.ts:198-213](../../remote/RemoteSessionManager.ts)).
- **Adapting SDK wire messages to Ink REPL state:**
  - [remote/sdkMessageAdapter.ts](../../remote/sdkMessageAdapter.ts) maps `SDKMessage` → internal `Message` or `StreamEvent`. To detect remote tool results, `convertSDKMessage()` inspects `b.type === 'tool_result'` directly rather than `parent_tool_use_id`, because agent-side `normalizeMessage()` hardcodes `parent_tool_use_id: null` for top-level tool results ([sdkMessageAdapter.ts:178-185](../../remote/sdkMessageAdapter.ts)).
  - [remote/remotePermissionBridge.ts](../../remote/remotePermissionBridge.ts) solves two local-UI gaps for remote `can_use_tool` prompts: `createSyntheticAssistantMessage()` fabricates the `AssistantMessage` required by `ToolUseConfirm`, and `createToolStub()` creates a minimal `Tool` fallback when the remote container invokes an MCP tool unknown to the local CLI.
  - `viewerOnly` mode (used by `claude assistant`) disables Ctrl+C interrupts, disables the 60s stuck-session reconnect timer, skips title overwrites, and passes `{ convertToolResults: true, convertUserTextMessages: true }` so `BriefTool` (`SendUserMessage`) tool results render visibly ([RemoteSessionManager.ts:56-61](../../remote/RemoteSessionManager.ts), [hooks/useRemoteSession.ts:269-278, 534-580](../../hooks/useRemoteSession.ts)).

#### Direct Connect (`server/` + `hooks/useDirectConnect.ts`)

Gated behind build-time `feature('DIRECT_CONNECT')`, Direct Connect eliminates the Anthropic cloud relay altogether for self-hosted `claude server` instances (`main.tsx:3961-4095`, where the server host modules are absent from this snapshot, while [server/types.ts](../../server/types.ts) preserves `ServerConfig`, `SessionInfo`, and the `~/.claude/server-sessions.json` `SessionIndexEntry` schema). On the client side:

1. [server/createDirectConnectSession.ts](../../server/createDirectConnectSession.ts) sends `POST ${serverUrl}/sessions` with `{ cwd, dangerously_skip_permissions }` and an optional `Authorization: Bearer` header, validating `{ session_id, ws_url, work_dir }` with `connectResponseSchema()`.
2. [server/directConnectManager.ts](../../server/directConnectManager.ts) opens a **single bidirectional WebSocket** directly to `ws_url`. Unlike `RemoteSessionManager`, there is no HTTP POST split: `sendMessage()` writes `--input-format stream-json` user frames straight onto the socket, `respondToPermissionRequest()` and `sendInterrupt()` speak the exact `StructuredIO` `control_response`/`control_request` envelopes, and incoming NDJSON lines are split on `\n` and routed to `onMessage` / `onPermissionRequest` (filtering out `keep_alive`, `streamlined_*`, and `post_turn_summary`).
3. [hooks/useDirectConnect.ts](../../hooks/useDirectConnect.ts) reuses the *exact same* `convertSDKMessage({ convertToolResults: true })`, `createSyntheticAssistantMessage()`, and `createToolStub()` adapters as `useRemoteSession.ts`, shutting down via `gracefulShutdown(1)` if the server socket closes.

### Hidden Invariants & Failure Modes

Four real-world scars in [hooks/useRemoteSession.ts](../../hooks/useRemoteSession.ts) explain why remote viewers are much trickier than they look:

- **Multi-echo ring dedup before POST:** `sentUUIDsRef` uses `BoundedUUIDSet(50)`—*not* a delete-on-first-match `Set`—and records `opts.uuid` *before* awaiting the POST. Why? The server may broadcast the POST to `/subscribe` *and* the worker may echo it again on its write path; deleting on the first echo lets the second echo duplicate the user bubble ([useRemoteSession.ts:126-137, 177-191, 490-493](../../hooks/useRemoteSession.ts)).
- **Clear response timeout *before* echo filtering:** Receiving the WS echo of our own POST proves the subscription is alive. Clearing `responseTimeoutRef` before the echo filter prevents slow-to-stream agents from spuriously tripping the 60s (or 180s during compaction) "unresponsive" warning and force-reconnecting ([useRemoteSession.ts:168-175](../../hooks/useRemoteSession.ts)).
- **Pruning `inProgressToolUseIDs` from raw `sdkMessage`:** Because non-`viewerOnly` mode returns `{ type: 'ignored' }` for `user` messages in `convertSDKMessage()`, deleting completed `tool_use_id`s post-conversion never fired—causing an unbounded set growth that showed up in BigQuery as a **5.2× higher RSS slope** for the CCR cohort ([useRemoteSession.ts:244-267](../../hooks/useRemoteSession.ts)).
- **Resetting event-sourced counters on reconnect:** On `onReconnecting`, `runningTaskIdsRef` and `inProgressToolUseIDs` are cleared immediately because missed `task_notification` or `tool_result` events across a WS gap would otherwise leave stale counters and spinners stuck forever ([useRemoteSession.ts:421-431](../../hooks/useRemoteSession.ts)).

---

## 5. Zero-Secret Subprocess Tunneling: The CCR `upstreamproxy/` Relay

### The Problem

Inside a CCR container, the LLM runs arbitrary shell commands (`curl`, `gh`, `kubectl`, Python scripts) that often need to query internal enterprise endpoints (like Datadog with `DD-API-KEY`). Putting org secrets into container environment variables or files violates basic prompt-injection containment: one malicious web page or repo comment instructing the agent to run `env` or `cat` exfiltrates the keys.

Putting a credential-injecting MITM proxy *outside* the container on CCR's server side solves secret isolation—the container never sees `DD-API-KEY`, only a short-lived session token—but hits three concrete systems obstacles:
1. **Heap scraping at the same UID:** If the parent Claude Code process holds `/run/ccr/session_token` in memory while spawning Bash subprocesses under the same Linux UID, a prompt-injected `gdb -p $PPID` could attach via `ptrace` and read the token straight off the heap!
2. **GKE L7 ingress has no raw `CONNECT` matcher:** CCR ingress routes by HTTP path prefix, so subprocesses cannot open raw `CONNECT` tunnels directly to the CCR edge—and direct container egress is blocked behind an egress gateway.
3. **Crash-restart vs. unlink race:** Unlinking `/run/ccr/session_token` too early breaks supervisor retries if CA download or socket bind fails; unlinking it too late exposes the file to the agent loop.

### The Real Implementation

[entrypoints/init.ts:167-183](../../entrypoints/init.ts) dynamically imports `upstreamproxy/` only when `CLAUDE_CODE_REMOTE` is truthy, registers `getUpstreamProxyEnv` into [utils/subprocessEnv.ts:67-90](../../utils/subprocessEnv.ts) (so `Bash`, MCP, LSP, and shell hooks all inherit the proxy env without a static import), and runs `initUpstreamProxy()`. Every step is **fail-open**—a broken proxy setup logs a warning and disables itself rather than breaking the session.

[upstreamproxy/upstreamproxy.ts](../../upstreamproxy/upstreamproxy.ts) executes a tightly ordered six-step bootstrap:

```ts
// upstreamproxy/upstreamproxy.ts:85-145 (abridged)
if (!isEnvTruthy(process.env.CLAUDE_CODE_REMOTE)) return state
// CCR evaluates ccr_upstream_proxy_enabled server-side (fresh containers
// have no warm GrowthBook cache) and injects this env var.
if (!isEnvTruthy(process.env.CCR_UPSTREAM_PROXY_ENABLED)) return state
const token = await readToken(tokenPath) // /run/ccr/session_token
if (!token) return state

setNonDumpable() // Linux prctl(PR_SET_DUMPABLE, 0) via bun:ffi libc.so.6

const baseUrl = opts?.ccrBaseUrl ?? process.env.ANTHROPIC_BASE_URL ?? 'https://api.anthropic.com'
const caOk = await downloadCaBundle(baseUrl, systemCaPath, caBundlePath) // 5s timeout
if (!caOk) return state

const wsUrl = baseUrl.replace(/^http/, 'ws') + '/v1/code/upstreamproxy/ws'
const relay = await startUpstreamProxyRelay({ wsUrl, sessionId, token })
registerCleanup(async () => relay.stop())
state = { enabled: true, port: relay.port, caBundlePath }

// Only unlink AFTER the listener is bound so supervisor restarts can retry on failure.
await unlink(tokenPath).catch(() => { /* warn */ })
```

Look at the security and compatibility engineering packed into those 60 lines:
- **Anti-`ptrace` FFI hardening:** `setNonDumpable()` ([upstreamproxy.ts:225-252](../../upstreamproxy/upstreamproxy.ts)) uses `bun:ffi` to `dlopen('libc.so.6')` and invoke `prctl(PR_SET_DUMPABLE /* 4 */, 0n, 0n, 0n, 0n)` on Linux, blocking same-UID `ptrace`/`/proc/$PPID/mem` heap inspection.
- **CA bundle concatenation:** `downloadCaBundle()` fetches `/v1/code/upstreamproxy/ca-cert` (with an explicit `AbortSignal.timeout(5000)` because Bun has no default fetch timeout) and appends it to `/etc/ssl/certs/ca-certificates.crt` at `~/.ccr/ca-bundle.crt`, then exports all four runtime-specific trust vars (`SSL_CERT_FILE`, `NODE_EXTRA_CA_CERTS`, `REQUESTS_CA_BUNDLE`, `CURL_CA_BUNDLE`).
- **HTTPS-only + multi-runtime `NO_PROXY`:** Only `HTTPS_PROXY`/`https_proxy` are set (never `HTTP_PROXY`—plain HTTP has no credentials to inject and would 405). `NO_PROXY_LIST` bypasses loopback, RFC 1918, IMDS (`169.254.0.0/16`), package registries, GitHub, and **three** forms of Anthropic's domain (`anthropic.com`, `.anthropic.com`, `*.anthropic.com`) because Bun/curl/Go use glob matching while Python `urllib`/`httpx` strip a leading dot ([upstreamproxy.ts:37-63, 185-199](../../upstreamproxy/upstreamproxy.ts)).
- **Nested child CLI inheritance:** If a child CLI process starts after the parent already unlinked `/run/ccr/session_token`, `getUpstreamProxyEnv()` detects inherited `HTTPS_PROXY` + `SSL_CERT_FILE` and passes the 8 proxy/CA env vars straight through to its own subprocesses ([upstreamproxy.ts:161-183](../../upstreamproxy/upstreamproxy.ts)).

#### The CONNECT-over-WebSocket Relay ([upstreamproxy/relay.ts](../../upstreamproxy/relay.ts))

`startUpstreamProxyRelay()` binds `127.0.0.1:0` (using `Bun.listen` under Bun, or Node `net.createServer` with preloaded `ws` under Node—the actual CCR container runtime) and runs a two-phase per-connection state machine:

1. **Phase 1 (CONNECT header parse):** Accumulates bytes until `\r\n\r\n` (capped at 8,192 bytes → `400 Bad Request`), validates `^CONNECT\s+(\S+)\s+HTTP\/1\.[01]$` (otherwise `405 Method Not Allowed`), and stashes any trailing bytes into `st.pending` before calling `openTunnel()`.
2. **Phase 2 (Protobuf-over-WebSocket tunnel):** Opens a WebSocket to `/v1/code/upstreamproxy/ws` routed through the container's egress proxy (`getWebSocketProxyAgent` under Node; `proxy: getWebSocketProxyUrl` under Bun) with two distinct auth layers:
   - **Upgrade headers:** `Authorization: Bearer <token>` (satisfies gateway `PRIVATE_API` auth) and **`Content-Type: application/proto`** (critical scar: without it, the Go server's `stream.go` defaults to `protojson` and fails silently with EOF; [relay.ts:352-359](../../upstreamproxy/relay.ts)).
   - **First tunnel chunk:** Encodes `${connectLine}\r\nProxy-Authorization: Basic base64(sessionId:token)\r\n\r\n` inside a 10-line hand-rolled protobuf message `UpstreamProxyChunk { bytes data = 1; }` (tag `0x0a` + varint length + bytes, zero `protobufjs` dependency; [relay.ts:66-103, 378-385](../../upstreamproxy/relay.ts)).
3. **Chunking and keepalive:** Client payloads are sliced to `MAX_CHUNK_BYTES = 512 * 1024` (Envoy's per-request buffer cap so `git push` works cleanly), and an empty zero-length `UpstreamProxyChunk` is sent every `PING_INTERVAL_MS = 30_000` (inside the 50-second sidecar idle timeout). Server chunks decode back to raw TCP bytes—first `HTTP/1.1 200 Connection Established`, then the MITM'd TLS stream.

### Hidden Invariants & Failure Modes

> [!WARNING]
> **Three low-level socket bugs that `relay.ts` explicitly guards against:**
> 1. **Coalesced `CONNECT` + `ClientHello` (`st.pending`):** TCP can deliver the `CONNECT` headers and initial TLS bytes in one packet (or fire `data` again while the WebSocket upgrade is in flight). `st.pending` buffers all post-header bytes until `ws.onopen` flushes them ([relay.ts:114-118, 327-340, 388-392](../../upstreamproxy/relay.ts)).
> 2. **Never write `502` into an established TLS tunnel (`st.established`):** Before the first server byte arrives, `ws.onerror` returns `HTTP/1.1 502 Bad Gateway\r\n\r\n`. Once `ws.onmessage` delivers payload bytes, `st.established = true` latches so a later error only closes the socket cleanly instead of injecting plaintext HTTP into TLS ([relay.ts:120-126, 405-420](../../upstreamproxy/relay.ts)).
> 3. **Bun partial TCP writes (`writeBuf` + `drain`):** Unlike Node's `net.Socket` (which buffers unconditionally), Bun's `sock.write()` returns the exact byte count accepted by the kernel and **silently drops the remainder**. `startBunRelay()` maintains a per-socket `writeBuf: Uint8Array[]` tail queue flushed in the `drain` callback ([relay.ts:181-226](../../upstreamproxy/relay.ts)).

---

## Putting the Layer Together

Every remote capability in Claude Code combines one of three topologies over the same NDJSON SDK/control protocol from Chapter 23:

```mermaid
flowchart LR
  subgraph LocalHost["Local Workstation"]
    REPL["Ink REPL + useReplBridge"]
    Perm["interactiveHandler (Race 4)"]
    Daemon["bridgeMain (1..32 children)"]
    Child["child --print --sdk-url (RemoteIO)"]
    Viewer["Ink REPL (useRemoteSession / useDirectConnect)"]
    REPL <--> Perm
    Daemon -->|"stdin token refresh / stdout snoop"| Child
  end

  subgraph Cloud["Anthropic Cloud (CCR / Session-Ingress)"]
    EnvAPI["Environments API (v1 poll/ack/hb)"]
    BridgeAPI["POST /v1/code/sessions/{id}/bridge (v2)"]
    Ingress["Session-Ingress WS+POST (v1) / CCR SSE+POST (v2)"]
    SubWS["SessionsWebSocket + POST /events"]
    Web["claude.ai / iOS / Android"]
    EnvAPI --> Ingress
    BridgeAPI --> Ingress
    Ingress <--> Web
    Ingress <--> SubWS
  end

  subgraph Container["CCR Container (or claude server)"]
    RemoteAgent["Remote cc Worker (RemoteIO)"]
    Relay["upstreamproxy 127.0.0.1 CONNECT->WS"]
    Subproc["Untrusted Bash / curl / gh"]
    Subproc -->|"HTTPS_PROXY + CA bundle"| Relay
    RemoteAgent -->|"prctl non-dumpable + unlink token"| Relay
  end

  REPL <-->|"ReplBridgeTransport (v1 Hybrid or v2 SSE+CCRClient)"| Ingress
  Child <-->|"HybridTransport or SSETransport + CCRClient"| Ingress
  Viewer <-->|"RemoteSessionManager (WS + POST)"| SubWS
  Viewer <-->|"DirectConnectSessionManager (single WS)"| RemoteAgent
  RemoteAgent <-->|"SSE + CCRClient"| Ingress
  Relay -->|"UpstreamProxyChunk proto over WS"| Cloud
```

Comparing all five remote modes side by side makes their architectural trade-offs explicit:

| Mode | Entrypoint / Manager | Auth & Session Setup | Read / Write Transports | Permission Path |
| :--- | :--- | :--- | :--- | :--- |
| **REPL Bridge (v1 env-based)** | `initReplBridge` → `initBridgeCore` (`replBridge.ts`) | OAuth → `POST /v1/environments/bridge` + poll/ack/hb | `HybridTransport` (WS + POST) or CCR v2 `SSE + CCRClient` | Race 4 in `interactiveHandler` (`BridgePermissionCallbacks`) |
| **REPL Bridge (v2 env-less)** | `initReplBridge` → `initEnvLessBridgeCore` (`remoteBridgeCore.ts`, `tengu_bridge_repl_v2`) | OAuth (+ Trusted Device) → `POST /v1/code/sessions/{id}/bridge` → `worker_jwt` + `worker_epoch` | `SSETransport` + `CCRClient` (rebuilt on proactive refresh / 401) | Race 4 + `reportState('requires_action' ↔ 'running')` |
| **Standalone / Daemon Bridge** | `entrypoints/cli.tsx` → `bridgeMain` / `runBridgeHeadless` (`bridgeMain.ts`) | OAuth env poll → spawns 1–32 `--sdk-url` children (worktree or same-dir) | Child `RemoteIO` (`HybridTransport` or `SSE + CCRClient`); stdin JWT rotation | Child emits `can_use_tool` to CCR + echoes to parent stdout |
| **Remote CCR Viewer** | `useRemoteSession` → `RemoteSessionManager` (`remote/`) | OAuth Bearer on WS + HTTP POST | `SessionsWebSocket` reads + `POST /v1/sessions/{id}/events` writes | Local Ink `ToolUseConfirm` via `createToolStub` + WS `control_response` |
| **Direct Connect** | `useDirectConnect` → `DirectConnectSessionManager` (`server/`, `feature('DIRECT_CONNECT')`) | Optional Bearer → `POST /sessions` → `{ws_url}` | Single bidirectional NDJSON WebSocket | Local Ink `ToolUseConfirm` via `createToolStub` + WS `control_response` |

---

## How This Snaps Into the Next Layer

Chapter 24 concludes our 24-chapter bottom-up climb through Claude Code—from Layer 0 primitives ([Chapter 01](01-atoms-types-stores-and-primitives.md)) and the tool/command/prompt contracts (Layers 1–2), through the streaming `query()` loop, compaction, memory, permissions, sandboxing, hooks, configuration, MCP, skills, background tasks, subagents, and swarms (Layers 3–6), into the custom Ink terminal renderer and interactive REPL (Layer 7), and finally out through cold-start bootstrapping, headless SDK protocols, and the remote wire protocols in this chapter (Layer 8).

From here, navigate to the book's reference companions:
- **[ARCHITECTURE_MAP.md](../ARCHITECTURE_MAP.md)** — complete directory-to-layer index tying every major module in the repository back to its chapter.
- **Planned Appendices (tracked in [OUTLINE.md](../OUTLINE.md)):**
  - *Appendix A* — Complete inventory of compile-time `feature()` flags (like `BRIDGE_MODE`, `CCR_MIRROR`, `CCR_AUTO_CONNECT`, `DIRECT_CONNECT`, `SSH_REMOTE`) and environment knobs.
  - *Appendix B* — Reconstructing the snapshot's absent interface boundaries (`types/message.ts`, `query/transitions.ts`, `cli/transports/Transport.ts`, `entrypoints/sdk/controlTypes.ts`, and the `server/` host files) from call sites.
  - *Appendix C* — A 500-line working mini-harness blueprint distilling the core loop, tool contract, permission gate, and transport patterns from Chapters 01–24.

---

## Reading Exercises & Code Checkpoints

1. **Trace all transport selection and epoch-mismatch paths:**
   ```bash
   rg -n "CLAUDE_CODE_USE_CCR_V2|CLAUDE_CODE_POST_FOR_SESSION_INGRESS_V2|onEpochMismatch" cli/ bridge/
   ```
   Verify why `CCRClient`'s default `onEpochMismatch` calls `process.exit(1)` while `createV2ReplTransport` overrides it to emit synthetic close code `4090` and throw `'epoch superseded'`.

2. **Audit every racer in the interactive permission engine:**
   Open [hooks/toolPermission/handlers/interactiveHandler.ts](../../hooks/toolPermission/handlers/interactiveHandler.ts) and trace every call to `claim()` and `bridgeCallbacks.cancelRequest()`. Notice why `onAllow`/`onReject`/`onAbort` call *both* `sendResponse()` and `cancelRequest()`, whereas hooks, the bash classifier, and MCP channel replies call only `cancelRequest()`.

3. **Verify the `cse_*` vs. `session_*` retagging boundary:**
   ```bash
   rg -n "toCompatSessionId|toInfraSessionId|sameSessionId" bridge/
   ```
   Trace which endpoints require `cse_*` (infrastructure / CCR v2 worker paths) versus `session_*` (compat `/v1/sessions/*` archive and title endpoints), and see how `setCseShimGate()` avoids pulling `growthbook.ts` into the SDK bundle.

4. **Inspect the `upstreamproxy/` trust boundary end-to-end:**
   Read [entrypoints/init.ts:161-184](../../entrypoints/init.ts), [utils/subprocessEnv.ts:64-99](../../utils/subprocessEnv.ts), and [upstreamproxy/upstreamproxy.ts:112-199](../../upstreamproxy/upstreamproxy.ts) together. Confirm why `unlink(tokenPath)` runs *after* `startUpstreamProxyRelay()` resolves, how child CLI processes still reach the parent's relay after the token file is gone, and why `relay.ts` refuses to emit `HTTP/1.1 502` once `st.established` flips to `true`.


---

<!-- chapters/25-bringing-it-to-the-present.md — https://reverseengineeringclaudecode.com/chapters/25-bringing-it-to-the-present -->

# Chapter 25 — Bringing It to the Present: From 2.1.88 to 2.1.331

> **Layer:** All layers (Layers 0–8), viewed across eight months of releases
> **Prerequisites:** [Chapter 00](00-how-to-read-a-1900-file-agent.md), and ideally the chapter that covers each layer you care about. This chapter links back to each one.
> **Primary Evidence Sources:**
> - The 2.1.88 source snapshot this book is written against (repository root, for example [Tool.ts](../../Tool.ts), [query.ts](../../query.ts), [entrypoints/sdk/coreTypes.ts](../../entrypoints/sdk/coreTypes.ts), [types/permissions.ts](../../types/permissions.ts), [constants/betas.ts](../../constants/betas.ts))
> - The public Claude Code changelog, sections `2.1.89` through `2.1.331`
> - The JavaScript modules embedded in the shipped native binary for **2.1.331** (build time `2026-11-23T15:17:48Z`), carved out of the binary's `__BUN` section
> - The earlier binary audit of **2.1.296**: [2026-10-11-claude-code-2.1.296-workflows-binary-audit.md](../../2026-10-11-claude-code-2.1.296-workflows-binary-audit.md) and [2026-10-11-workflow-surface-audit.md](../../2026-10-11-workflow-surface-audit.md)

---

## Why This Chapter Exists

Chapters 00 through 24 describe one build of Claude Code: 2.1.88, published on 2026-03-31. That build is a fixed point, and it is the only version whose TypeScript source, comments, and file layout we can read. Claude Code has kept shipping since then. The changelog adds roughly 240 release sections after 2.1.88. The build installed on our machine as we write this reports itself as:

```text
$ ~/.local/share/claude/versions/2.1.331 --version
2.1.331 (Claude Code)
```

A reader who finishes this book and then opens the current product will find most of the architecture where the book left it. They will also find whole subsystems that the snapshot only hinted at behind `feature()` gates, a handful of features that are gone, and new layers of policy, caching, and orchestration on top. This chapter maps that drift onto the book's nine-layer model.

We can't do that with the same certainty as the other 24 chapters, because we don't have the later source. Every claim in this chapter therefore carries an evidence label.

### The Evidence Legend

| Tag | Meaning | How strong |
| :--- | :--- | :--- |
| **[CL x.y.z]** | The public changelog says so, under release `x.y.z`. | What Anthropic chose to announce. It doesn't cover internals, and a "Removed" line doesn't always mean the code is gone. |
| **[BIN-331]** | We saw it in the modules extracted from the shipped 2.1.331 binary. Where it helps, we name the string, the property name, or the hashed chunk file it came from (for example `chunk-g0g3fmj2.js`). | Strong for "this string or shape exists in the build". Weak for "this code path runs for you", because the runtime gates are invisible to us. |
| **[BIN-296]** | We saw it in the earlier extraction of 2.1.296, as written up in the workflow audits in this repository. | Same strength as BIN-331, for an earlier build. |
| **[SNAP]** | We read it in the 2.1.88 source in this repository. | The book's normal standard. |
| **[SPEC]** | Our inference. The text always says what the inference rests on. | Plausible, unconfirmed. |

> [!IMPORTANT]
> Chunk file names such as `chunk-aczeq1a4.js` are content hashes that the bundler assigns at build time. They locate evidence inside the 2.1.331 build only. They change in every release, so treat them as coordinates, not as names.

---

## 1. How We Know What We Know

### The Problem

A source snapshot, a changelog, and a compiled binary are three different kinds of evidence. They fail in different ways, and they don't line up on their own.

- **The snapshot** has everything a reverse engineer wants: file paths, type names, comments that explain the scars (Chapter 00's `DANGEROUS_uncachedSystemPromptSection`, Chapter 07's withheld-error ladder). It also has holes. `types/message.ts`, `query/transitions.ts`, and `services/contextCollapse/` are imported but missing, and many modules sit behind `feature('...')` and `USER_TYPE === 'ant'` gates that external builds strip out.
- **The changelog** is complete and dated, but it is written for users. It says "Added dynamic workflows". It doesn't say which file owns the scheduler.
- **The binary** is what actually ships. It is also minified, its comments are gone, its module boundaries are redrawn by the bundler, and it still contains code that is gated off at run time.

### What a Bun Binary Gives Up

Native Claude Code installs have been bun-compiled executables since the CLI "changed … to spawn a native Claude Code binary (via a per-platform optional dependency) instead of bundled JavaScript" **[CL 2.1.113]**. The 2.1.331 file is a 381 MB arm64 Mach-O. Its JavaScript lives in a segment named `__BUN`.

We followed the extraction runbook in `coder-two-tools/docs/cc/extract-installed-cli.md`. Step 6 worked: `unbunjs list --json` read the module table and reported **3,857 modules** in a 237 MB payload, with one entry point, `/$bunfs/root/cli` **[BIN-331]**. Step 7 did not work. `unbunjs extract` misread each module's bytecode length on this Bun layout and began writing a `.bytecode` file of roughly 125 MB beside every chunk. It had filled the disk before we stopped it and deleted the output. We then carved the source text directly. Each module record in the `list` output carries a `contents_offset` and `contents_length` relative to `payload_start`, so a 20-line script could seek and copy each module. That produced 81 MB of source. The carved copy of a module that `unbunjs` had written correctly before it failed (`chunk-dkgv0tv2.js`) matched byte for byte.

> [!WARNING]
> If you repeat this on a later build, run `unbunjs list` first and check whether `bytecode_length` is plausible. In 2.1.331 it reported values around 131 MB per module, which can't be right. Carve the `contents` ranges yourself rather than running a full `extract`.

What the carve recovers:

- **3,609 JavaScript chunks**, minified, with hashed names. Only one original source path survived: `src/plugins/functionHooks/hooks-worker/hooks-worker.js`.
- **String literals and object property names, intact.** Minification renames local bindings, but `isConcurrencySafe`, `"aborted_streaming"`, `"PreToolUse"`, and every `tengu_*` event name survive. This chapter leans on them.
- **Bundled assets**: 135 zstd-compressed files and 75 Markdown files (skills, API reference docs, workflow templates), plus a 925 KB TypeScript declaration file for the plugin hook API (`claude-code.d.ts-32067a2b.txt`) **[BIN-331]**.
- **React Compiler output.** Components still carry the memo-cache arrays Chapter 00 described (`if(U[19]!==L||U[20]!==J)…U[21]=ae`) and the `react.memo_cache_sentinel` symbol **[BIN-331]**.

What it can't recover:

- **Names of local functions and modules.** `query()` and `queryLoop()` don't exist by name; we find them by their parameter shapes.
- **Comments.** The "why" that fills Chapters 01–24 is gone. Where this chapter explains *why*, that is **[SPEC]** unless the changelog says it.
- **Run-time gates.** Bun's compile-time `feature()` calls are already resolved. The leftovers are visible as empty spreads: the `/config` category table in `chunk-05hpdrv2.js` contains `"remoteHomeSettings",...[],...[],"dialogExpiry"` **[BIN-331]**, which is what `...(feature('X') ? [...] : [])` compiles to when `X` is off. GrowthBook gates are a different matter. They remain as `tengu_*` strings, and we can't tell which ones are on for any given account. The bundle has 4,225 distinct `"tengu_…"` strings, against 817 in the snapshot **[BIN-331, SNAP]**. That count includes both telemetry event names and flag names.

### Scale

| Build | Embedded modules | Source |
| :--- | :--- | :--- |
| 2.1.88 snapshot | ~1,884 TypeScript/TSX files (not bundled) | **[SNAP]** |
| 2.1.270 | 1,879 modules | runbook, **[BIN]** |
| 2.1.296 | 2,609 modules | **[BIN-296]** |
| 2.1.331 | 3,857 modules (3,609 `.js`) | **[BIN-331]** |

The module counts aren't comparable to the file count, because the bundler splits and merges modules freely. Still, the bundle grew by about half between 2.1.296 and 2.1.331, a span of six weeks.

---

## 2. The Timeline: Five Eras

We group 240 releases into five eras. The boundaries are our editorial choice **[SPEC]**. Every milestone in the table is quoted from the changelog.

| Era | Releases | Milestones (all **[CL]**) |
| :--- | :--- | :--- |
| **1. Unflagging the snapshot** | 2.1.89 – 2.1.113 | 2.1.89: `CLAUDE_CODE_NO_FLICKER=1` alt-screen renderer, `/buddy`. 2.1.92: removed `/tag` and `/vim`. 2.1.98: Monitor tool. 2.1.110: `/tui fullscreen`. 2.1.111: auto mode no longer requires `--enable-auto-mode`, PowerShell tool rollout. 2.1.113: native binary. |
| **2. Native build, orchestration debut** | 2.1.117 – 2.1.160 | 2.1.117: `Glob`/`Grep` replaced by embedded `bfs`/`ugrep` on native macOS/Linux. 2.1.139: agent view (`claude agents`), `/goal`. 2.1.152: `MessageDisplay` hook. 2.1.154: dynamic workflows, streaming tool execution always on, lean system prompt default. 2.1.160: trigger keyword renamed `workflow` → `ultracode`. |
| **3. Background by default** | 2.1.172 – 2.1.248 | 2.1.178: removed `TeamCreate`/`TeamDelete`. 2.1.198: subagents run in the background by default. 2.1.200: "default" mode renamed "Manual". 2.1.222: removed ultraplan. 2.1.224: `claude self-hosted-runner`, cross-session `SendMessage`. 2.1.232: fork subagents on by default. 2.1.243: zstd-compressed binary. 2.1.248: workflow reference moved into a `workflow-authoring` skill. |
| **4. Cache, policy, and mods** | 2.1.251 – 2.1.287 | 2.1.251: `PreModelSwitch`/`PostModelSwitch` hooks. 2.1.267: deferred mid-session MCP/plugin tools for cache reuse. 2.1.277: AGENTS.md support, TaskOutput removed. 2.1.278: server-side auto-mode classifier by default. 2.1.284: interactive sessions start in auto mode. 2.1.287: Claude Mods. |
| **5. Code Mode and hardening** | 2.1.288 – 2.1.331 | 2.1.299: idle compaction. 2.1.302: fork subagents on by default in `-p` and the SDK. 2.1.314: `permissions.blockWritesOutsideWorkingDirectories`. 2.1.323: Code Mode, v1 MCP client removed. 2.1.325: sandboxed Bash no longer auto-allowed. 2.1.330: easel chart mod. |

```mermaid
flowchart LR
    S["2.1.88 snapshot<br/>(this book)"] --> E1["Era 1<br/>2.1.89–2.1.113<br/>flags become features"]
    E1 --> E2["Era 2<br/>2.1.117–2.1.160<br/>native binary, workflows"]
    E2 --> E3["Era 3<br/>2.1.172–2.1.248<br/>background by default"]
    E3 --> E4["Era 4<br/>2.1.251–2.1.287<br/>cache, policy, mods"]
    E4 --> E5["Era 5<br/>2.1.288–2.1.331<br/>Code Mode, hardening"]
    B1["BIN-296 audit"] -.-> E4
    B2["BIN-331 extract"] -.-> E5
```

A pattern runs through all five eras: **features that sat behind a snapshot `feature()` gate ship, change names, and then turn into defaults.** Auto mode is the clearest case. In the snapshot it is `feature('TRANSCRIPT_CLASSIFIER')` in [types/permissions.ts](../../types/permissions.ts) **[SNAP]**. It then lost its command-line flag **[CL 2.1.111]**, lost its consent step **[CL 2.1.152]**, gained a server-side classifier by default **[CL 2.1.278]**, and became the starting mode of interactive sessions **[CL 2.1.284]**.

---

## 3. Layer by Layer

### Layer 0 — Leaf Atoms ([Chapter 01](01-atoms-types-stores-and-primitives.md))

Little here is visible from outside, which is what you'd expect of primitives.

- **Runtime.** The bundled Bun was upgraded to 1.4 **[CL 2.1.181]**. The binary is now zstd-compressed, "about 75 MB instead of 340 MB on Linux x64" **[CL 2.1.243]**. The compile flags recorded in the module table disable autoloading of `bunfig`, `tsconfig`, `package.json`, and default `.env` files, and the embedded `exec_argv` includes `--zero-fill-buffers` and `--no-crash-report-upload` **[BIN-331, modules.json]**.
- **Concurrent writers to `~/.claude.json`.** The process-wide config file from Chapter 01 became a source of real bugs once many sessions ran at once: "concurrent sessions silently reverting each other's `~/.claude.json` changes" **[CL 2.1.259]**, user settings "lost when several Claude Code processes saved them at the same time" **[CL 2.1.330]**. **[SPEC]** Background sessions, agent view, and cross-session messaging made a single-writer assumption false that was true enough in 2.1.88.
- **Transcripts.** Edit-heavy transcripts shrank "up to 79x" **[CL 2.1.208]**. Local transcripts now "also record each API request's system prompt, tools and parameters" **[CL 2.1.300]**. This one crosses into Layer 2: once the transcript records the prompt it sent, a resumed session can reuse those exact bytes, and the cache prefix stays stable.

### Layer 1 — Tool, Command, and Message Contracts ([Chapter 02](02-the-tool-contract.md), [Chapter 03](03-command-and-message-contracts.md))

**The `Tool` contract survived almost character for character.** The snapshot's `TOOL_DEFAULTS` in [Tool.ts:757-769](../../Tool.ts) defines `isEnabled`, `isConcurrencySafe`, `isReadOnly`, `isDestructive`, `checkPermissions`, `toAutoClassifierInput`, and `userFacingName` **[SNAP]**. The 2.1.331 bundle has:

```js
var yo={isEnabled:()=>!0,isConcurrencySafe:(e)=>!1,isReadOnly:(e)=>!1,
  isDestructive:(e)=>!1,remoteExecution:aIs,toAutoClassifierInput:(e)=>"",
  userFacingName:(e)=>""};
```

That is `chunk-g0g3fmj2.js` **[BIN-331]**. The fail-closed defaults Chapter 02 called out (`isConcurrencySafe → false`, `isReadOnly → false`) are unchanged. Two things moved:

1. `checkPermissions` is no longer a default. The adapter around it supplies the allow-by-default answer (`Promise.resolve({behavior:"allow",updatedInput:r})`) only when the tool doesn't define one **[BIN-331]**.
2. A new default, `remoteExecution: Object.freeze({supported:!1})`, sits beside a `backgrounding` accessor that defaults to `"never"` **[BIN-331]**. **[SPEC]** Tools now declare whether they can run on another machine and whether they can move to the background. Both are axes the 2.1.88 contract didn't have.

**A second tool shape sits on top of the first.** The same chunk has a wrapper that takes a definition with a `create(context)` factory and adapts it to the classic `call` / `validateInput` / `checkPermissions` interface. Its per-call context exposes fields such as `runEngine`, `ask`, `sameTurnToolUses`, `remoteCall`, and `inputFromAnotherMachine`. When a runner owns the tool, the wrapper refuses a call whose location changed after its permission check, with the message "`… was not run: where it runs changed after its permission was checked. Send the call again.`" Property names such as `underlyingV1ToolName` and `familyParentToolName` appear across 12 chunks **[BIN-331]**. **[SPEC]** There is a "v2" tool definition style that is translated into the v1 shape this book describes. The query loop and the permission engine still see v1 tools, which is why the seam held.

**The built-in tool roster changed.** Names we found in the bundle **[BIN-331]**: `Agent`, `Artifact`, `AskUserQuestion`, `Bash`, `Brief`, `CronCreate`, `Edit`, `EndConversation`, `EnterPlanMode`, `EnterWorktree`, `ExitPlanMode`, `ExitWorktree`, `Glob`, `Grep`, `ListAgents`, `LSP`, `Monitor`, `NotebookEdit`, `PowerShell`, `PushNotification`, `Read`, `RemoteTrigger`, `ScheduleWakeup`, `SendFeedback`, `SendMessage`, `Skill`, `StructuredOutput`, `TaskCreate`, `TaskStop`, `TodoWrite`, `ToolSearch`, `WebFetch`, `WebSearch`, `Workflow`, `Write`.

- **Added since 2.1.88:** Monitor **[CL 2.1.98]**, PushNotification ("Added a push notification tool" **[CL 2.1.110]**, gated in the bundle by `tengu_kairos_push_notifications` **[BIN-331]**), EndConversation **[CL 2.1.214]**, SendFeedback **[CL 2.1.247]**, cross-session ListAgents **[CL 2.1.224]**, and Workflow (see Layer 6).
- **Removed:** TaskOutput ("Removed the deprecated TaskOutput tool; Claude reads a background task's output file with Read instead" **[CL 2.1.277]**), and TeamCreate/TeamDelete **[CL 2.1.178]**. Both names still appear in the bundle, in one `Set`: `["Frame","FrameRead","TeamCreate","TeamDelete","SuggestBackgroundPR","AutofixPr","TaskOutput","AgentOutputTool","BashOutputTool","AgentOutput","BashOutput"]` (`chunk-dkgv0tv2.js`) **[BIN-331]**. The set is consulted when replaying recorded tool names and is skipped in the "no loaded tool" consistency warning. **[SPEC]** It is a list of retired tool names kept so that old transcripts resume without errors. It also hints at tools the changelog never named (`Frame`, `FrameRead`, `SuggestBackgroundPR`).
- **Narrowed:** the todo/task tools "are no longer available on Opus 4.8, Sonnet 5, Fable 5, Mythos 5, and newer models" unless `CLAUDE_CODE_ENABLE_TODO_TOOLS=1` **[CL 2.1.233]**. On native macOS/Linux builds, `Glob` and `Grep` are "replaced by embedded `bfs` and `ugrep` available through the Bash tool" **[CL 2.1.117]**. The tool names remain in the bundle for Windows and npm builds **[BIN-331]**.

**Commands.** The three-way `prompt | local | local-jsx` union from Chapter 03 is still how commands are written: we found literal `type:"local-jsx"` command objects with `name`, `description`, `argumentHint`, `availability`, `isEnabled`, and a lazy `load:()=>…` **[BIN-331]**, the same fields as [types/command.ts](../../types/command.ts) **[SNAP]**. Commands that changed:

- **Removed:** `/tag` and `/vim` ("toggle vim mode via `/config` → Editor mode") **[CL 2.1.92]**. Neither has a `name:"tag"` or `name:"vim"` command object in 2.1.331. `editorMode` and `vimInsertModeRemaps` settings remain **[BIN-331]**.
- **Merged or renamed:** `/cost` and `/stats` merged into `/usage` **[CL 2.1.118]**. `/undo` became an alias of `/rewind` **[CL 2.1.108]**. `/simplify` was renamed `/code-review` **[CL 2.1.147]**, then returned as a cleanup-only review **[CL 2.1.154]**.
- **Opened to the model:** "The model can now discover and invoke built-in slash commands like `/init`, `/review`, and `/security-review` via the Skill tool" **[CL 2.1.108]**. Commands and skills now share one surface the model can call.

**Message normalization.** `normalizeMessagesForAPI()` from Chapter 03 caused a performance regression: "message normalization cost grew quadratically with the number of turns, causing multi-second stalls and slow resumes" **[CL 2.1.216]**.

### Layer 2 — The Agent Engine ([Chapters 04–08](04-prompt-engineering-and-cache-boundaries.md))

**The query loop is still an `AsyncGenerator` state machine.** The loop isn't named in the bundle, but it is easy to find by shape. `chunk-aczeq1a4.js` (318 KB minified, against 69 KB for the commented [query.ts](../../query.ts)) contains `async function*` declarations taking `{…toolUseContext, querySource, cacheSafeParams, snipTokensFreed, sentSystemPrompt, sentInlineTools}`. It holds 109 `yield*` delegations, 14 uses of `needsFollowUp`, and calls to `streamingToolExecutor.takeFinishedResults()`, `addTool(`, and `getRemainingResults` **[BIN-331]**. These are the names Chapter 07 traced through `query.ts:1411-1728` **[SNAP]**.

**The terminal-reason union grew.** The snapshot's `query.ts` returns reasons including `completed`, `max_turns`, `aborted_streaming`, `aborted_tools`, `blocking_limit`, `prompt_too_long`, `image_error`, `model_error`, `hook_stopped`, and `stop_hook_prevented` **[SNAP]**. A 2.1.331 helper (`chunk-5d8pv3g2.js`) sorts reasons into errors and non-errors **[BIN-331]**:

| Reason class | 2.1.331 members |
| :--- | :--- |
| Error-like | `blocking_limit`, `rapid_refill_breaker`, `prompt_too_long`, `image_error`, `model_error`, `api_error`, `malformed_tool_use_exhausted`, `budget_exhausted`, `structured_output_retry_exhausted`, `tool_deferred_unavailable`, `turn_setup_failed` |
| Not errors | `aborted_streaming`, `aborted_tools`, `stop_hook_prevented`, `hook_stopped`, `tool_deferred`, `max_turns`, `background_requested`, `completed` |

Every 2.1.88 reason survived. The additions map onto changelog entries: `rapid_refill_breaker` is the autocompact thrash detector ("detects when context refills to the limit immediately after compacting three times in a row" **[CL 2.1.89]**). `tool_deferred` pairs with the PreToolUse `"defer"` decision that the snapshot already had. **[SPEC]** `background_requested` likely backs send now, which moves "running tools to the background instead of cancelling the turn" **[CL 2.1.281]**. Two continuation transitions from the snapshot, `collapse_drain_retry` and `token_budget_continuation`, don't appear anywhere in the bundle **[BIN-331]**. **[SPEC]** The first follows from context collapse disappearing (Layer 3). The second suggests the snapshot's `checkTokenBudget()` continuation was replaced by the hard `budget` ceiling that workflows share ("hard ceiling (further `agent()` calls throw)" **[BIN-296]**) and the new `budget_exhausted` terminal.

**Streaming tool execution is now unconditional.** Chapter 06 described `StreamingToolExecutor` as gated. The changelog says: "Streaming tool execution is now always enabled, including when telemetry is disabled or on Bedrock/Vertex/Foundry (previously behind a feature flag)" **[CL 2.1.154]**. A related rule in the batch partitioner changed: "A failed Bash command in a parallel batch no longer cancels its sibling calls" **[CL 2.1.161]**.

**Cache-boundary discipline got stricter, not looser.** Chapter 04 built its argument on `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` and on keeping prefix bytes stable. In 2.1.331 the literal `"__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__"` still exists, in the same chunk as the hook-event list (`chunk-bp2w4xmq.js`) **[BIN-331]**, and it is now a public contract: "a `--system-prompt` that contains a `__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__` line: the text above it is now cached globally" **[CL 2.1.275]**. Most of the cache work since 2.1.88 is repair of places that broke the prefix:

- "`--resume` causing a full prompt-cache miss when deferred tools, MCP servers or custom agents are present" **[CL 2.1.90]**.
- `--exclude-dynamic-system-prompt-sections` "for improved cross-user prompt caching" **[CL 2.1.98]**.
- "mid-session MCP and plugin tools … now receive them as deferred definitions" instead of being appended to the tool list **[CL 2.1.267]**. This is Chapter 15's ToolSearch deferral, reused as a cache-preservation tool.
- `/fork` keeps the cache "because its worktree briefing arrives as a message, not a system-prompt change" **[CL 2.1.257]**.
- Workflow fan-outs "stagger same-prefix sibling agents so subsequent agents read the cached prompt prefix" **[CL 2.1.229]**.
- `/cost` and the status line report "a likely cause for prompt-cache misses" **[CL 2.1.260]**.
- Cache lifetime became configurable: `ENABLE_PROMPT_CACHING_1H` **[CL 2.1.108]**, then `promptCacheTtl` and `subagentPromptCacheTtl` **[CL 2.1.243]**.

The API beta headers tell the same story. The snapshot's [constants/betas.ts](../../constants/betas.ts) lists 17 dated betas **[SNAP]**. The 2.1.331 table in `chunk-y30r659v.js` registers 44 key/value pairs **[BIN-331]**. It keeps `prompt-caching-scope-2026-01-05`, the beta behind Chapter 04's `scope: 'global'`, and adds `prompt-caching-evict-2026-05-12`, `cache-keepalive-2026-09-03`, `cache-diagnosis-2026-04-07`, `context-hint-2026-04-09`, `mid-conversation-tool-changes-2026-07-01`, `inline-tools-2026-09-15`, `thinking-resumption-2026-07-17`, `resumption-2026-10-08`, `server-side-fallback-2026-06-01`, `auto-mode-classifier-2026-07-16`, `subagent-review-2026-11-17`, and `message-threads-2026-08-12`, among others. Three snapshot betas are gone from the whole bundle: `token-efficient-tools-2026-03-28`, `summarize-connector-text-2026-03-13`, and `cli-internal-2026-02-09` **[BIN-331]**. **[SPEC]** Several cache concerns moved onto the server between 2.1.88 and 2.1.331 (keepalive, eviction, diagnosis, mid-conversation tool changes). Without them, the client would have to manage those prefix bytes itself.

**Models, retries, and the API client (Chapter 05).** The `withRetry` machinery gained a watchdog family (`CLAUDE_CODE_RETRY_WATCHDOG` **[CL 2.1.186]**, `CLAUDE_CODE_RETRY_WATCHDOG_MAX_WAIT_MS` **[CL 2.1.295]**) and a cap: "One limit covers a whole model call, at most 14 requests" **[CL 2.1.286]**. Fallback became a setting: `fallbackModel` "(up to three fallbacks tried in order)" **[CL 2.1.166]**. A stalled stream "now aborts after 5 minutes of no data and retries without streaming" **[CL 2.1.105]**. Non-interactive sessions "automatically continue a response cut off mid-stream" **[CL 2.1.246]**. The system prompt itself forked: "The lean system prompt is now the default for all models except Haiku, Sonnet, and Opus 4.7 and earlier" **[CL 2.1.154]**.

### Layer 3 — Compaction and Memory ([Chapter 09](09-five-layer-compaction-pipeline.md), [Chapter 10](10-memory-systems-claudemd-auto-memory-and-dream.md))

Chapter 09's five-stage pipeline (tool-result budget → snip → microcompact → context collapse → autocompact) is where the evidence is most mixed. We go stage by stage, using telemetry event names present in the snapshot and in 2.1.331 as the main evidence.

| Snapshot stage | 2.1.331 evidence | Verdict |
| :--- | :--- | :--- |
| Tool-result budget | `tengu_message_level_tool_result_budget_enforced` and `tengu_tool_result_persisted_message_budget` in both builds **[SNAP, BIN-331]** | Present |
| Snip (`HISTORY_SNIP`) | `snipEnabled` and `snipDebug` listed under an `Internal:` `/config` category; `snipTokensFreed` still a query-loop parameter. `tengu_snip_resume_filtered` gone **[BIN-331]** | Present, still internal **[SPEC]** |
| Microcompact | `tengu_time_based_microcompact` and the `microcompact_boundary` system subtype present. `tengu_cached_microcompact` gone **[BIN-331]** | Time-based variant present; cached variant not visible |
| Context collapse | `services/contextCollapse/` was already absent from the snapshot **[SNAP]**. No `collapse_drain_retry` and no context-collapse identifiers in 2.1.331 **[BIN-331]** | Not visible. **[SPEC]** Never shipped externally, or removed |
| Autocompact | `tengu_compact`, `tengu_auto_compact_succeeded`, plus new `tengu_auto_compact_rapid_refill_breaker`, `…_routed_reactive`, `…_put_off`, `…_window_in_force` **[BIN-331]** | Present, much expanded |

On top of the five stages, three new ones have arrived:

1. **Idle compaction.** "a 200K+ token conversation left idle for about 54 minutes is compacted before its one-hour prompt cache expires, so your next message doesn't reprocess it all" **[CL 2.1.299]**. The bundle has `tengu_idle_compact_fired`, `tengu_idle_compact_settled`, and `idleCompaction` in the "Model & output" `/config` group **[BIN-331]**. The trigger is the cache TTL, not the context limit, which makes this a Layer 2 cache concern implemented in Layer 3.
2. **Precomputed compaction.** It isn't in the changelog. The bundle has ten `tengu_precomputed_compact_*` events (`started`, `ready`, `consumed`, `discarded`, `rehydrated`, …) and a `precomputeCompactionEnabled` setting in the "Experimental" `/config` group, read with default `true` in startup telemetry (`El("precomputeCompactionEnabled",!0)`) **[BIN-331]**. **[SPEC]** A summary is prepared in the background ahead of need and swapped in when the threshold hits, which hides compaction latency the way `preconnectAnthropicApi()` hides TLS latency in Chapter 22.
3. **Server-side compaction.** The bundle carries a `"compact_20260112"` context-management edit type next to the snapshot's `clear_tool_uses_20250919` and `clear_thinking_20251015` **[BIN-331, SNAP]**. The changelog only touches the edge of it: a conversation "too long for the client-side safety classifier to review … is now compacted" **[CL 2.1.288]**, and the same for "the server-side classifier" **[CL 2.1.302]**.

Compaction also became a hookable, policy-bearing event. PreCompact "can now block compaction" **[CL 2.1.105]**, and its output is "cut at 10,000 characters" **[CL 2.1.314]**. A fix stopped automatic compaction "reusing the session's earlier system prompt instead of rebuilding it the way `/compact` does" **[CL 2.1.328]**.

**Memory.** Chapter 10's four systems drifted unevenly:

- **CLAUDE.md** gained a sibling: "in a project with no CLAUDE.md, Claude Code reads AGENTS.md instead" **[CL 2.1.277]**. Path-scoped rules and nested CLAUDE.md now load on Write, Edit, and single-file Bash reads, not only on Read **[CL 2.1.288, 2.1.293]**.
- **Auto-memory (`memdir/`)** survives and grew. The snapshot's `tengu_memdir_*` events are all present, and new ones appear, such as `tengu_memdir_index_backfilled` and `tengu_memdir_write_lint` **[BIN-331]**. A family of more than 20 `tengu_org_memory_*` events and `CLAUDE_MEMORY_STORES` ("Memory recall now finds mounted team memory stores" **[CL 2.1.172]**) point to an organization-scoped memory tier. The snapshot's `teamMemorySync` identifier is gone, but `team_memory` strings remain **[BIN-331]**.
- **Auto-dream** survives intact. The snapshot's `tengu_auto_dream_fired`, `…_completed`, and `…_failed` are present, along with `…_skipped` and `…_toggled`. `dream` is still a task type **[BIN-331]**.
- **Session memory is the surprise.** The snapshot has 16 `tengu_session_memory_*` and `tengu_sm_compact_*` events **[SNAP]**. The 2.1.331 bundle has none of them. The only `session_memory` strings left belong to the bundled gRPC library **[BIN-331]**. The changelog never announces a removal. **[SPEC]** Session-memory-based compaction (`sm_compact`) was retired or folded into precomputed compaction, which solves the same problem: a ready-made summary on hand before it's needed. We'd need source to confirm.

### Layer 4 — Safety, Policy, Sandbox, and Hooks ([Chapters 11–14](11-the-permission-engine.md))

**The permission engine's vocabulary held exactly.** The snapshot's `PermissionDecisionReason` union in [types/permissions.ts](../../types/permissions.ts) has 11 `type` tags: `rule`, `mode`, `subcommandResults`, `permissionPromptTool`, `hook`, `asyncAgent`, `sandboxOverride`, `classifier`, `workingDir`, `safetyCheck`, and `other` **[SNAP]**. A search of the 2.1.331 bundle for `type:"…"` literals with those names returns the same 11, no more and no fewer **[BIN-331]**. Counting by frequency, `other` (302 call sites) and `safetyCheck` (186) dominate. In the snapshot, `rule` led **[BIN-331, SNAP]**. **[SPEC]** Most new policy has been added as safety checks, not as new rule types.

**Modes.** The SDK schema in `chunk-y30r659v.js` enumerates `["default","acceptEdits","bypassPermissions","plan","dontAsk","auto"]` **[BIN-331]**. That is the snapshot's `EXTERNAL_PERMISSION_MODES` plus `auto`, which has moved out from behind `feature('TRANSCRIPT_CLASSIFIER')` into the public list **[SNAP]**. The internal `bubble` mode still exists in a mode-mapping `switch` **[BIN-331]**. "Default" was relabeled "Manual" in the UI, with `--permission-mode manual` accepted "alongside `default`" **[CL 2.1.200]**. **[SPEC]** The schema keeps `default` as the wire value and `manual` is a display alias.

**The classifier left the client.** Chapter 11's `yoloClassifier` ran in-process. Its successor is server-side by default for API, Enterprise, and third-party platforms **[CL 2.1.278]**. With telemetry or flags off there is no fallback to the built-in classifier **[CL 2.1.319]**. The bundle registers an `auto-mode-classifier-2026-07-16` beta **[BIN-331]**. The classifier also gained new subjects: it "now evaluates subagent spawns" **[CL 2.1.178]**, `SendMessage` "is checked by the classifier" **[CL 2.1.222]**, and subagents "report back through a hand-back call that the classifier reviews" **[CL 2.1.271]**. The safe-list logic the snapshot used for Workflow (orchestrator safe because each subagent goes through `canUseTool`) **[SNAP]** reappears as a general principle: check the leaf call, not the orchestrator.

**Rules got richer.** `Tool(param:value)` syntax "to match a tool's input parameters … e.g. `Agent(model:opus)`" **[CL 2.1.178]**. "Deny rules accept globs in the tool-name position" **[CL 2.1.166]**. New fail-closed switches: `permissions.denyInsteadOfPrompting` **[CL 2.1.319]**, `permissions.blockReadsOutsideWorkingDirectories` **[CL 2.1.257]**, and `permissions.blockWritesOutsideWorkingDirectories` **[CL 2.1.314]**.

**Shell and sandbox (Chapter 12).** PowerShell went from a snapshot-only `tools/PowerShellTool/` directory **[SNAP]** to a rollout **[CL 2.1.111]**, then to the Windows fallback when Git Bash is absent **[CL 2.1.120]**, and then to the primary shell when enabled **[CL 2.1.126]**. The bundle ships typed shell-binding declarations for both shells, `core.bash.async.d.ts` and `core.powershell.async.d.ts`, which describe a `$` template-string shell call **[BIN-331]**. **[SPEC]** They serve scripted callers, mods or Code Mode, and not the model's plain Bash tool. The sandbox lost its most permissive default: "Changed sandboxed Bash commands to follow the normal permission flow by default; set `sandbox.autoAllowBashIfSandboxed: true` to keep running them without prompts" **[CL 2.1.325]**. A Linux PID-namespace subprocess sandbox arrived under `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` **[CL 2.1.98]**.

**Hooks (Chapter 13).** The snapshot's `HOOK_EVENTS` in [entrypoints/sdk/coreTypes.ts](../../entrypoints/sdk/coreTypes.ts) lists 27 events **[SNAP]**. The 2.1.331 array in `chunk-bp2w4xmq.js` lists 33 **[BIN-331]**, with the 27 in the same order and six new ones:

| New event | Evidence |
| :--- | :--- |
| `PostToolBatch` | **[BIN-331]**; mentioned in **[CL 2.1.328]** |
| `UserPromptExpansion` | **[BIN-331]** only; we found no changelog entry |
| `PreModelSwitch`, `PostModelSwitch` | **[CL 2.1.251]** |
| `DirectoryAdded` | **[CL 2.1.219]** |
| `MessageDisplay` | "lets hooks transform or hide assistant message text as it is displayed" **[CL 2.1.152]** |

The exit-reason array next to it, `["clear","resume","logout","prompt_input_exit","other"]`, is identical to the snapshot's `EXIT_REASONS` **[BIN-331, SNAP]**. Hooks also gained new handler types and fail-closed controls: `type: "mcp_tool"` hooks **[CL 2.1.118]**, `hookSpecificOutput.updatedToolOutput` "for all tools" **[CL 2.1.121]**, `onFailure: "block"` **[CL 2.1.295]**, and `updatedInput` "validated like Claude's own input" **[CL 2.1.300]**. One subtraction: "Agent-type hooks no longer run on `PermissionRequest`" **[CL 2.1.280]**.

**Settings and policy (Chapter 14)** grew a model-governance surface (`enforceAvailableModels` **[CL 2.1.175]**, `deniedModels` **[CL 2.1.283]**, `allowedProviders` **[CL 2.1.285]**) and version pinning (`requiredMinimumVersion` and `requiredMaximumVersion` **[CL 2.1.163]**). `forceRemoteSettingsRefresh` "blocks startup until remote settings are fetched (fail-closed)" **[CL 2.1.92]**. That release is the first after the snapshot, and the README already uses this setting's absence to date the snapshot.

### Layer 5 — Dynamic Capabilities ([Chapter 15](15-model-context-protocol-mcp.md), [Chapter 16](16-skills-plugins-output-styles-and-lsp.md))

**MCP replaced its client.** "the v1 MCP client is removed" and `MCP_SDK_GENERATION=v1` now runs "the v2 MCP client in a compatibility mode" **[CL 2.1.323]**. Protocol `2026-07-28` became the negotiated default in steps, first for stdio servers **[CL 2.1.292]**, then claude.ai connectors **[CL 2.1.295]**, then cloud and Remote Control connectors **[CL 2.1.299]**. Long-running MCP calls became background tasks: first "MCP calls running longer than 2 minutes move to the background automatically" **[CL 2.1.212]**, then "MCP tasks in the terminal" **[CL 2.1.319]**. The bundle's task-type list includes `mcp_task` **[BIN-331]**. ToolSearch, the snapshot's deferred-schema mechanism, is still central. `shouldDefer` appears in 35 chunks, and `alwaysLoad` (an MCP config key **[CL 2.1.121]** and an `_meta['anthropic/alwaysLoad']` field **[CL 2.1.285]**) in 24 **[BIN-331]**.

**Skills absorbed things.** Built-in commands became Skill-callable **[CL 2.1.108]**. The Workflow tool's long reference "moved into a bundled `workflow-authoring` skill", which cut the tool description "about 1k tokens instead of 5.7k" **[CL 2.1.248]**. **[SPEC]** Skills became the standard place to put long, rarely needed prompt text that would otherwise cost tokens on every request.

**Plugins became a programmable runtime: Claude Mods.** The snapshot's plugins (Chapter 16) contribute declarative components: commands, agents, skills, hooks, MCP servers, output styles, and LSP servers **[SNAP]**. "Added Claude Mods: plugins may now modify deeper behavior" **[CL 2.1.287]**. The bundle shows what that means. The one surviving original path is `src/plugins/functionHooks/hooks-worker/hooks-worker.js`, and the 925 KB `claude-code.d.ts` describes itself as "Claude Code function hooks: the plugin API's TypeScript declarations", for a hooks module that "runs in an environment of its own: no DOM, no Node" **[BIN-331]**. Its quoted hook and call names include `tool.check`, `tool.register`, `turn.start`, `turn.step`, `agent.spawn`, `prompt.submit`, `session.compact`, `model.complete`, `model.fork`, `ui.view`, `vcs.isolate`, `engine.create`, and `classic.PreToolUse` **[BIN-331]**. Several of them show up in the changelog as they were added: `agent.spawn` for teammates **[CL 2.1.289]**, `serverToolUses` on `turn.step` **[CL 2.1.290]**, and `$.tool.register` with `isDeferred` **[CL 2.1.293]**. Built-in mods ship on this API: "You should know" **[CL 2.1.287]** and easel, "a built-in mod that draws charts" **[CL 2.1.330]**.

> [!NOTE]
> The name `classic.PreToolUse` suggests that Chapter 13's shell, HTTP, prompt, and agent hooks are now presented to mods as a "classic" layer inside a larger event system **[SPEC]**. It fits the pattern we saw in the Tool contract: the 2.1.88 abstraction is kept and wrapped, and a new layer is built over it.

### Layer 6 — Tasks, Subagents, Swarms, Workflows ([Chapters 17–19](17-background-task-runtime.md))

**The task-type union grew from 7 to 11.** The snapshot's [Task.ts](../../Task.ts) defines `local_bash`, `local_agent`, `remote_agent`, `in_process_teammate`, `local_workflow`, `monitor_mcp`, and `dream` **[SNAP]**. A `switch` in 2.1.331 (`chunk-feeb7y8f.js`) handles those 7 plus `monitor_ws`, `mcp_task`, `auto_mode_scan`, and `post_turn_memory` **[BIN-331]**. **[SPEC]** `monitor_ws` is a WebSocket variant of the Monitor tool, `auto_mode_scan` backs auto-mode setup, and `post_turn_memory` moves memory extraction off the turn's critical path.

**Workflows, the snapshot's biggest absence, shipped.** The 2.1.88 tree has the wiring for `feature('WORKFLOW_SCRIPTS')` (task type `local_workflow`, the `WorkflowPermissionRequest` dispatch, the classifier safe-list entry, `ALL_AGENT_DISALLOWED_TOOLS`) but not `tools/WorkflowTool/` itself ([workflow surface audit](../../2026-10-11-workflow-surface-audit.md)) **[SNAP]**. The public arrival: "Introducing dynamic workflows: ask Claude to create a workflow and it orchestrates work across tens to hundreds of agents in the background" **[CL 2.1.154]**. The 2.1.296 audit documents the shipped tool: name `Workflow`, alias `RunWorkflow`, the `agent()` / `parallel()` / `pipeline()` / `phase()` script API, `wf_*` run IDs, a `journal.jsonl` that replays unchanged `agent()` calls on resume, `scriptSha256` integrity checks, and a bundled `deep-research` workflow **[BIN-296]**. All of these strings are still present in 2.1.331, including the search hint "orchestrate subagents with deterministic JavaScript workflow" **[BIN-331]**. One thing did move: the `v2Run` engine identifier from 2.1.296 no longer appears **[BIN-331]**. **[SPEC]** It was renamed or merged.

The snapshot's guesses held. Its `SyntheticOutputTool` comment about "80-call workflows" and its Map-based session hooks for "high-concurrency workflows" **[SNAP]** describe the shipped system's workload accurately. That is the strongest evidence in this chapter that the snapshot's gated code was the real design and not a dead end.

**Subagents went to the background, then forked by default.**

- "Subagents now run in the background by default" **[CL 2.1.198]**.
- "a `subagent_type: "fork"` subagent inherits the full conversation and prompt cache" and is on by default in interactive sessions **[CL 2.1.232]**, then in `-p`, the SDK, Desktop, and VS Code **[CL 2.1.302]**.
- Nesting went from forbidden, to "up to 5 levels deep" **[CL 2.1.172]**, to off by default **[CL 2.1.217]**, to "depth 3 by default" **[CL 2.1.219]**.

**[SPEC]** Chapter 18's context-forking machinery (`renderedSystemPrompt` for byte-identical forks, 9 chunks in 2.1.331 **[BIN-331]**) went from an optimization to the default spawn mode. Inheriting the parent's prefix is now the cheapest way to start a subagent.

**Teams lost their ceremony.** "removed the `TeamCreate` and `TeamDelete` tools. With `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1` set, every session now has one implicit team" **[CL 2.1.178]**. Teams expanded across sessions instead: "cross-session `SendMessage` … with `ListAgents` to discover them" **[CL 2.1.224]**. `crossSessionInbound` appears in 12 chunks **[BIN-331]**. Agent view ("a single list of every Claude Code session — running, blocked on you, or done" **[CL 2.1.139]**) and the background daemon (`claude attach`, `logs`, `stop`, `respawn`, `rm` **[CL 2.1.251]**) turned Chapter 17's in-process task registry into a machine-wide one.

**KAIROS leaked out in pieces.** The snapshot's `feature('KAIROS')` assistant-mode code (Chapter 19, Chapter 24) never shipped under that name: there is no `KAIROS` string in 2.1.331. But 11 chunks reference `tengu_kairos_*` GrowthBook gates, including `tengu_kairos_push_notifications` on the PushNotification tool and `tengu_kairos_loop_keepalive` behind `CLAUDE_CODE_LOOP_KEEPALIVE` **[BIN-331]**. Both match public entries: the push notification tool **[CL 2.1.110]** and the `/loop` keepalive **[CL 2.1.319]**.

### Layer 7 — Terminal UI ([Chapter 20](20-inside-ink-terminal-react-renderer.md), [Chapter 21](21-the-interactive-repl-screens-keybindings-and-vim.md))

**The fullscreen renderer graduated.** The snapshot carries `CLAUDE_CODE_NO_FLICKER` **[SNAP]**, announced in the first post-snapshot entry as "flicker-free alt-screen rendering with virtualized scrollback" **[CL 2.1.89]**. It became a `/tui` command and setting **[CL 2.1.110]**, the default for new third-party-provider installs **[CL 2.1.239]**, gained a fallback ("now falls back to the classic renderer instead of exiting" **[CL 2.1.236]**), and finally the old renderer got a name: "`/tui classic` as the name for the non-fullscreen renderer" **[CL 2.1.327]**. The env var is still read in 8 chunks of 2.1.331 **[BIN-331]**.

**The custom Ink fork is still there.** The DOM node names from [ink/dom.ts](../../ink/dom.ts) (`ink-root`, `ink-box`, `ink-text`, `ink-virtual-text`) are present, as is a `ScrollBox` **[BIN-331]**. The changelog shows continuous renderer work, for example streaming CPU "reduced … by ~37% by coalescing text updates to 100ms" **[CL 2.1.191]**, and a new terminal protocol, "Program Status Protocol (OSC 7501)" **[CL 2.1.295]**.

**Removed:** `/vim` as a command (vim mode lives on as an editor mode, and got visual mode **[CL 2.1.118]**) **[CL 2.1.92]**. **Gone without a removal note:** `/buddy`. The snapshot's `buddy/` directory has `CompanionSprite.tsx` and a species list (`axolotl`, `capybara`, …) behind `feature('BUDDY')` **[SNAP]**. The changelog introduced it as "here for April 1st" **[CL 2.1.89]**. 2.1.331 has no `buddy` command, no `CompanionSprite`, and no `capybara` **[BIN-331]**. The only `axolotl` left is in a random-name word list. **[SPEC]** It was a one-day feature and was removed quietly.

**Accessibility arrived:** a screen reader mode (`--ax-screen-reader`, `CLAUDE_AX_SCREEN_READER=1`) **[CL 2.1.208]**.

### Layer 8 — Entrypoints, SDK, and Remote ([Chapters 22–24](22-cold-start-mastery-cli-init-main.md))

**The `--version` fast path survived, and gained a little weight.** The snapshot's [entrypoints/cli.tsx:36-37](../../entrypoints/cli.tsx) says "Fast-path for --version/-v: zero module loading needed", and Chapter 22 builds on it **[SNAP]**. The 2.1.331 `cli` entry (30,700 bytes) still checks `e[0]==="--version"||e[0]==="-v"||e[0]==="-V"` against `process.argv.slice(2)` and prints from an inlined object with `VERSION:"2.1.331"` **[BIN-331]**. Before that check it now loads a few modules (a thread CPU meter, an argv reader), and it also accepts a trailing `--verbose` **[BIN-331]**. The principle held, though it isn't strictly zero-import anymore. Startup also got lighter elsewhere: "`claude -p` and Claude Code Remote no longer load the interactive UI" **[CL 2.1.283]**.

**The SDK control protocol (Chapter 23)** kept its vocabulary. `control_request`, `control_response`, `can_use_tool`, `stream_event`, `apply_flag_settings`, `mcp_message`, and `workflow_progress` are all present **[BIN-331]**. New verbs appeared: `set_model` **[CL 2.1.285]** and `register_repo_root` **[CL 2.1.219]**.

**Remote surfaces (Chapter 24)** kept their wire-level identifiers: `/v1/environments/bridge`, `/v1/code/sessions` (29 chunks), `worker_jwt`, `worker_epoch` (22 chunks), the `cse_` session prefix (25 chunks), `tengu_bridge_repl_v2`, and `CLAUDE_CODE_USE_CCR_V2` **[BIN-331]**. The changes are additions on top:

- **Self-hosted runners**: "`claude self-hosted-runner` turns your own machines or containers into a place Claude Code web, mobile, and desktop sessions can run" **[CL 2.1.224]**. That reverses Chapter 24's topology: the cloud dispatches work to a local machine instead of a local machine attaching to the cloud.
- **The upstream proxy** from Chapter 24 lost its log strings. None of the snapshot's `[upstreamproxy] …` messages or its `/v1/code/upstreamproxy/ws` path appear **[BIN-331]**. `CCR_UPSTREAM_PROXY_ENABLED` survives in an env allowlist beside a newer family: `CCR_AGENT_PROXY_ENABLED`, `CCR_EGRESS_GATEWAY_ENABLED`, `CCR_AGENT_PROXY_RELAY_MODE` **[BIN-331]**. The non-dumpable-process discipline (`prctl(PR_SET_DUMPABLE)`) now guards the code-review runner: "Not starting: Claude Code could not make itself non-dumpable … so the review's commands could read its tokens from memory" **[BIN-331]**. **[SPEC]** The credential-relay idea from Chapter 24 was generalized into an agent proxy and an egress gateway, and its threat model spread to new execution contexts.
- **Workflows run remotely**: `remote: true` dispatch and a hidden `__remote-workflow` command **[BIN-296]**, still present in 2.1.331 **[BIN-331]**.

---

## 4. Where the Seams Held

The question at the end of every chapter in this book is "how does this snap into the next layer?" After 240 releases, the more useful question is which joints held. Here is the scorecard.

| 2.1.88 abstraction | Chapter | Status in 2.1.331 | Evidence |
| :--- | :--- | :--- | :--- |
| `Tool` + fail-closed `TOOL_DEFAULTS` | [02](02-the-tool-contract.md) | **Held.** Same five defaults, plus `remoteExecution` and `backgrounding`. A v2 `create()` style is adapted into it | **[BIN-331]** `chunk-g0g3fmj2.js` |
| Command `local-jsx` / `local` / `prompt` union | [03](03-command-and-message-contracts.md) | **Held.** Same object shape with lazy `load()` | **[BIN-331]** |
| `AsyncGenerator` query loop + `Terminal` reasons | [07](07-the-heartbeat-query-loop.md) | **Held, extended.** All 10 snapshot reasons kept, 9 more added | **[BIN-331]** `chunk-5d8pv3g2.js` |
| `StreamingToolExecutor` | [06](06-executing-tools.md) | **Held, ungated.** Always on | **[CL 2.1.154]**, **[BIN-331]** |
| `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` | [04](04-prompt-engineering-and-cache-boundaries.md) | **Held, now public API** | **[CL 2.1.275]**, **[BIN-331]** |
| Permission decision-reason union | [11](11-the-permission-engine.md) | **Held exactly.** Same 11 tags | **[BIN-331]** |
| Hook event list | [13](13-the-hook-system.md) | **Held, extended.** 27 → 33, order preserved | **[BIN-331]** `chunk-bp2w4xmq.js` |
| Task-type union | [17](17-background-task-runtime.md) | **Held, extended.** 7 → 11 | **[BIN-331]** |
| Ink DOM node types | [20](20-inside-ink-terminal-react-renderer.md) | **Held** | **[BIN-331]** |
| `--version` zero-import fast path | [22](22-cold-start-mastery-cli-init-main.md) | **Mostly held.** A few modules load first | **[BIN-331]** `cli` |
| SDK control-protocol verbs | [23](23-machine-readable-modes-headless-sdk-and-control-protocols.md) | **Held, extended** | **[BIN-331]** |
| Five-stage compaction pipeline | [09](09-five-layer-compaction-pipeline.md) | **Reshaped.** Collapse not visible, session-memory compaction gone; idle, precomputed, and server-side stages added | **[BIN-331]**, **[CL 2.1.299]** |
| Session memory | [10](10-memory-systems-claudemd-auto-memory-and-dream.md) | **Not visible** | **[BIN-331]** (absence) |
| Teams via `TeamCreate` | [19](19-agent-teams-swarms-and-coordinator-mode.md) | **Replaced** by an implicit team and cross-session messaging | **[CL 2.1.178, 2.1.224]** |
| In-process `yoloClassifier` | [11](11-the-permission-engine.md) | **Moved** mostly server-side | **[CL 2.1.278, 2.1.319]** |

> [!IMPORTANT]
> The joints that held are the **data contracts**: unions of string tags, object shapes with defaults, and the generator protocol. The pieces that moved are **policies and placements**: where the classifier runs, which compaction stage fires, whether a subagent forks. **[SPEC]** That is the payoff of the book's bottom-up order. The lower layers are stable because so much depends on them, and the upper layers change because nothing depends on them.

The most surprising seam is the ant-only `REPL` tool. In the snapshot, [tools/REPLTool/constants.ts](../../tools/REPLTool/constants.ts) defines `REPL_TOOL_NAME = 'REPL'` and enables it only when `USER_TYPE === 'ant'` and the entrypoint is `cli`. Its comment notes that "REPL mode hides" the primitive tools **[SNAP]**. The 2.1.331 bundle has `var _r="REPL",Ste="Eval",b_n="Code"` in `chunk-vtw3x6sh.js`, and a tool prompt that begins "REPL is your programming interface to Claude Code's tools. Use it to loop, branch, and compose tool calls with code" **[BIN-331]**. Elsewhere the bundle tells the model that a tool "is only available inside REPL. Use REPL with code: await …({...})" and defines `CLAUDE_CODE_EXPERIMENTAL_CODE_MODE` with the display name "Code Mode (experimental)" **[BIN-331]**. The public entry: "Added Code Mode, an experimental opt-in in which Claude writes JavaScript to call its tools" **[CL 2.1.323]**. **[SPEC]** Code Mode is the snapshot's internal REPL tool, shipped. It changes Chapter 02's mental model the most: tools stop being called one per `tool_use` block and become async functions in a script. The Tool contract still holds, because each function call inside the script goes back through `checkPermissions` and hooks. The changelog's Code Mode fixes about hooks and permissions inside scripts ("A PreToolUse hook that errors no longer refuses a script's call…" **[CL 2.1.329]**) point the same way.

---

## 5. Open Questions: What We'd Need the Source For

1. **Is context collapse gone, or was it never external?** The snapshot imported a missing `services/contextCollapse/`, and 2.1.331 has no trace of it. A binary can't tell "removed" apart from "compiled out from the start".
2. **What replaced session memory?** Sixteen telemetry events disappeared without a changelog line. Whether precomputed compaction is the successor is our guess, and only source comments could confirm it.
3. **How does the v2 tool `create()` style relate to `buildTool()`?** We can see the adapter, but not which built-in tools were migrated, or why `checkPermissions` left the defaults.
4. **What are `Frame`, `FrameRead`, and `SuggestBackgroundPR`?** They appear only in the retired-tool set. They may be tools that shipped to some users and never reached the changelog.
5. **What exactly is `UserPromptExpansion`?** It's a hook event with no changelog entry. The 2.1.299 change that made `UserPromptSubmit` run "before a skill or command expands" suggests it fires after expansion, but that's a guess.
6. **Is `ultraplan` dead?** The changelog says "Removed ultraplan feature" **[CL 2.1.222]**. The 2.1.331 bundle still registers a `local-jsx` command named `ultraplan` ("Draft an editable plan in a cloud session") with `availability:["claude-ai"]` and an `isEnabled` gate, and lists it in what looks like a cloud-feature upsell table beside `ultrareview` and `teleport` (`chunk-dkgv0tv2.js`) **[BIN-331]**. A removal note and live command code side by side is exactly the snapshot-versus-shipped ambiguity this book has flagged since Chapter 00.
7. **Which of the 4,225 `tengu_*` strings are gates, and which are on?** That would take GrowthBook payloads, not code.

---

## Putting the Layer Together

```mermaid
flowchart TB
    subgraph Held["Held from 2.1.88"]
        T["Tool + TOOL_DEFAULTS"]
        Q["AsyncGenerator query loop"]
        P["Permission reason union"]
        H["Hook event list (27)"]
        B["Dynamic boundary marker"]
    end
    subgraph Extended["Extended on top"]
        T2["v2 create() adapter,<br/>remoteExecution, backgrounding"]
        Q2["+9 terminal reasons"]
        H2["+6 hook events, Claude Mods API"]
        B2["server-side cache betas,<br/>idle and precomputed compaction"]
        W["Workflows, fork subagents,<br/>agent view, Code Mode"]
    end
    subgraph Moved["Moved or removed"]
        C["yoloClassifier: server-side"]
        R["TeamCreate, TaskOutput, /tag, /vim, /buddy"]
        S["Session memory, context collapse"]
    end
    T --> T2
    Q --> Q2
    H --> H2
    B --> B2
    T --> W
    Q --> W
    P --> C
```

---

## How This Snaps Into the Book

This chapter has no next layer. It is a delta against all of them. Use it this way:

- **Reading a chapter for the current product?** Read the chapter, then come back to that layer's subsection in Section 3 for what changed. Anything tagged **[CL]** is safe to rely on. Treat **[BIN]** as "the code exists". Treat **[SPEC]** as a lead to verify.
- **Building your own harness from this book (Appendix C)?** Section 4 is the list of patterns that survived eight months and 240 releases in production: fail-closed tool defaults, a generator loop with typed terminal reasons, a closed union of permission decision reasons, and an explicit cache boundary. Those are the ones to copy.
- **Repeating this exercise on a later build?** Use the carving method from Section 1, then diff the same anchors: `TOOL_DEFAULTS`, the terminal-reason `switch`, the hook-event array, the decision-reason tags, the task-type `switch`, and the beta-header table. They are string-stable and grep-friendly, and in this build they found the right code every time.

---

## Reading Exercises & Code Checkpoints

1. **Diff the hook events yourself.** Print the snapshot's list:
   ```bash
   sed -n '/export const HOOK_EVENTS = \[/,/\] as const/p' entrypoints/sdk/coreTypes.ts
   ```
   Then predict, from the changelog entries cited in Section 3, which six events 2.1.331 adds and where in the array they fall. Check your answer against the table above. Why might `PostToolBatch` sit right after `PostToolUseFailure` rather than at the end?

2. **Find the seam that held exactly.** Run:
   ```bash
   rg -n "type: '(rule|mode|subcommandResults|permissionPromptTool|hook|asyncAgent|sandboxOverride|classifier|workingDir|safetyCheck|other)'" types/permissions.ts
   ```
   Every one of these tags still exists in 2.1.331. Pick one, such as `asyncAgent`, and trace where [utils/permissions/](../../utils/permissions/) produces it. Then explain why a later feature, the classifier reviewing subagent hand-backs **[CL 2.1.271]**, could ship without adding a new tag.

3. **Reconstruct Code Mode's ancestry.** Read [tools/REPLTool/constants.ts](../../tools/REPLTool/constants.ts) and [tools.ts](../../tools.ts) around the `REPL_ONLY_TOOLS` export and the `--bare + REPL mode` comment. Which snapshot tools does REPL hide, and what does that tell you about how Code Mode must route each inner call through Chapter 06's `checkPermissionsAndCallTool()`?

4. **Audit a terminal reason.** In [query.ts](../../query.ts), find every `return { reason: … }`:
   ```bash
   rg -n "reason: '" query.ts
   ```
   Then classify each one using the 2.1.331 error/non-error split from Section 3. Which snapshot continuation transitions (`next_turn`, `reactive_compact_retry`, …) are *not* terminal reasons, and why does that distinction let the loop grow new terminals without breaking callers such as `QueryEngine.submitMessage()`?


---

<!-- appendices/A-feature-flags-and-env-knobs.md — https://reverseengineeringclaudecode.com/appendices/A-feature-flags-and-env-knobs -->

# Appendix A — Complete Inventory of Build-Time `feature()` Flags & Environment Knobs

> **Scope:** Cross-cutting reference companion to [Chapter 00](../chapters/00-how-to-read-a-1900-file-agent.md) through [Chapter 24](../chapters/24-across-the-wire-remote-sessions-bridge-and-direct-connect.md)
> **Snapshot Census:** 90 unique build-time `feature('...')` flags (933 executable call sites across 197 files importing `bun:bundle`), 357 `process.env.USER_TYPE` checks in `.ts` files vs. 95 constant-folded `"external" ===/!== 'ant'` checks in `.tsx` files, and 472 distinct `process.env.*` keys across 1,884 `.ts`/`.tsx` source files.
> **Primary Source Files:**
> - [bridge/bridgeEnabled.ts](../../bridge/bridgeEnabled.ts) — canonical positive-ternary `feature()` DCE idiom
> - [tools/BashTool/bashPermissions.ts](../../tools/BashTool/bashPermissions.ts) & [tools/BashTool/pathValidation.ts](../../tools/BashTool/pathValidation.ts) — Bun's per-function `feature()` DCE complexity cliff
> - [components/MemoryUsageIndicator.tsx](../../components/MemoryUsageIndicator.tsx) — constant-folded `USER_TYPE` build define in `.tsx`
> - [utils/envUtils.ts](../../utils/envUtils.ts) — `isEnvTruthy()`, `isEnvDefinedFalsy()`, `isBareMode()`, `getClaudeConfigHomeDir()`
> - [utils/managedEnv.ts](../../utils/managedEnv.ts) & [utils/managedEnvConstants.ts](../../utils/managedEnvConstants.ts) — `SAFE_ENV_VARS` allowlist and three-layer `filterSettingsEnv()` security boundary
> - [utils/subprocessEnv.ts](../../utils/subprocessEnv.ts) — child-process secret scrubbing (`CLAUDE_CODE_SUBPROCESS_ENV_SCRUB`) and CCR proxy injection
> - [entrypoints/cli.tsx](../../entrypoints/cli.tsx) & [constants/system.ts](../../constants/system.ts) — top-level `ABLATION_BASELINE` injection and `NATIVE_CLIENT_ATTESTATION`

---

## Why Four Separate Gating Layers Exist

Reading Claude Code without understanding its gating taxonomy creates an illusion of arbitrary complexity: why does one capability check `feature('BRIDGE_MODE')`, another check `process.env.USER_TYPE === 'ant'`, a third read `process.env.CLAUDE_CODE_NO_FLICKER`, and a fourth query `getFeatureValue_CACHED_MAY_BE_STALE('tengu_ccr_bridge', false)`?

Each layer defends a distinct boundary that the others cannot enforce:

```text
  COMPILE TIME (Bun bundler + JSX compiler)
  +------------------------------------------------------------------------+
  | 1. feature('FLAG') from 'bun:bundle'   -> Dead-code elimination (DCE)  |
  |    & MACRO.* / USER_TYPE define           Strips code, strings, & deps |
  +------------------------------------------------------------------------+
                                      |
                                      v  (surviving binary)
  PROCESS STARTUP & SETTINGS LOAD (init.ts -> managedEnv.ts)
  +------------------------------------------------------------------------+
  | 2. process.env.* & settings.json `env` -> Operator / CI / IDE overrides|
  |    Filtered by SAFE_ENV_VARS pre-trust    & stripped for SSH/CCD/host  |
  +------------------------------------------------------------------------+
                                      |
                                      v  (runtime process)
  REMOTE CONTROL PLANE & POLICY (growthbook.ts / policyLimits)
  +------------------------------------------------------------------------+
  | 3. GrowthBook (`tengu_*`) & Policy     -> Live kill switches & A/B     |
  |    Disk-cached + background refresh       rollouts without shipping    |
  +------------------------------------------------------------------------+
                                      |
                                      v  (per-request / per-tool)
  CHILD PROCESS BOUNDARY (subprocessEnv.ts)
  +------------------------------------------------------------------------+
  | 4. GHA_SUBPROCESS_SCRUB + proxy env    -> Strips parent auth secrets   |
  |    before Bash / MCP / LSP / hooks        from prompt-injectable tools |
  +------------------------------------------------------------------------+
```

Compile-time flags exist for **bundle size, secrecy, and zero-overhead exclusion**: unreleased codenames, internal GrowthBook keys, and ant-only telemetry never ship in external binaries. Environment variables exist for **machine-local configuration, CI/SDK orchestration, and emergency escape hatches** before a network round-trip can occur. GrowthBook gates provide **instant post-release kill switches**. Understanding how these layers compose prevents misreading a dead external branch as live production behavior.

---

## 1. How Build-Time `feature()` Dead-Code Elimination Works (And Where It Breaks)

### The Three Compile-Time Primitives

Across the repository, Bun's bundler resolves three compile-time mechanisms before emitting a release artifact:

1. **`import { feature } from 'bun:bundle'`** (imported by **197** files; **90** unique flags; **933** executable call sites). Every flag compiles to a literal `true` or `false` at bundle time, letting the minifier drop unreachable `require(...)` calls, prompt text, tools, and GrowthBook gate names.
2. **`MACRO.*` build constants** (injected globally): `MACRO.VERSION`, `MACRO.BUILD_TIME`, `MACRO.PACKAGE_URL`, `MACRO.NATIVE_PACKAGE_URL`, `MACRO.FEEDBACK_CHANNEL`, `MACRO.ISSUES_EXPLAINER`, and `MACRO.VERSION_CHANGELOG`. Used for zero-import `--version` (`entrypoints/cli.tsx:37-42`) and updater URLs.
3. **`USER_TYPE` define** (`'ant'` vs. `'external'`), covered in Section 3.

### Three Production Scars in Bun's `feature()` Evaluator

Treating `feature('...')` like an ordinary boolean helper causes silent leaks and silent feature regressions. Three scars documented directly in the source capture the exact traps:

**Scar 1 — Positive Ternary Required to Strip String Literals.** In [bridge/bridgeEnabled.ts](../../bridge/bridgeEnabled.ts), [voice/voiceModeEnabled.ts](../../voice/voiceModeEnabled.ts), [hooks/useReplBridge.tsx](../../hooks/useReplBridge.tsx), and [tools/BriefTool/upload.ts](../../tools/BriefTool/upload.ts), engineers deliberately avoid early-return negative guards:

```ts
// bridge/bridgeEnabled.ts:28-36
export function isBridgeEnabled(): boolean {
  // Positive ternary pattern — see docs/feature-gating.md.
  // Negative pattern (if (!feature(...)) return) does not eliminate
  // inline string literals from external builds.
  return feature('BRIDGE_MODE')
    ? isClaudeAISubscriber() &&
        getFeatureValue_CACHED_MAY_BE_STALE('tengu_ccr_bridge', false)
    : false
}
```

When written as `if (!feature('BRIDGE_MODE')) return false; return getFeatureValue_...('tengu_ccr_bridge', false)`, Bun's DCE pass fails to eliminate the trailing string literal `'tengu_ccr_bridge'` from the bundle. Wrapping the entire body inside a positive `feature('...') ? ... : false` (or `if (feature('...')) { ... }`) is mandatory whenever a gated branch holds internal strings or `require()` calls.

**Scar 2 — Bun's Per-Function DCE Complexity Cliff.** In [tools/BashTool/bashPermissions.ts](../../tools/BashTool/bashPermissions.ts) and [tools/BashTool/pathValidation.ts](../../tools/BashTool/pathValidation.ts), a large permission function hit an internal complexity ceiling inside Bun's constant folder:

```ts
// tools/BashTool/bashPermissions.ts:81-89
// DCE cliff: Bun's feature() evaluator has a per-function complexity budget.
// bashToolHasPermission is right at the limit. `import { X as Y }` aliases
// inside the import block count toward this budget; when they push it over
// the threshold Bun can no longer prove feature('BASH_CLASSIFIER') is a
// constant and silently evaluates the ternaries to `false`, dropping every
// pendingClassifierCheck spread. Keep aliases as top-level const rebindings
// instead. (See also the comment on checkSemanticsDeny below.)
const bashCommandIsSafeAsync = bashCommandIsSafeAsync_DEPRECATED
const splitCommand = splitCommand_DEPRECATED
```

Worse still, [tools/BashTool/pathValidation.ts:1155-1163](../../tools/BashTool/pathValidation.ts) records that an obsolete 80-line dead function in `bashPermissions.ts` **cannot be deleted** because removing it shifted the module across the complexity threshold and caused 8 of 30 classifier tests to silently fail (`feature('BASH_CLASSIFIER')` folded to `false`).

**Scar 3 — Zero-Allocation Native Attestation & Static Libc.** Not every `feature()` flag gates an experimental product feature. Two target the compiled binary runtime itself:
- `NATIVE_CLIENT_ATTESTATION` ([constants/system.ts:64-83](../../constants/system.ts)) embeds a fixed-width `cch=00000;` placeholder in the attribution header string so Anthropic's custom Bun HTTP stack (`bun-anthropic/src/http/Attestation.zig`) can overwrite the five zeros in-place with a computed attestation hash without altering `Content-Length` or reallocating the request buffer.
- `IS_LIBC_MUSL` / `IS_LIBC_GLIBC` ([utils/envDynamic.ts:52-59](../../utils/envDynamic.ts)) short-circuit Linux libc detection at compile time in native binaries, falling back to an async fire-and-forget `stat('/lib/libc.musl-...')` check only in unbundled Node runs.

> [!NOTE]
> **Snapshot Absences Behind `feature()` Gates:** Because external builds dead-code-eliminate ungated modules, **31 of the 90 flags** guard `require(...)` or `import(...)` targets that are **absent from this source snapshot** (only their call sites survive). Those flags are marked with `†` in the tables below; see Appendix B for call-site reconstruction of key missing modules.

---

## 2. Complete Inventory of All 90 Build-Time `feature()` Flags

Counts below report **executable code call sites** across all `.ts` and `.tsx` files (`933` total; raw regex hits including 39 documentation comments equal `972`). Every single unique flag in the repository appears exactly once across Tables 2.1–2.6 (`14 + 15 + 12 + 11 + 22 + 16 = 90`). Flags marked `†` reference at least one snapshot-absent module.

### 2.1 Agent, Swarm, Proactive & Autonomous Modes (14 flags, 332 sites)

| Flag | Sites (Files) | Primary Source Files | Role & Companion Chapter |
| :--- | :---: | :--- | :--- |
| `KAIROS` † | 147 (54) | [main.tsx](../../main.tsx), [screens/REPL.tsx](../../screens/REPL.tsx), [bridge/bridgeMain.ts](../../bridge/bridgeMain.ts) | Always-on assistant mode: daily memory logs, assistant daemon bridge, push/file tools ([Ch 10](../chapters/10-memory-systems-claudemd-auto-memory-and-dream.md), [Ch 24](../chapters/24-across-the-wire-remote-sessions-bridge-and-direct-connect.md)) |
| `KAIROS_BRIEF` | 39 (20) | [main.tsx](../../main.tsx), [constants/prompts.ts](../../constants/prompts.ts), [tools/BriefTool/BriefTool.ts](../../tools/BriefTool/BriefTool.ts) | Concise "brief" output mode (`SendUserMessage` / `ctrl+shift+b`) for async updates ([Ch 04](../chapters/04-prompt-engineering-and-cache-boundaries.md), [Ch 21](../chapters/21-the-interactive-repl-screens-keybindings-and-vim.md)) |
| `PROACTIVE` † | 37 (15) | [screens/REPL.tsx](../../screens/REPL.tsx), [cli/print.ts](../../cli/print.ts), [constants/prompts.ts](../../constants/prompts.ts) | Autonomous tick/wake loop (`--proactive`, `SleepTool`, periodic wakeups) ([Ch 17](../chapters/17-background-task-runtime.md)) |
| `COORDINATOR_MODE` † | 32 (15) | [cli/print.ts](../../cli/print.ts), [main.tsx](../../main.tsx), [coordinator/coordinatorMode.ts](../../coordinator/coordinatorMode.ts) | Multi-agent orchestrator mode stripping direct edit tools from leader ([Ch 19](../chapters/19-agent-teams-swarms-and-coordinator-mode.md)) |
| `UDS_INBOX` † | 18 (10) | [tools/SendMessageTool/SendMessageTool.ts](../../tools/SendMessageTool/SendMessageTool.ts), [main.tsx](../../main.tsx), [setup.ts](../../setup.ts) | Unix domain socket cross-session peer inbox (`ListPeersTool`, `/peers`) ([Ch 19](../chapters/19-agent-teams-swarms-and-coordinator-mode.md)) |
| `BG_SESSIONS` † | 11 (7) | [utils/concurrentSessions.ts](../../utils/concurrentSessions.ts), [query.ts](../../query.ts), [screens/REPL.tsx](../../screens/REPL.tsx) | Background tmux-backed CLI sessions (`claude --bg`, detach-on-exit) ([Ch 17](../chapters/17-background-task-runtime.md), [Ch 22](../chapters/22-cold-start-mastery-cli-init-main.md)) |
| `AGENT_TRIGGERS` | 10 (6) | [cli/print.ts](../../cli/print.ts), [screens/REPL.tsx](../../screens/REPL.tsx), [tools/ScheduleCronTool/prompt.ts](../../tools/ScheduleCronTool/prompt.ts) | Local cron trigger tools (`CronCreate`, `CronDelete`, `CronList`) ([Ch 17](../chapters/17-background-task-runtime.md)) |
| `ULTRAPLAN` | 10 (5) | [screens/REPL.tsx](../../screens/REPL.tsx), [components/PromptInput/PromptInput.tsx](../../components/PromptInput/PromptInput.tsx), [commands/ultraplan.tsx](../../commands/ultraplan.tsx) | Deep remote planning workflow triggered via `/ultraplan` ([Ch 11](../chapters/11-the-permission-engine.md), [Ch 21](../chapters/21-the-interactive-repl-screens-keybindings-and-vim.md)) |
| `WORKFLOW_SCRIPTS` † | 10 (7) | [commands.ts](../../commands.ts), [tasks.ts](../../tasks.ts), [constants/tools.ts](../../constants/tools.ts) | Scriptable multi-step workflow engine (`WorkflowTool`, `local_workflow` tasks) ([Ch 17](../chapters/17-background-task-runtime.md)) |
| `TEMPLATES` † | 6 (5) | [query/stopHooks.ts](../../query/stopHooks.ts), [query.ts](../../query.ts), [utils/markdownConfigLoader.ts](../../utils/markdownConfigLoader.ts) | Template-driven background job definitions (`templates/` config dir) ([Ch 07](../chapters/07-the-heartbeat-query-loop.md), [Ch 16](../chapters/16-skills-plugins-output-styles-and-lsp.md)) |
| `FORK_SUBAGENT` † | 5 (5) | [tools/AgentTool/forkSubagent.ts](../../tools/AgentTool/forkSubagent.ts), [commands.ts](../../commands.ts), [commands/branch/index.ts](../../commands/branch/index.ts) | Cache-sharing forked subagents and `/fork` conversation branching ([Ch 18](../chapters/18-subagents-context-forking-and-worktrees.md)) |
| `VERIFICATION_AGENT` | 4 (4) | [constants/prompts.ts](../../constants/prompts.ts), [tools/AgentTool/builtInAgents.ts](../../tools/AgentTool/builtInAgents.ts), [tools/TaskUpdateTool/TaskUpdateTool.ts](../../tools/TaskUpdateTool/TaskUpdateTool.ts) | Ant-only A/B verification agent contract (`tengu_hive_evidence`) ([Ch 18](../chapters/18-subagents-context-forking-and-worktrees.md)) |
| `AGENT_TRIGGERS_REMOTE` | 2 (2) | [tools.ts](../../tools.ts), [skills/bundled/index.ts](../../skills/bundled/index.ts) | Remote scheduled agent trigger tools & bundled skill ([Ch 16](../chapters/16-skills-plugins-output-styles-and-lsp.md), [Ch 17](../chapters/17-background-task-runtime.md)) |
| `BUILTIN_EXPLORE_PLAN_AGENTS` | 1 (1) | [tools/AgentTool/builtInAgents.ts](../../tools/AgentTool/builtInAgents.ts) | A/B gate controlling whether built-in `Explore` and `Plan` agents are registered ([Ch 18](../chapters/18-subagents-context-forking-and-worktrees.md)) |

### 2.2 Compaction, Context & Memory (15 flags, 142 sites)

| Flag | Sites (Files) | Primary Source Files | Role & Companion Chapter |
| :--- | :---: | :--- | :--- |
| `TEAMMEM` | 46 (15) | [utils/collapseReadSearch.ts](../../utils/collapseReadSearch.ts), [utils/claudemd.ts](../../utils/claudemd.ts), [services/teamMemorySync/watcher.ts](../../services/teamMemorySync/watcher.ts) | Shared team memory directory, secret guard, and background sync watcher ([Ch 10](../chapters/10-memory-systems-claudemd-auto-memory-and-dream.md)) |
| `CONTEXT_COLLAPSE` † | 22 (13) | [query.ts](../../query.ts), [services/compact/autoCompact.ts](../../services/compact/autoCompact.ts), [setup.ts](../../setup.ts) | Stage 4 compaction: collapsible history spans and `CtxInspectTool` ([Ch 09](../chapters/09-five-layer-compaction-pipeline.md)) |
| `HISTORY_SNIP` † | 16 (8) | [utils/messages.ts](../../utils/messages.ts), [QueryEngine.ts](../../QueryEngine.ts), [query.ts](../../query.ts) | Stage 2 compaction: surgical history snipping (`SnipTool`, `/force-snip`) ([Ch 09](../chapters/09-five-layer-compaction-pipeline.md)) |
| `CACHED_MICROCOMPACT` † | 11 (5) | [services/api/claude.ts](../../services/api/claude.ts), [query.ts](../../query.ts), [services/compact/microCompact.ts](../../services/compact/microCompact.ts) | Server-side cache-editing microcompact (`cache_edits` API blocks) ([Ch 09](../chapters/09-five-layer-compaction-pipeline.md)) |
| `PROMPT_CACHE_BREAK_DETECTION` | 9 (6) | [services/api/claude.ts](../../services/api/claude.ts), [services/compact/microCompact.ts](../../services/compact/microCompact.ts), [services/api/promptCacheBreakDetection.ts](../../services/api/promptCacheBreakDetection.ts) | Diffs system prompt/tools/messages between turns to diagnose cache misses ([Ch 04](../chapters/04-prompt-engineering-and-cache-boundaries.md)) |
| `TOKEN_BUDGET` | 9 (6) | [screens/REPL.tsx](../../screens/REPL.tsx), [query.ts](../../query.ts), [constants/prompts.ts](../../constants/prompts.ts) | Multi-turn token-budget tracking and continuation nudges ([Ch 07](../chapters/07-the-heartbeat-query-loop.md)) |
| `CONNECTOR_TEXT` | 8 (5) | [services/api/claude.ts](../../services/api/claude.ts), [utils/messages.ts](../../utils/messages.ts), [constants/betas.ts](../../constants/betas.ts) | `summarize-connector-text-2026-03-13` beta for compacting inter-tool prose ([Ch 05](../chapters/05-talking-to-the-model.md)) |
| `EXTRACT_MEMORIES` | 6 (3) | [query/stopHooks.ts](../../query/stopHooks.ts), [cli/print.ts](../../cli/print.ts), [utils/backgroundHousekeeping.ts](../../utils/backgroundHousekeeping.ts) | End-of-turn background memory extraction agent ([Ch 10](../chapters/10-memory-systems-claudemd-auto-memory-and-dream.md)) |
| `REACTIVE_COMPACT` † | 5 (5) | [query.ts](../../query.ts), [services/compact/autoCompact.ts](../../services/compact/autoCompact.ts), [commands/compact/compact.ts](../../commands/compact/compact.ts) | On-demand compaction triggered reactively on `prompt_too_long` (`tengu_cobalt_raccoon`) ([Ch 07](../chapters/07-the-heartbeat-query-loop.md), [Ch 09](../chapters/09-five-layer-compaction-pipeline.md)) |
| `MEMORY_SHAPE_TELEMETRY` † | 3 (2) | [utils/sessionFileAccessHooks.ts](../../utils/sessionFileAccessHooks.ts), [memdir/findRelevantMemories.ts](../../memdir/findRelevantMemories.ts) | Logs recall shape telemetry for memory directory queries ([Ch 10](../chapters/10-memory-systems-claudemd-auto-memory-and-dream.md)) |
| `AGENT_MEMORY_SNAPSHOT` | 2 (2) | [main.tsx](../../main.tsx), [tools/AgentTool/loadAgentsDir.ts](../../tools/AgentTool/loadAgentsDir.ts) | Syncs custom agent memory snapshots on startup ([Ch 18](../chapters/18-subagents-context-forking-and-worktrees.md)) |
| `BREAK_CACHE_COMMAND` | 2 (1) | [context.ts](../../context.ts) | Dev-only `/break-cache` injection into dynamic system prompt section ([Ch 04](../chapters/04-prompt-engineering-and-cache-boundaries.md)) |
| `COMPACTION_REMINDERS` | 1 (1) | [utils/attachments.ts](../../utils/attachments.ts) | Injects `compaction_reminder` system attachment as context fills ([Ch 09](../chapters/09-five-layer-compaction-pipeline.md)) |
| `KAIROS_DREAM` † | 1 (1) | [skills/bundled/index.ts](../../skills/bundled/index.ts) | Registers bundled `/dream` cross-session memory consolidation skill ([Ch 10](../chapters/10-memory-systems-claudemd-auto-memory-and-dream.md)) |
| `ULTRATHINK` | 1 (1) | [utils/thinking.ts](../../utils/thinking.ts) | Enables `ultrathink` keyword boost (`tengu_turtle_carbon`) ([Ch 05](../chapters/05-talking-to-the-model.md)) |

### 2.3 Tools, Shell, Permissions & Sandbox (12 flags, 195 sites)

| Flag | Sites (Files) | Primary Source Files | Role & Companion Chapter |
| :--- | :---: | :--- | :--- |
| `TRANSCRIPT_CLASSIFIER` † | 108 (44) | [utils/permissions/permissionSetup.ts](../../utils/permissions/permissionSetup.ts), [utils/permissions/yoloClassifier.ts](../../utils/permissions/yoloClassifier.ts), [main.tsx](../../main.tsx) | Auto-mode LLM safety classifier over full conversation transcripts ([Ch 11](../chapters/11-the-permission-engine.md)) |
| `BASH_CLASSIFIER` | 45 (19) | [tools/BashTool/bashPermissions.ts](../../tools/BashTool/bashPermissions.ts), [hooks/useCanUseTool.tsx](../../hooks/useCanUseTool.tsx), [utils/classifierApprovals.ts](../../utils/classifierApprovals.ts) | Per-command Bash ML/LLM classifier for permission auto-approval ([Ch 11](../chapters/11-the-permission-engine.md), [Ch 12](../chapters/12-shell-execution-sandboxing-and-workspace-tools.md)) |
| `MONITOR_TOOL` † | 13 (9) | [tools/BashTool/prompt.ts](../../tools/BashTool/prompt.ts), [tasks/LocalShellTask/LocalShellTask.tsx](../../tasks/LocalShellTask/LocalShellTask.tsx), [tasks.ts](../../tasks.ts) | Streaming shell/MCP monitor tool (`MonitorTool`, `monitor_mcp` task) ([Ch 17](../chapters/17-background-task-runtime.md)) |
| `TREE_SITTER_BASH_SHADOW` | 5 (2) | [tools/BashTool/bashPermissions.ts](../../tools/BashTool/bashPermissions.ts), [utils/bash/parser.ts](../../utils/bash/parser.ts) | Shadow-mode tree-sitter Bash AST parser comparing against legacy regex parser (`tengu_birch_trellis`) ([Ch 12](../chapters/12-shell-execution-sandboxing-and-workspace-tools.md)) |
| `TERMINAL_PANEL` † | 5 (5) | [tools.ts](../../tools.ts), [keybindings/defaultBindings.ts](../../keybindings/defaultBindings.ts), [hooks/useGlobalKeybindings.tsx](../../hooks/useGlobalKeybindings.tsx) | Embedded terminal capture tool (`TerminalCaptureTool`) and `meta+j` toggle ([Ch 21](../chapters/21-the-interactive-repl-screens-keybindings-and-vim.md)) |
| `REVIEW_ARTIFACT` † | 4 (2) | [components/permissions/PermissionRequest.tsx](../../components/permissions/PermissionRequest.tsx), [skills/bundled/index.ts](../../skills/bundled/index.ts) | Code-review artifact tool (`ReviewArtifactTool`) and `hunter` skill ([Ch 16](../chapters/16-skills-plugins-output-styles-and-lsp.md)) |
| `WEB_BROWSER_TOOL` † | 4 (3) | [screens/REPL.tsx](../../screens/REPL.tsx), [tools.ts](../../tools.ts), [main.tsx](../../main.tsx) | Native Bun `WebView`-backed embedded browser tool ([Ch 02](../chapters/02-the-tool-contract.md)) |
| `TREE_SITTER_BASH` | 3 (1) | [utils/bash/parser.ts](../../utils/bash/parser.ts) | Primary tree-sitter Bash AST parser activation ([Ch 12](../chapters/12-shell-execution-sandboxing-and-workspace-tools.md)) |
| `FILE_PERSISTENCE` | 3 (2) | [cli/print.ts](../../cli/print.ts), [utils/filePersistence/filePersistence.ts](../../utils/filePersistence/filePersistence.ts) | Uploads modified output files to Files API at end of each turn in remote/BYOC sessions ([Ch 23](../chapters/23-machine-readable-modes-headless-sdk-and-control-protocols.md)) |
| `OVERFLOW_TEST_TOOL` † | 2 (2) | [tools.ts](../../tools.ts), [utils/permissions/classifierDecision.ts](../../utils/permissions/classifierDecision.ts) | Synthetic context-overflow test tool for compaction/classifier testing ([Ch 02](../chapters/02-the-tool-contract.md)) |
| `POWERSHELL_AUTO_MODE` | 2 (2) | [utils/permissions/yoloClassifier.ts](../../utils/permissions/yoloClassifier.ts), [utils/permissions/permissions.ts](../../utils/permissions/permissions.ts) | Extends auto-mode classifier support to `PowerShellTool` ([Ch 11](../chapters/11-the-permission-engine.md), [Ch 12](../chapters/12-shell-execution-sandboxing-and-workspace-tools.md)) |
| `HOOK_PROMPTS` | 1 (1) | [screens/REPL.tsx](../../screens/REPL.tsx) | Exposes interactive `requestPrompt` callback from REPL to hook engine ([Ch 13](../chapters/13-the-hook-system.md)) |

### 2.4 MCP, Skills, Plugins & Commands (11 flags, 72 sites)

| Flag | Sites (Files) | Primary Source Files | Role & Companion Chapter |
| :--- | :---: | :--- | :--- |
| `EXPERIMENTAL_SKILL_SEARCH` † | 19 (9) | [tools/SkillTool/SkillTool.ts](../../tools/SkillTool/SkillTool.ts), [constants/prompts.ts](../../constants/prompts.ts), [utils/attachments.ts](../../utils/attachments.ts) | Semantic local/remote skill search and prefetch pipeline ([Ch 16](../chapters/16-skills-plugins-output-styles-and-lsp.md)) |
| `KAIROS_CHANNELS` | 18 (13) | [services/mcp/useManageMCPConnections.ts](../../services/mcp/useManageMCPConnections.ts), [cli/print.ts](../../cli/print.ts), [services/mcp/channelNotification.ts](../../services/mcp/channelNotification.ts) | Inbound MCP channel notifications & push messages (`tengu_harbor`) ([Ch 15](../chapters/15-model-context-protocol-mcp.md)) |
| `CHICAGO_MCP` | 13 (7) | [services/mcp/client.ts](../../services/mcp/client.ts), [query.ts](../../query.ts), [services/mcp/config.ts](../../services/mcp/config.ts) | Built-in desktop computer-use MCP server integration ([Ch 15](../chapters/15-model-context-protocol-mcp.md)) |
| `MCP_SKILLS` † | 9 (3) | [services/mcp/client.ts](../../services/mcp/client.ts), [services/mcp/useManageMCPConnections.ts](../../services/mcp/useManageMCPConnections.ts), [commands.ts](../../commands.ts) | Exposes MCP server prompts as discoverable skills ([Ch 15](../chapters/15-model-context-protocol-mcp.md), [Ch 16](../chapters/16-skills-plugins-output-styles-and-lsp.md)) |
| `KAIROS_GITHUB_WEBHOOKS` † | 4 (4) | [tools.ts](../../tools.ts), [hooks/useReplBridge.tsx](../../hooks/useReplBridge.tsx), [commands.ts](../../commands.ts) | PR subscription tool (`/subscribe-pr`, `SubscribePRTool`) and webhook sanitizer ([Ch 24](../chapters/24-across-the-wire-remote-sessions-bridge-and-direct-connect.md)) |
| `MCP_RICH_OUTPUT` | 3 (1) | [tools/MCPTool/UI.tsx](../../tools/MCPTool/UI.tsx) | Truncated rich parameter rendering in MCP tool UI blocks ([Ch 15](../chapters/15-model-context-protocol-mcp.md)) |
| `NEW_INIT` | 2 (1) | [commands/init.ts](../../commands/init.ts) | Enhanced `/init` scaffolding `CLAUDE.md`, skills, and hooks (`CLAUDE_CODE_NEW_INIT`) ([Ch 10](../chapters/10-memory-systems-claudemd-auto-memory-and-dream.md)) |
| `BUILDING_CLAUDE_APPS` | 1 (1) | [skills/bundled/index.ts](../../skills/bundled/index.ts) | Registers bundled `claudeApi` skill for building apps with the Claude API ([Ch 16](../chapters/16-skills-plugins-output-styles-and-lsp.md)) |
| `RUN_SKILL_GENERATOR` † | 1 (1) | [skills/bundled/index.ts](../../skills/bundled/index.ts) | Registers bundled skill-generator meta-skill ([Ch 16](../chapters/16-skills-plugins-output-styles-and-lsp.md)) |
| `SKILL_IMPROVEMENT` | 1 (1) | [utils/hooks/skillImprovement.ts](../../utils/hooks/skillImprovement.ts) | Post-sampling hook updating skills from execution traces (`tengu_copper_panda`) ([Ch 13](../chapters/13-the-hook-system.md), [Ch 16](../chapters/16-skills-plugins-output-styles-and-lsp.md)) |
| `TORCH` † | 1 (1) | [commands.ts](../../commands.ts) | Registers internal `/torch` slash command (module absent from snapshot) ([Ch 03](../chapters/03-command-and-message-contracts.md)) |

### 2.5 UI, Voice, Bridge, Remote & Daemon (22 flags, 153 sites)

| Flag | Sites (Files) | Primary Source Files | Role & Companion Chapter |
| :--- | :---: | :--- | :--- |
| `VOICE_MODE` † | 47 (15) | [hooks/useVoiceIntegration.tsx](../../hooks/useVoiceIntegration.tsx), [voice/voiceModeEnabled.ts](../../voice/voiceModeEnabled.ts), [screens/REPL.tsx](../../screens/REPL.tsx) | Push-to-talk speech-to-text input (`space` hold-to-talk, streaming STT) ([Ch 21](../chapters/21-the-interactive-repl-screens-keybindings-and-vim.md)) |
| `BRIDGE_MODE` | 27 (13) | [hooks/useReplBridge.tsx](../../hooks/useReplBridge.tsx), [bridge/bridgeEnabled.ts](../../bridge/bridgeEnabled.ts), [main.tsx](../../main.tsx) | Remote Control REPL bridge connecting local CLI to `claude.ai` (`tengu_ccr_bridge`) ([Ch 24](../chapters/24-across-the-wire-remote-sessions-bridge-and-direct-connect.md)) |
| `BUDDY` † | 18 (7) | [screens/REPL.tsx](../../screens/REPL.tsx), [buddy/CompanionSprite.tsx](../../buddy/CompanionSprite.tsx), [components/PromptInput/PromptInput.tsx](../../components/PromptInput/PromptInput.tsx) | Terminal ASCII companion sprite and `/buddy` reactions ([Ch 21](../chapters/21-the-interactive-repl-screens-keybindings-and-vim.md)) |
| `LODESTONE` | 6 (4) | [main.tsx](../../main.tsx), [utils/backgroundHousekeeping.ts](../../utils/backgroundHousekeeping.ts), [interactiveHelpers.tsx](../../interactiveHelpers.tsx) | Deep-link URI protocol registration and `--handle-uri` launcher ([Ch 22](../chapters/22-cold-start-mastery-cli-init-main.md)) |
| `DIRECT_CONNECT` | 5 (1) | [main.tsx](../../main.tsx) | `--connect` direct WebSocket/HTTP server session attachment ([Ch 24](../chapters/24-across-the-wire-remote-sessions-bridge-and-direct-connect.md)) |
| `DOWNLOAD_USER_SETTINGS` | 5 (3) | [cli/print.ts](../../cli/print.ts), [services/settingsSync/index.ts](../../services/settingsSync/index.ts), [commands/reload-plugins/reload-plugins.ts](../../commands/reload-plugins/reload-plugins.ts) | Pulls cloud-synced user settings into remote/headless sessions ([Ch 14](../chapters/14-configuration-settings-and-enterprise-policy.md)) |
| `MESSAGE_ACTIONS` | 5 (2) | [screens/REPL.tsx](../../screens/REPL.tsx), [keybindings/defaultBindings.ts](../../keybindings/defaultBindings.ts) | `shift+up` message action menu (copy/rewind/branch on prior turns) ([Ch 21](../chapters/21-the-interactive-repl-screens-keybindings-and-vim.md)) |
| `QUICK_SEARCH` | 5 (2) | [components/PromptInput/PromptInput.tsx](../../components/PromptInput/PromptInput.tsx), [keybindings/defaultBindings.ts](../../keybindings/defaultBindings.ts) | `ctrl+shift+f` / `cmd+shift+f` global transcript search overlay ([Ch 21](../chapters/21-the-interactive-repl-screens-keybindings-and-vim.md)) |
| `CCR_MIRROR` | 4 (3) | [bridge/remoteBridgeCore.ts](../../bridge/remoteBridgeCore.ts), [bridge/bridgeEnabled.ts](../../bridge/bridgeEnabled.ts), [main.tsx](../../main.tsx) | Read-only mirror of local CLI turns to `claude.ai` without full remote control ([Ch 24](../chapters/24-across-the-wire-remote-sessions-bridge-and-direct-connect.md)) |
| `HISTORY_PICKER` | 4 (2) | [components/PromptInput/PromptInput.tsx](../../components/PromptInput/PromptInput.tsx), [hooks/useHistorySearch.ts](../../hooks/useHistorySearch.ts) | Interactive scrollable prompt history picker modal ([Ch 21](../chapters/21-the-interactive-repl-screens-keybindings-and-vim.md)) |
| `KAIROS_PUSH_NOTIFICATION` | 4 (3) | [components/Settings/Config.tsx](../../components/Settings/Config.tsx), [tools.ts](../../tools.ts), [tools/ConfigTool/supportedSettings.ts](../../tools/ConfigTool/supportedSettings.ts) | Mobile/desktop push notifications on task completion (`PushNotificationTool`) ([Ch 24](../chapters/24-across-the-wire-remote-sessions-bridge-and-direct-connect.md)) |
| `SSH_REMOTE` | 4 (1) | [main.tsx](../../main.tsx) | `claude ssh` remote execution launcher with forwarded auth socket ([Ch 22](../chapters/22-cold-start-mastery-cli-init-main.md)) |
| `AUTO_THEME` † | 3 (3) | [components/ThemePicker.tsx](../../components/ThemePicker.tsx), [components/design-system/ThemeProvider.tsx](../../components/design-system/ThemeProvider.tsx), [tools/ConfigTool/supportedSettings.ts](../../tools/ConfigTool/supportedSettings.ts) | OS dark/light automatic theme switching (`systemThemeWatcher`) ([Ch 20](../chapters/20-inside-ink-terminal-react-renderer.md)) |
| `CCR_AUTO_CONNECT` | 3 (2) | [utils/config.ts](../../utils/config.ts), [bridge/bridgeEnabled.ts](../../bridge/bridgeEnabled.ts) | Automatic remote-control bridge reconnection (`tengu_cobalt_harbor`) ([Ch 24](../chapters/24-across-the-wire-remote-sessions-bridge-and-direct-connect.md)) |
| `DAEMON` † | 3 (2) | [entrypoints/cli.tsx](../../entrypoints/cli.tsx), [commands.ts](../../commands.ts) | Persistent background daemon supervisor (`claude daemon` / `/remote-control-server`) ([Ch 22](../chapters/22-cold-start-mastery-cli-init-main.md), [Ch 24](../chapters/24-across-the-wire-remote-sessions-bridge-and-direct-connect.md)) |
| `AWAY_SUMMARY` | 2 (2) | [hooks/useAwaySummary.ts](../../hooks/useAwaySummary.ts), [screens/REPL.tsx](../../screens/REPL.tsx) | Generates catch-up summary after terminal loses focus for 5+ minutes ([Ch 20](../chapters/20-inside-ink-terminal-react-renderer.md), [Ch 21](../chapters/21-the-interactive-repl-screens-keybindings-and-vim.md)) |
| `NATIVE_CLIPBOARD_IMAGE` | 2 (1) | [utils/imagePaste.ts](../../utils/imagePaste.ts) | Native macOS `NSPasteboard` image read (~0.03ms) avoiding `osascript` spawn ([Ch 21](../chapters/21-the-interactive-repl-screens-keybindings-and-vim.md)) |
| `UPLOAD_USER_SETTINGS` | 2 (2) | [services/settingsSync/index.ts](../../services/settingsSync/index.ts), [main.tsx](../../main.tsx) | Uploads local user settings to cloud sync in background ([Ch 14](../chapters/14-configuration-settings-and-enterprise-policy.md)) |
| `BYOC_ENVIRONMENT_RUNNER` † | 1 (1) | [entrypoints/cli.tsx](../../entrypoints/cli.tsx) | Fast-path `claude environment-runner` entrypoint for Bring-Your-Own-Cloud containers ([Ch 22](../chapters/22-cold-start-mastery-cli-init-main.md)) |
| `CCR_REMOTE_SETUP` | 1 (1) | [commands.ts](../../commands.ts) | Registers `/web-setup` command for Claude Code on the web (`tengu_cobalt_lantern`) ([Ch 24](../chapters/24-across-the-wire-remote-sessions-bridge-and-direct-connect.md)) |
| `SELF_HOSTED_RUNNER` † | 1 (1) | [entrypoints/cli.tsx](../../entrypoints/cli.tsx) | Fast-path `claude self-hosted-runner` worker entrypoint ([Ch 22](../chapters/22-cold-start-mastery-cli-init-main.md)) |
| `STREAMLINED_OUTPUT` | 1 (1) | [cli/print.ts](../../cli/print.ts) | Compact NDJSON transformer for `--output-format stream-json` (`CLAUDE_CODE_STREAMLINED_OUTPUT`) ([Ch 23](../chapters/23-machine-readable-modes-headless-sdk-and-control-protocols.md)) |

### 2.6 Internal, Telemetry, Build & Release (16 flags, 39 sites)

| Flag | Sites (Files) | Primary Source Files | Role & Companion Chapter |
| :--- | :---: | :--- | :--- |
| `COMMIT_ATTRIBUTION` † | 12 (9) | [cli/print.ts](../../cli/print.ts), [utils/sessionRestore.ts](../../utils/sessionRestore.ts), [setup.ts](../../setup.ts) | Tracks AI-authored commit attribution hooks & git trailers ([Ch 14](../chapters/14-configuration-settings-and-enterprise-policy.md)) |
| `SHOT_STATS` | 10 (3) | [utils/stats.ts](../../utils/stats.ts), [utils/statsCache.ts](../../utils/statsCache.ts), [components/Stats.tsx](../../components/Stats.tsx) | Per-session prompt/shot distribution histograms in `/stats` ([Ch 05](../chapters/05-talking-to-the-model.md)) |
| `ALLOW_TEST_VERSIONS` | 2 (1) | [utils/nativeInstaller/download.ts](../../utils/nativeInstaller/download.ts) | Allows installing `99.99.*` synthetic test release versions ([Ch 22](../chapters/22-cold-start-mastery-cli-init-main.md)) |
| `COWORKER_TYPE_TELEMETRY` | 2 (1) | [services/analytics/metadata.ts](../../services/analytics/metadata.ts) | Attaches `CLAUDE_CODE_COWORKER_TYPE` dimension to analytics events ([Ch 05](../chapters/05-talking-to-the-model.md)) |
| `HARD_FAIL` | 2 (2) | [main.tsx](../../main.tsx), [utils/log.ts](../../utils/log.ts) | Adds hidden `--hard-fail` CLI flag that crashes immediately on any `logError()` ([Ch 22](../chapters/22-cold-start-mastery-cli-init-main.md)) |
| `ABLATION_BASELINE` | 1 (1) | [entrypoints/cli.tsx](../../entrypoints/cli.tsx) | Harness-science L0 ablation preset setting 7 disable env vars before module imports ([Ch 22](../chapters/22-cold-start-mastery-cli-init-main.md)) |
| `ANTI_DISTILLATION_CC` | 1 (1) | [services/api/claude.ts](../../services/api/claude.ts) | Sends `anti_distillation: ['fake_tools']` on 1P CLI requests (`tengu_anti_distill_fake_tool_injection`) ([Ch 05](../chapters/05-talking-to-the-model.md)) |
| `DUMP_SYSTEM_PROMPT` | 1 (1) | [entrypoints/cli.tsx](../../entrypoints/cli.tsx) | Zero-REPL `--dump-system-prompt` fast-path for prompt inspection ([Ch 04](../chapters/04-prompt-engineering-and-cache-boundaries.md), [Ch 22](../chapters/22-cold-start-mastery-cli-init-main.md)) |
| `ENHANCED_TELEMETRY_BETA` | 1 (1) | [utils/telemetry/sessionTracing.ts](../../utils/telemetry/sessionTracing.ts) | Enables detailed OpenTelemetry span tracing beta ([Ch 05](../chapters/05-talking-to-the-model.md)) |
| `IS_LIBC_GLIBC` | 1 (1) | [utils/envDynamic.ts](../../utils/envDynamic.ts) | Compile-time assertion that target Linux binary uses glibc ([Ch 22](../chapters/22-cold-start-mastery-cli-init-main.md)) |
| `IS_LIBC_MUSL` | 1 (1) | [utils/envDynamic.ts](../../utils/envDynamic.ts) | Compile-time assertion that target Linux binary uses musl ([Ch 22](../chapters/22-cold-start-mastery-cli-init-main.md)) |
| `NATIVE_CLIENT_ATTESTATION` | 1 (1) | [constants/system.ts](../../constants/system.ts) | Inserts `cch=00000;` in attribution header for Zig HTTP stack attestation ([Ch 05](../chapters/05-talking-to-the-model.md)) |
| `PERFETTO_TRACING` | 1 (1) | [utils/telemetry/perfettoTracing.ts](../../utils/telemetry/perfettoTracing.ts) | Enables Perfetto protobuf performance trace writer (`CLAUDE_CODE_PERFETTO_TRACE`) ([Ch 22](../chapters/22-cold-start-mastery-cli-init-main.md)) |
| `SKIP_DETECTION_WHEN_AUTOUPDATES_DISABLED` | 1 (1) | [components/AutoUpdaterWrapper.tsx](../../components/AutoUpdaterWrapper.tsx) | Skips update version checks completely when auto-updates are disabled ([Ch 14](../chapters/14-configuration-settings-and-enterprise-policy.md)) |
| `SLOW_OPERATION_LOGGING` | 1 (1) | [utils/slowOperations.ts](../../utils/slowOperations.ts) | Swaps in internal slow-JSON/op logging thresholds (`slowLoggingAnt` vs. `slowLoggingExternal`) ([Ch 01](../chapters/01-atoms-types-stores-and-primitives.md)) |
| `UNATTENDED_RETRY` | 1 (1) | [services/api/withRetry.ts](../../services/api/withRetry.ts) | Allows infinite/extended retries for headless evals (`CLAUDE_CODE_UNATTENDED_RETRY`) ([Ch 05](../chapters/05-talking-to-the-model.md)) |

---

## 3. The `USER_TYPE === 'ant'` Split: Constant Folding Across `.tsx` vs. `.ts`

Alongside `feature()`, the codebase contains a second compile-time axis distinguishing Anthropic internal ("ant") builds from public releases (`"external"`). Inspecting this snapshot reveals an immediate, striking asymmetry between `.ts` and `.tsx` files:

| Pattern | `.ts` Files (1,332 total) | `.tsx` Files (552 total) | Notes |
| :--- | :---: | :---: | :--- |
| `process.env.USER_TYPE` | **357** hits (165 files) | **0** executable hits (3 comments) | Top `.ts` sites: `firstPartyEventLoggingExporter.ts` (19), `growthbook.ts` (17), `insights.ts` (10), `mockRateLimits.ts` (9), `prompts.ts` (12) |
| `"external" === 'ant'` | **0** hits | **88** hits (27 files) | Constant-folded by build define prior to React Compiler output |
| `"external" !== 'ant'` | **0** hits | **7** hits (7 files) | Combined with `===`, **95** folded checks across **31** unique `.tsx` files |
| Inline `sourceMappingURL=` | **0** / 1,332 files | **552** / 552 files | Every `.tsx` file passed through the React Compiler + define transform |

Why does `"external" === 'ant'` appear exclusively in `.tsx` files? Because in the build pipeline that produced this snapshot, `.tsx` files were run through the React Compiler transform (`_c(...)` memoization slots + inline base64 `sourceMappingURL`) with the bundler define `process.env.USER_TYPE = "external"` already substituted—while `.ts` files bypassed the JSX/React Compiler pass and preserved their raw `process.env.USER_TYPE === 'ant'` expressions.

You can verify that `USER_TYPE` is structurally guaranteed to be a build-time constant (never toggled at runtime) from [components/MemoryUsageIndicator.tsx](../../components/MemoryUsageIndicator.tsx):

```tsx
// components/MemoryUsageIndicator.tsx:5-16
export function MemoryUsageIndicator(): React.ReactNode {
  // Ant-only: the /heapdump link is an internal debugging aid. Gating before
  // the hook means the 10s polling interval is never set up in external builds.
  // USER_TYPE is a build-time constant, so the hook call below is either always
  // reached or dead-code-eliminated — never conditional at runtime.
  if ("external" !== 'ant') {
    return null;
  }

  // eslint-disable-next-line react-hooks/rules-of-hooks
  // biome-ignore lint/correctness/useHookAtTopLevel: USER_TYPE is a build-time constant
  const memoryUsage = useMemoryUsage();
```

Placing a React hook after an `if` return would violate the Rules of Hooks if `USER_TYPE` could ever vary dynamically; it is safe *only* because the bundler folds `"external" !== 'ant'` to `true` and dead-code-eliminates `useMemoryUsage()` in external builds (and folds `'ant' !== 'ant'` to `false` in internal builds).

> [!IMPORTANT]
> **`feature()` vs. `USER_TYPE === 'ant'`:** Use `USER_TYPE === 'ant'` for behavior strictly scoped to Anthropic employees (internal telemetry exporters, `/heapdump`, `isUndercover()`, ant-only model overrides, `mockRateLimits.ts`). Use `feature('...')` for capabilities that ship in *some* external builds or need independent build-matrix ablation—as [main.tsx:2662](../../main.tsx) explicitly notes: *"Gated on `TRANSCRIPT_CLASSIFIER` (not `USER_TYPE`) so GrowthBook kill switch runs for external builds too."*

---

## 4. Environment Variable Architecture: Trust Boundaries, Filters, and Subprocess Scrubbing

The codebase reads **472 distinct `process.env.*` keys** (`196` `CLAUDE_CODE_*`, `31` other `CLAUDE_*`, `26` `ANTHROPIC_*`, `21` `DISABLE_*`, `16` `OTEL_*`, `12` `ENABLE_*`, `8` `MCP_*`, `7` `USE_*`, plus standard OS/cloud/proxy variables). Before consulting the tables in Section 5, four load-bearing invariants govern how every variable enters, overrides, and exits `process.env`.

### Invariant 1: Strict Tri-State Boolean Parsing

In [utils/envUtils.ts:32-47](../../utils/envUtils.ts), boolean knobs are never parsed with bare `Boolean(process.env.X)` (which would treat `"0"` and `"false"` as truthy):

```ts
// utils/envUtils.ts:32-47
export function isEnvTruthy(envVar: string | boolean | undefined): boolean {
  if (!envVar) return false
  if (typeof envVar === 'boolean') return envVar
  const normalizedValue = envVar.toLowerCase().trim()
  return ['1', 'true', 'yes', 'on'].includes(normalizedValue)
}

export function isEnvDefinedFalsy(
  envVar: string | boolean | undefined,
): boolean {
  if (envVar === undefined) return false
  if (typeof envVar === 'boolean') return !envVar
  if (!envVar) return false
  const normalizedValue = envVar.toLowerCase().trim()
  return ['0', 'false', 'no', 'off'].includes(normalizedValue)
}
```

Notice the subtle tri-state boundary: an empty string `""` returns `false` for **both** `isEnvTruthy("")` and `isEnvDefinedFalsy("")`, allowing unset/empty values to fall back to defaults (e.g., `CLAUDE_CODE_NO_FLICKER=0` explicitly opts out an ant user, while empty falls through to the build default in [utils/fullscreen.ts:108-125](../../utils/fullscreen.ts)).

### Invariant 2: Pre-Trust `SAFE_ENV_VARS` Allowlist

Because `settings.json` supports an `"env": { ... }` map, a malicious Git repository could commit `.claude/settings.json` with `ANTHROPIC_BASE_URL` pointing to an attacker's proxy, `NODE_EXTRA_CA_CERTS` trusting an attacker's CA, or `HTTP_PROXY` hijacking first-run auth traffic *before* the user answers the workspace trust dialog.

[utils/managedEnv.ts:93-199](../../utils/managedEnv.ts) solves this with a two-phase loader wired into `init.ts` (see [Chapter 14](../chapters/14-configuration-settings-and-enterprise-policy.md) and [Chapter 22](../chapters/22-cold-start-mastery-cli-init-main.md)):

```text
  Phase 1: applySafeConfigEnvironmentVariables()   [BEFORE trust dialog]
    - Trusted sources (userSettings, flagSettings, policySettings): ALL vars
    - Untrusted sources (projectSettings, localSettings): ONLY SAFE_ENV_VARS
      (blocked: ANTHROPIC_BASE_URL, HTTP(S)_PROXY, NODE_EXTRA_CA_CERTS,
       NODE_TLS_REJECT_UNAUTHORIZED, ANTHROPIC_API_KEY, LD_PRELOAD, PATH)
                              |
                              v  (user grants workspace trust)
  Phase 2: applyConfigEnvironmentVariables()       [AFTER trust dialog]
    - Merges all settings.env keys -> clears CA, mTLS, & proxy caches
    - Rebuilds global HTTP/HTTPS agents via configureGlobalAgents()
```

### Invariant 3: Three Host-Protection Strip Filters

Every settings-sourced `env` object passes through `filterSettingsEnv()` ([utils/managedEnv.ts:85-91](../../utils/managedEnv.ts)), composing three strip guards:

1. **`withoutSSHTunnelVars()`**: When `ANTHROPIC_UNIX_SOCKET` is set (`claude ssh`), strips `ANTHROPIC_UNIX_SOCKET`, `ANTHROPIC_BASE_URL`, `ANTHROPIC_API_KEY`, `ANTHROPIC_AUTH_TOKEN`, and `CLAUDE_CODE_OAUTH_TOKEN` so the remote host's `~/.claude/settings.json` cannot clobber the forwarded local auth tunnel.
2. **`withoutHostManagedProviderVars()`**: When `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST` is truthy, strips all `PROVIDER_MANAGED_ENV_VARS` plus any `VERTEX_REGION_CLAUDE_*` prefix ([utils/managedEnvConstants.ts:14-70](../../utils/managedEnvConstants.ts)) so a user's personal Bedrock/Vertex settings cannot hijack an enterprise or desktop host's inference routing.
3. **`withoutCcdSpawnEnvKeys()`**: When `CLAUDE_CODE_ENTRYPOINT === 'claude-desktop'`, snapshots all spawn-time env keys on first call and strips them from settings so user settings (e.g., `OTEL_LOGS_EXPORTER=console`) cannot corrupt the desktop host's stdio JSON-RPC stream.

### Invariant 4: Child-Process Secret Scrubbing (`subprocessEnv()`)

When running in untrusted automation (such as GitHub Actions with `allowed_non_write_users`), prompt injection inside a Bash tool could execute `echo $ANTHROPIC_API_KEY`. [utils/subprocessEnv.ts:15-99](../../utils/subprocessEnv.ts) wraps every child spawn (Bash, shell snapshots, MCP stdio, LSP, shell hooks): when `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` is truthy, it deletes 23 secret keys (`GHA_SUBPROCESS_SCRUB`: Anthropic auth, OTLP headers, AWS/GCP/Azure credentials, GitHub OIDC & runtime tokens, `SSH_SIGNING_KEY`, `ALL_INPUTS`) **plus their `INPUT_<KEY>` GitHub Actions duplicates**, while keeping them intact inside the parent Claude Code process and merging CCR's `_getUpstreamProxyEnv()` relay vars.

---

## 5. Load-Bearing Environment Knobs by Subsystem

Every variable name and primary file path below is verified directly against this snapshot.

### 5.1 Startup, Paths, Isolation & Diagnostics

| Environment Variable | Primary Source File(s) | Effect & Invariant |
| :--- | :--- | :--- |
| `CLAUDE_CONFIG_DIR` | [utils/envUtils.ts](../../utils/envUtils.ts), [utils/env.ts](../../utils/env.ts) | Overrides `~/.claude` config root (memoized & NFC-normalized; keyed on var) |
| `CLAUDE_CODE_SIMPLE` | [utils/envUtils.ts](../../utils/envUtils.ts), [main.tsx](../../main.tsx) | `--bare` mode: skips hooks, LSP, plugin sync, skill walk, and all keychain reads (~30 gates) |
| `CLAUDE_CODE_ENTRYPOINT` | [main.tsx](../../main.tsx), [services/analytics/metadata.ts](../../services/analytics/metadata.ts) | Identifies launch surface (`cli`, `claude-desktop`, `sdk-ts`, etc.); activates CCD env snapshot & attestation |
| `CLAUDE_CODE_ABLATION_BASELINE` | [entrypoints/cli.tsx](../../entrypoints/cli.tsx) | Behind `feature('ABLATION_BASELINE')`: forces 7 disable env vars at line 21 before module load |
| `CLAUDE_CODE_PROFILE_STARTUP` | [utils/startupProfiler.ts](../../utils/startupProfiler.ts), [utils/headlessProfiler.ts](../../utils/headlessProfiler.ts) | Emits cold-start checkpoint timing breakdown ([Ch 22](../chapters/22-cold-start-mastery-cli-init-main.md)) |
| `CLAUDE_CODE_PROFILE_QUERY` | [utils/queryProfiler.ts](../../utils/queryProfiler.ts) | Profiles per-turn query loop latency stages |
| `CLAUDE_CODE_EXIT_AFTER_FIRST_RENDER` | [cli/print.ts](../../cli/print.ts), [hooks/useAfterFirstRender.ts](../../hooks/useAfterFirstRender.ts) | Exits immediately after initial Ink frame for startup benchmarking |
| `CLAUDE_CODE_DEBUG_LOGS_DIR` | [utils/debug.ts](../../utils/debug.ts) | Redirects debug log files from default temp/config directory |
| `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` | [utils/privacyLevel.ts](../../utils/privacyLevel.ts) | Sets privacy level `essential-traffic`: disables telemetry, auto-updater, error reporting, and marketplace calls |
| `DISABLE_TELEMETRY` | [utils/privacyLevel.ts](../../utils/privacyLevel.ts) | Sets privacy level `no-telemetry` (keeps non-telemetry network calls active) |
| `DISABLE_AUTOUPDATER` | [utils/config.ts](../../utils/config.ts) | Disables background CLI auto-updates |
| `CLAUDE_CODE_ENABLE_TELEMETRY` | [utils/telemetry/instrumentation.ts](../../utils/telemetry/instrumentation.ts) | Activates OpenTelemetry metrics/logs/traces export (`OTEL_EXPORTER_OTLP_*`, `OTEL_METRICS_EXPORTER`, `OTEL_LOGS_EXPORTER`) |
| `CLAUDE_CODE_OTEL_FLUSH_TIMEOUT_MS` | [utils/telemetry/instrumentation.ts](../../utils/telemetry/instrumentation.ts) | Caps OTel exporter flush wait during graceful shutdown |
| `IS_DEMO` | [components/LogoV2/LogoV2.tsx](../../components/LogoV2/LogoV2.tsx), [utils/status.tsx](../../utils/status.tsx) | Hides sensitive account/email/org details in terminal banners for demos |
| `CLAUDE_CODE_TMPDIR` | [utils/imagePaste.ts](../../utils/imagePaste.ts), [utils/permissions/filesystem.ts](../../utils/permissions/filesystem.ts) | Overrides temp directory used by shell providers, clipboard paste, and scratch files |

### 5.2 Model, Inference Providers, Auth & Streaming

| Environment Variable | Primary Source File(s) | Effect & Invariant |
| :--- | :--- | :--- |
| `ANTHROPIC_API_KEY` | [utils/auth.ts](../../utils/auth.ts), [components/Settings/Config.tsx](../../components/Settings/Config.tsx) | First-party API key (stripped from untrusted project settings and scrubbed subprocesses) |
| `ANTHROPIC_AUTH_TOKEN` | [utils/auth.ts](../../utils/auth.ts), [services/api/client.ts](../../services/api/client.ts) | Custom `Authorization: Bearer` token for gateways/proxies |
| `ANTHROPIC_BASE_URL` | [services/api/client.ts](../../services/api/client.ts), [services/api/logging.ts](../../services/api/logging.ts) | Overrides first-party API origin (non-1P host auto-disables optimistic ToolSearch unless explicitly set) |
| `ANTHROPIC_MODEL` | [main.tsx](../../main.tsx), [utils/model/model.ts](../../utils/model/model.ts) | Overrides primary loop model alias or full model ID |
| `ANTHROPIC_SMALL_FAST_MODEL` | [utils/model/model.ts](../../utils/model/model.ts), [services/api/logging.ts](../../services/api/logging.ts) | Overrides auxiliary fast model (Haiku-tier helpers, summaries, prefetches) |
| `ANTHROPIC_DEFAULT_{OPUS,SONNET,HAIKU}_MODEL` | [utils/model/model.ts](../../utils/model/model.ts), [utils/model/modelOptions.ts](../../utils/model/modelOptions.ts) | Remaps model tier aliases to provider-specific IDs (e.g., Bedrock ARNs or Vertex IDs) |
| `ANTHROPIC_BETAS` / `ANTHROPIC_CUSTOM_HEADERS` | [utils/betas.ts](../../utils/betas.ts), [services/api/client.ts](../../services/api/client.ts) | Comma-separated extra beta headers / custom `Key: Value` HTTP headers injected on API calls |
| `CLAUDE_CODE_USE_{BEDROCK,VERTEX,FOUNDRY}` | [utils/auth.ts](../../utils/auth.ts), [services/api/client.ts](../../services/api/client.ts) | Switches inference backend to AWS Bedrock, Google Vertex AI, or Azure Foundry ([Ch 05](../chapters/05-talking-to-the-model.md)) |
| `CLAUDE_CODE_SKIP_{BEDROCK,VERTEX,FOUNDRY}_AUTH` | [services/api/client.ts](../../services/api/client.ts), [utils/model/bedrock.ts](../../utils/model/bedrock.ts) | Bypasses cloud SDK SigV4/IAM/ADC auth for authenticating proxy gateways |
| `CLAUDE_CODE_OAUTH_TOKEN` | [utils/auth.ts](../../utils/auth.ts), [bridge/bridgeEnabled.ts](../../bridge/bridgeEnabled.ts) | Injects OAuth access token directly (note: lacks `user:profile` scope for some GrowthBook org gates) |
| `CLAUDE_CODE_API_KEY_HELPER_TTL_MS` | [utils/auth.ts](../../utils/auth.ts) | Cache TTL for `apiKeyHelper` shell command output |
| `CLAUDE_CODE_MAX_OUTPUT_TOKENS` | [query.ts](../../query.ts), [services/api/claude.ts](../../services/api/claude.ts) | Overrides per-turn `max_tokens` ceiling sent to the Messages API |
| `MAX_THINKING_TOKENS` | [utils/thinking.ts](../../utils/thinking.ts), [main.tsx](../../main.tsx) | Explicit extended-thinking token budget (`0` disables thinking) |
| `CLAUDE_CODE_EFFORT_LEVEL` | [utils/effort.ts](../../utils/effort.ts), [commands/effort/effort.tsx](../../commands/effort/effort.tsx) | Sets reasoning effort (`low`/`medium`/`high`/`max`/`unset`); `CLAUDE_CODE_ALWAYS_ENABLE_EFFORT` forces on 3P |
| `CLAUDE_CODE_DISABLE_THINKING` / `DISABLE_INTERLEAVED_THINKING` | [services/api/claude.ts](../../services/api/claude.ts), [utils/betas.ts](../../utils/betas.ts) | Disables extended thinking or interleaved-thinking beta header |
| `CLAUDE_CODE_DISABLE_FAST_MODE` | [utils/fastMode.ts](../../utils/fastMode.ts), [query/config.ts](../../query/config.ts) | Hard kill switch disabling fast-mode inference |
| `CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS` | [utils/betas.ts](../../utils/betas.ts), [utils/toolSearch.ts](../../utils/toolSearch.ts) | Strips 1P experimental beta headers and `schema.strict` for third-party proxy compatibility |
| `CLAUDE_CODE_MAX_RETRIES` / `API_TIMEOUT_MS` | [services/api/withRetry.ts](../../services/api/withRetry.ts), [services/api/client.ts](../../services/api/client.ts) | Tunes transient HTTP retry count and per-request socket timeout |
| `CLAUDE_CODE_ATTRIBUTION_HEADER` | [constants/system.ts](../../constants/system.ts) | Set falsy (`0`/`false`) to omit `cc_version`/`cc_entrypoint` attribution header |
| `DISABLE_PROMPT_CACHING` | [services/api/claude.ts](../../services/api/claude.ts) | Disables `cache_control` breakpoints (also per-tier: `DISABLE_PROMPT_CACHING_{OPUS,SONNET,HAIKU}`) |

### 5.3 Compaction, Context Window & Memory

| Environment Variable | Primary Source File(s) | Effect & Invariant |
| :--- | :--- | :--- |
| `DISABLE_COMPACT` / `DISABLE_AUTO_COMPACT` | [services/compact/autoCompact.ts](../../services/compact/autoCompact.ts), [commands/compact/index.ts](../../commands/compact/index.ts) | Disables all compaction (incl. `/compact`) or disables automatic compaction only ([Ch 09](../chapters/09-five-layer-compaction-pipeline.md)) |
| `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` | [services/compact/autoCompact.ts](../../services/compact/autoCompact.ts) | Triggers auto-compaction at custom percentage (`1`–`100`) of effective context window |
| `CLAUDE_CODE_AUTO_COMPACT_WINDOW` | [services/compact/autoCompact.ts](../../services/compact/autoCompact.ts) | Caps effective token window used when computing auto-compact thresholds |
| `CLAUDE_CODE_BLOCKING_LIMIT_OVERRIDE` | [services/compact/autoCompact.ts](../../services/compact/autoCompact.ts) | Overrides hard token ceiling where the loop refuses new turns |
| `ENABLE_CLAUDE_CODE_SM_COMPACT` / `DISABLE_CLAUDE_CODE_SM_COMPACT` | [services/compact/sessionMemoryCompact.ts](../../services/compact/sessionMemoryCompact.ts) | Force-enables or disables session-memory-backed compaction (avoids full summarization call) |
| `USE_API_CLEAR_TOOL_RESULTS` / `USE_API_CLEAR_TOOL_USES` | [services/compact/apiMicrocompact.ts](../../services/compact/apiMicrocompact.ts) | Switches Stage 3 microcompaction to server-side `context_management` tool-clearing API edits |
| `USE_API_CONTEXT_MANAGEMENT` | [utils/betas.ts](../../utils/betas.ts) | Ant-only opt-in for server-side context management beta header |
| `CLAUDE_CODE_DISABLE_1M_CONTEXT` / `CLAUDE_CODE_MAX_CONTEXT_TOKENS` | [utils/context.ts](../../utils/context.ts) | Opts out of 1M-token context window or clamps effective context window size |
| `CLAUDE_CODE_DISABLE_CLAUDE_MDS` | [context.ts](../../context.ts) | Suppresses loading hierarchical `CLAUDE.md` instruction files ([Ch 10](../chapters/10-memory-systems-claudemd-auto-memory-and-dream.md)) |
| `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` | [utils/claudemd.ts](../../utils/claudemd.ts) | Loads `CLAUDE.md` files from `--add-dir` extra directories (off by default) |
| `CLAUDE_CODE_DISABLE_AUTO_MEMORY` | [memdir/memdir.ts](../../memdir/memdir.ts), [memdir/paths.ts](../../memdir/paths.ts) | Disables persistent cross-session auto-memory directory (`memdir/`) |
| `CLAUDE_CODE_REMOTE_MEMORY_DIR` | [memdir/paths.ts](../../memdir/paths.ts), [tools/AgentTool/agentMemory.ts](../../tools/AgentTool/agentMemory.ts) | Redirects auto-memory storage to a mounted remote/shared directory |
| `CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING` / `CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING` | [utils/fileHistory.ts](../../utils/fileHistory.ts) | Disables `/rewind` disk snapshots in interactive mode or enables them in headless SDK runs ([Ch 08](../chapters/08-session-envelope-query-engine-and-transcripts.md)) |

### 5.4 Permissions, Shell, Sandboxing & Workspace Tools

| Environment Variable | Primary Source File(s) | Effect & Invariant |
| :--- | :--- | :--- |
| `IS_SANDBOX` | [setup.ts](../../setup.ts), [services/api/withRetry.ts](../../services/api/withRetry.ts) | Declares execution inside an isolated container (permits `--dangerously-skip-permissions` as root) |
| `CLAUDE_CODE_BUBBLEWRAP` | [utils/envDynamic.ts](../../utils/envDynamic.ts), [setup.ts](../../setup.ts) | Signals Linux `bwrap` sandbox environment ([Ch 12](../chapters/12-shell-execution-sandboxing-and-workspace-tools.md)) |
| `CLAUDE_CODE_DISABLE_COMMAND_INJECTION_CHECK` | [tools/BashTool/bashPermissions.ts](../../tools/BashTool/bashPermissions.ts) | Disables Bash AST/regex command-injection validator (high-risk override) |
| `CLAUDE_CODE_SUBPROCESS_ENV_SCRUB` | [utils/subprocessEnv.ts](../../utils/subprocessEnv.ts) | Strips `GHA_SUBPROCESS_SCRUB` + `INPUT_*` credentials from all child tool/hook/MCP/LSP processes |
| `CLAUDE_CODE_MANAGED_SETTINGS_PATH` | [utils/settings/managedPath.ts](../../utils/settings/managedPath.ts) | Overrides enterprise `managed-settings.json` location ([Ch 14](../chapters/14-configuration-settings-and-enterprise-policy.md)) |
| `CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST` | [utils/managedEnv.ts](../../utils/managedEnv.ts), [utils/managedEnvConstants.ts](../../utils/managedEnvConstants.ts) | Locks inference provider/endpoint/model env vars against user settings overrides |
| `CLAUDE_CODE_SHELL` / `CLAUDE_CODE_SHELL_PREFIX` | [utils/Shell.ts](../../utils/Shell.ts), [utils/shell/bashProvider.ts](../../utils/shell/bashProvider.ts) | Forces specific shell binary or wraps every shell/MCP command in a prefix wrapper |
| `CLAUDE_BASH_MAINTAIN_PROJECT_WORKING_DIR` | [utils/envUtils.ts](../../utils/envUtils.ts) | Resets shell `cwd` back to project root after every `BashTool` invocation |
| `BASH_DEFAULT_TIMEOUT_MS` / `BASH_MAX_TIMEOUT_MS` | [utils/timeouts.ts](../../utils/timeouts.ts) | Sets default and upper-bound timeout for `BashTool` commands |
| `BASH_MAX_OUTPUT_LENGTH` | [utils/shell/outputLimits.ts](../../utils/shell/outputLimits.ts) | Caps inline Bash stdout/stderr chars before truncation/spill |
| `CLAUDE_CODE_USE_POWERSHELL_TOOL` | [utils/shell/shellToolUtils.ts](../../utils/shell/shellToolUtils.ts) | Enables native Windows `PowerShellTool` alongside/instead of Git Bash |
| `CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY` | [services/tools/toolOrchestration.ts](../../services/tools/toolOrchestration.ts) | Max parallel read-only tool calls per assistant turn (default `10`; [Ch 06](../chapters/06-executing-tools.md)) |
| `CLAUDE_CODE_FILE_READ_MAX_OUTPUT_TOKENS` | [tools/FileReadTool/limits.ts](../../tools/FileReadTool/limits.ts) | Overrides per-call token ceiling for `FileReadTool` |
| `USE_BUILTIN_RIPGREP` | [utils/ripgrep.ts](../../utils/ripgrep.ts) | Forces bundled vs. system `rg` binary (`0` uses system PATH `rg`) |
| `CLAUDE_CODE_UNDERCOVER` | [utils/undercover.ts](../../utils/undercover.ts) | Suppresses internal/Anthropic attribution strings when working in public repos |

### 5.5 MCP, Skills, Hooks & Plugins

| Environment Variable | Primary Source File(s) | Effect & Invariant |
| :--- | :--- | :--- |
| `ENABLE_TOOL_SEARCH` | [utils/toolSearch.ts](../../utils/toolSearch.ts) | Controls deferred tool loading: `true`/`auto:0` (always defer), `auto`/`auto:N` (defer above `N%` context, default `10%`), `false`/`auto:100` (eager) ([Ch 15](../chapters/15-model-context-protocol-mcp.md)) |
| `MCP_TIMEOUT` / `MCP_TOOL_TIMEOUT` | [services/mcp/client.ts](../../services/mcp/client.ts) | Server startup handshake timeout and per-tool-call timeout for MCP servers |
| `MAX_MCP_OUTPUT_TOKENS` | [utils/mcpValidation.ts](../../utils/mcpValidation.ts) | Token cap on inline MCP tool responses before warning/truncation |
| `ENABLE_MCP_LARGE_OUTPUT_FILES` | [services/mcp/client.ts](../../services/mcp/client.ts) | Spills oversized MCP payloads to disk files rather than truncating |
| `ENABLE_CLAUDEAI_MCP_SERVERS` | [services/mcp/claudeai.ts](../../services/mcp/claudeai.ts) | Enables/disables synced `claude.ai` hosted MCP connectors |
| `ENABLE_LSP_TOOL` | [tools.ts](../../tools.ts) | Opts into the background Language Server Protocol tool ([Ch 16](../chapters/16-skills-plugins-output-styles-and-lsp.md)) |
| `SLASH_COMMAND_TOOL_CHAR_BUDGET` | [tools/SkillTool/prompt.ts](../../tools/SkillTool/prompt.ts) | Character budget for listing available skills/commands in system prompt |
| `CLAUDE_CODE_SESSIONEND_HOOKS_TIMEOUT_MS` | [utils/hooks.ts](../../utils/hooks.ts), [utils/gracefulShutdown.ts](../../utils/gracefulShutdown.ts) | Caps shutdown wait for `SessionEnd` hooks ([Ch 13](../chapters/13-the-hook-system.md)) |
| `CLAUDE_CODE_SYNC_PLUGIN_INSTALL` | [setup.ts](../../setup.ts), [cli/print.ts](../../cli/print.ts) | Blocks startup until plugin installation completes (headless/CI determinism) |
| `CLAUDE_CODE_PLUGIN_CACHE_DIR` | [utils/plugins/pluginDirectories.ts](../../utils/plugins/pluginDirectories.ts) | Overrides on-disk plugin cache directory |
| `FORCE_AUTOUPDATE_PLUGINS` | [utils/config.ts](../../utils/config.ts) | Forces plugin marketplace updates even when CLI auto-updater is disabled |
| `CLAUDE_CODE_ENABLE_XAA` | [services/mcp/xaaIdpLogin.ts](../../services/mcp/xaaIdpLogin.ts) | Enables Cross-App Access (XAA) IdP authentication flow for enterprise MCP servers |

### 5.6 Background Tasks, Subagents, Swarms & Coordinator

| Environment Variable | Primary Source File(s) | Effect & Invariant |
| :--- | :--- | :--- |
| `CLAUDE_CODE_DISABLE_BACKGROUND_TASKS` | [tools/BashTool/BashTool.tsx](../../tools/BashTool/BashTool.tsx), [tools/PowerShellTool/prompt.ts](../../tools/PowerShellTool/prompt.ts) | Disables `run_in_background` across shell and agent tools (captured at module import time!) |
| `CLAUDE_CODE_ENABLE_TASKS` / `CLAUDE_CODE_TASK_LIST_ID` | [utils/tasks.ts](../../utils/tasks.ts), [main.tsx](../../main.tsx) | Enables persistent shared task list and pins a shared cross-session task list ID ([Ch 17](../chapters/17-background-task-runtime.md)) |
| `CLAUDE_CODE_SUBAGENT_MODEL` | [utils/model/agent.ts](../../utils/model/agent.ts) | Overrides default model used when spawning subagents ([Ch 18](../chapters/18-subagents-context-forking-and-worktrees.md)) |
| `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS` | [utils/agentSwarmsEnabled.ts](../../utils/agentSwarmsEnabled.ts) | Opt-in gate enabling multi-agent teams (`TeamCreateTool`, mailbox, in-process/tmux teammates; [Ch 19](../chapters/19-agent-teams-swarms-and-coordinator-mode.md)) |
| `CLAUDE_CODE_COORDINATOR_MODE` | [coordinator/coordinatorMode.ts](../../coordinator/coordinatorMode.ts), [main.tsx](../../main.tsx) | Activates Coordinator Mode (behind `feature('COORDINATOR_MODE')`) |
| `CLAUDE_CODE_DISABLE_CRON` | [tools/ScheduleCronTool/prompt.ts](../../tools/ScheduleCronTool/prompt.ts) | Disables scheduled cron trigger tools for the session |
| `CLAUDE_CODE_PROACTIVE` / `CLAUDE_CODE_BRIEF` | [main.tsx](../../main.tsx), [tools/BriefTool/BriefTool.ts](../../tools/BriefTool/BriefTool.ts) | Runtime opt-in for proactive wake loop / brief mode (behind `PROACTIVE` / `KAIROS_BRIEF`) |
| `CLAUDE_CODE_PLAN_V2_AGENT_COUNT` | [utils/planModeV2.ts](../../utils/planModeV2.ts) | Tunes parallel planner/explorer subagent fan-out in Plan Mode V2 |
| `CLAUDE_CODE_EAGER_FLUSH` | [QueryEngine.ts](../../QueryEngine.ts) | Forces immediate transcript persistence flushes inside `QueryEngine` ([Ch 08](../chapters/08-session-envelope-query-engine-and-transcripts.md)) |

### 5.7 Terminal UI, Fullscreen, IDE & Accessibility

| Environment Variable | Primary Source File(s) | Effect & Invariant |
| :--- | :--- | :--- |
| `CLAUDE_CODE_NO_FLICKER` | [utils/fullscreen.ts](../../utils/fullscreen.ts) | Toggles Ink alternate-screen buffer + virtualized scrollback (`0` opts out; auto-disabled under `tmux -CC`; [Ch 20](../chapters/20-inside-ink-terminal-react-renderer.md)) |
| `CLAUDE_CODE_DISABLE_MOUSE` / `CLAUDE_CODE_DISABLE_MOUSE_CLICKS` | [utils/fullscreen.ts](../../utils/fullscreen.ts) | Keeps alt-screen while disabling SGR mouse tracking (preserves native terminal copy-on-select) or click handlers |
| `CLAUDE_CODE_DISABLE_VIRTUAL_SCROLL` | [components/Messages.tsx](../../components/Messages.tsx), [screens/REPL.tsx](../../screens/REPL.tsx) | Disables message-list virtualization in fullscreen mode |
| `CLAUDE_CODE_DISABLE_TERMINAL_TITLE` | [screens/REPL.tsx](../../screens/REPL.tsx), [utils/gracefulShutdown.ts](../../utils/gracefulShutdown.ts) | Prevents OSC escape sequences from overwriting terminal tab/window title |
| `CLAUDE_CODE_ACCESSIBILITY` | [ink/components/App.tsx](../../ink/components/App.tsx), [components/TextInput.tsx](../../components/TextInput.tsx) | Enables screen-reader-friendly Ink rendering hints |
| `CLAUDE_CODE_SYNTAX_HIGHLIGHT` | [native-ts/color-diff/index.ts](../../native-ts/color-diff/index.ts), [components/ThemePicker.tsx](../../components/ThemePicker.tsx) | Toggles native syntax highlighting in structured code diffs (`0` disables) |
| `CLAUDE_CODE_TMUX_PREFIX` | [components/LogoV2/LogoV2.tsx](../../components/LogoV2/LogoV2.tsx) | Surfaces tmux prefix conflict guidance when spawned inside managed tmux sessions |
| `CLAUDE_CODE_IDE_HOST_OVERRIDE` / `CLAUDE_CODE_SSE_PORT` | [utils/ide.ts](../../utils/ide.ts), [hooks/useIDEIntegration.tsx](../../hooks/useIDEIntegration.tsx) | Connects CLI to VS Code / JetBrains IDE extension lockfile & SSE bridge |
| `CLAUDE_CODE_ENABLE_PROMPT_SUGGESTION` | [services/PromptSuggestion/promptSuggestion.ts](../../services/PromptSuggestion/promptSuggestion.ts), [query/stopHooks.ts](../../query/stopHooks.ts) | Enables speculative next-prompt ghost text after assistant turns ([Ch 21](../chapters/21-the-interactive-repl-screens-keybindings-and-vim.md)) |
| `CLAUDE_CODE_DISABLE_FEEDBACK_SURVEY` | [components/FeedbackSurvey/useFeedbackSurvey.tsx](../../components/FeedbackSurvey/useFeedbackSurvey.tsx) | Suppresses post-compact, memory, and session quality feedback prompts |

### 5.8 Remote Sessions, Bridge, Proxy & TLS

| Environment Variable | Primary Source File(s) | Effect & Invariant |
| :--- | :--- | :--- |
| `CLAUDE_CODE_REMOTE` | [cli/print.ts](../../cli/print.ts), [entrypoints/cli.tsx](../../entrypoints/cli.tsx) | Marks headless remote container execution (auto-injects `--max-old-space-size=8192` into `NODE_OPTIONS` at `cli.tsx:9-14`) |
| `CLAUDE_CODE_REMOTE_SESSION_ID` | [services/analytics/metadata.ts](../../services/analytics/metadata.ts), [utils/filePersistence/filePersistence.ts](../../utils/filePersistence/filePersistence.ts) | Binds container turn telemetry and Files API persistence to remote session UUID |
| `CLAUDE_CODE_USE_CCR_V2` | [cli/print.ts](../../cli/print.ts), [bridge/remoteBridgeCore.ts](../../bridge/remoteBridgeCore.ts) | Selects CCR v2 transport (`HybridTransport` / `SSETransport` + worker epochs; [Ch 24](../chapters/24-across-the-wire-remote-sessions-bridge-and-direct-connect.md)) |
| `CLAUDE_BRIDGE_SESSION_INGRESS_URL` | [bridge/bridgeMain.ts](../../bridge/bridgeMain.ts), [bridge/initReplBridge.ts](../../bridge/initReplBridge.ts) | Overrides session ingress endpoint for remote bridge connections |
| `CLAUDE_CODE_SESSION_ACCESS_TOKEN` | [utils/sessionIngressAuth.ts](../../utils/sessionIngressAuth.ts), [bridge/remoteBridgeCore.ts](../../bridge/remoteBridgeCore.ts) | Bearer token authenticating remote session ingress WebSockets/POSTs |
| `CLAUDE_CODE_IS_COWORK` | [QueryEngine.ts](../../QueryEngine.ts) | Identifies Cowork desktop-managed container execution inside `QueryEngine` |
| `ANTHROPIC_UNIX_SOCKET` | [utils/managedEnv.ts](../../utils/managedEnv.ts), [utils/auth.ts](../../utils/auth.ts) | Routes API traffic over a `-R` SSH-forwarded Unix socket proxy (activates `withoutSSHTunnelVars()`) |
| `CLAUDE_CODE_CLIENT_CERT` / `CLAUDE_CODE_CLIENT_KEY` | [utils/mtls.ts](../../utils/mtls.ts), [utils/apiPreconnect.ts](../../utils/apiPreconnect.ts) | Client certificate & private key paths for mutual TLS (mTLS) to corporate gateways |
| `NODE_EXTRA_CA_CERTS` | [utils/caCerts.ts](../../utils/caCerts.ts), [utils/caCertsConfig.ts](../../utils/caCertsConfig.ts) | Custom CA PEM bundle; read during `init.ts` *before* BoringSSL caches its cert store ([Ch 22](../chapters/22-cold-start-mastery-cli-init-main.md)) |
| `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` | [utils/proxy.ts](../../utils/proxy.ts), [upstreamproxy/upstreamproxy.ts](../../upstreamproxy/upstreamproxy.ts) | Global outbound proxy routing (blocked from untrusted repo settings prior to trust dialog) |
| `CLAUDE_CODE_PROXY_RESOLVES_HOSTS` | [utils/proxy.ts](../../utils/proxy.ts) | Signals that the corporate proxy handles DNS resolution for SSRF/proxy routing |

---

## Verification & Exploration Commands

Every count and claim in this appendix can be independently verified against the repository with read-only `rg` commands:

1. **Reproduce the complete 90-flag `feature()` census:**
   ```sh
   rg --glob '*.ts' --glob '*.tsx' --glob '!book/**' -o "feature\(['\"][A-Za-z0-9_-]+['\"]\)" | sort | uniq -c | sort -nr
   ```
2. **Observe the `.tsx` constant-folding split vs. `.ts` runtime checks for `USER_TYPE`:**
   ```sh
   rg --glob '*.tsx' --glob '!book/**' -c '"external"\s*[!=]==\s*'\''ant'\'''
   rg --glob '*.ts'  --glob '!book/**' -c 'process\.env\.USER_TYPE'
   ```
3. **Inspect the Bun DCE complexity cliff and positive-ternary invariant comments:**
   ```sh
   rg --glob '*.ts' --glob '*.tsx' --glob '!book/**' 'DCE cliff|Negative pattern \(if \(!feature'
   ```
4. **Audit every env var permitted before the workspace trust dialog vs. scrubbed from subprocesses:**
   Read [utils/managedEnvConstants.ts](../../utils/managedEnvConstants.ts) (`SAFE_ENV_VARS` & `PROVIDER_MANAGED_ENV_VARS`) alongside [utils/subprocessEnv.ts](../../utils/subprocessEnv.ts) (`GHA_SUBPROCESS_SCRUB`).


---

<!-- appendices/B-missing-snapshot-boundaries.md — https://reverseengineeringclaudecode.com/appendices/B-missing-snapshot-boundaries -->

# Appendix B — Reconstructing the Missing Snapshot Boundaries from Call Sites

> **Role:** Forensic Reference & Boundary Catalog (Companion to [Chapter 00](../chapters/00-how-to-read-a-1900-file-agent.md)–[Chapter 24](../chapters/24-across-the-wire-remote-sessions-bridge-and-direct-connect.md))
> **Prerequisites:** [Chapter 00](../chapters/00-how-to-read-a-1900-file-agent.md), [Chapter 03](../chapters/03-command-and-message-contracts.md), [Chapter 07](../chapters/07-the-heartbeat-query-loop.md), [Chapter 09](../chapters/09-five-layer-compaction-pipeline.md)
> **Primary Source Files (Observed Call Sites):**
> - [`utils/messages.ts`](../../utils/messages.ts) — message factories, normalization, and snip projection call sites
> - [`query.ts`](../../query.ts) — `query()` turn state machine, `Continue`/`Terminal` transitions, collapse/reactive/snip/skillSearch hooks
> - [`QueryEngine.ts`](../../QueryEngine.ts) — session envelope, message stream dispatch, `snipReplay` callback
> - [`types/logs.ts`](../../types/logs.ts) & [`utils/sessionStorage.ts`](../../utils/sessionStorage.ts) — JSONL persistence contracts, tombstone removal, and obfuscated `marble-origami-*` collapse entries
> - [`services/compact/microCompact.ts`](../../services/compact/microCompact.ts) & [`services/api/claude.ts`](../../services/api/claude.ts) — cached microcompact state and `cache_edits` wire contract
> - [`utils/attachments.ts`](../../utils/attachments.ts) & [`tools/SkillTool/SkillTool.ts`](../../tools/SkillTool/SkillTool.ts) — skill-search discovery, prefetch, and remote-skill execution seams
> - [`screens/REPL.tsx`](../../screens/REPL.tsx), [`cli/print.ts`](../../cli/print.ts) & [`commands/compact/compact.ts`](../../commands/compact/compact.ts) — proactive loop and reactive-only compaction seams

---

## Why This Snapshot Has Exact, Predictable Holes

When you read a real-world source snapshot rather than a full upstream monorepo, broken imports look alarming at first. In this checkout, scanning all **1,903** `.ts`/`.tsx`/`.js`/`.jsx`/`.mjs`/`.cjs` source files outside `book/` turns up **187 unique unresolved local import targets** (across both relative `./`/`../` specifiers and `src/` root aliases) plus **13 external, internal-scoped (`@ant/*`), or Bun runtime packages** (`bun:bundle`, `bun:ffi`, `@anthropic-ai/*`).

The crucial systems insight is that these 187 holes are **not random corruption**. Every single one falls cleanly into one of four mechanical build-pipeline boundaries:

1. **TypeScript type erasure (31 pure type-only modules + 2 generated SDK type files).**
   Files imported exclusively via `import type` (or ambient `.d.ts` files like `ink/global.d.ts`) compile to **zero bytes of runtime JavaScript**. In any snapshot captured from runtime-emitted sources or post-strip artifacts, pure type modules leave behind their exact import lists in every consumer while contributing nothing to the runtime module graph.
2. **Build-time dead-code elimination (`feature('...')` & `USER_TYPE === 'ant'`) + excluded-strings hygiene (109 dynamic-only targets + 4 mixed type/dynamic targets + 6 tree-shaken static targets).**
   As introduced in [Chapter 00](../chapters/00-how-to-read-a-1900-file-agent.md), Claude Code builds internal (`ant`) and external customer binaries from one tree using `bun:bundle`'s compile-time `feature('...')` predicate. Even when a symbol is imported via a static top-level ES `import`—such as `isConnectorTextBlock` (`types/connectorText.js`), `TungstenTool`, `TungstenLiveMonitor`, or `WORKFLOW_TOOL_NAME` (`tools/WorkflowTool/constants.js`)—every runtime call site is guarded behind `feature('...')` or `process.env.USER_TYPE === 'ant'` (already constant-folded to `"external" === 'ant'` in React-Compiler-transformed `.tsx` files like [`components/agents/ToolSelector.tsx:61`](../../components/agents/ToolSelector.tsx) and [`screens/REPL.tsx:4584`](../../screens/REPL.tsx)). Once the false branch folds away, Bun's tree-shaker drops the target module completely.

   Even more revealing are the inline comments explaining an upstream **excluded-strings CI check** that rejects external builds if internal codenames or feature strings leak into un-gated files:

```ts
// utils/attachments.ts:88-95
import type { DiscoverySignal } from '../services/skillSearch/signals.js'
// Conditional require for DCE. All skill-search string literals that would
// otherwise leak into external builds live inside these modules. The only
// surfaces in THIS file are: the maybe() call (gated via spread below) and
// the skill_listing suppression check (uses the same skillSearchModules null
// check). The type-only DiscoverySignal import above is erased at compile time.
const skillSearchModules = feature('EXPERIMENTAL_SKILL_SEARCH')
```

   The same invariant forces [`QueryEngine.ts:900-905`](../../QueryEngine.ts) to inject `snipReplay` as a callback so snip subtype strings never appear in `QueryEngine.ts`, forces [`query.ts:868-870`](../../query.ts) to wrap `cache_deleted_input_tokens` inside `feature('CACHED_MICROCOMPACT')`, and forces [`types/logs.ts:249-256`](../../types/logs.ts) to obfuscate context-collapse transcript discriminators as `'marble-origami-commit'` and `'marble-origami-snapshot'`.
3. **Generated codegen outputs (2 targets).**
   [`entrypoints/sdk/coreTypes.ts:19`](../../entrypoints/sdk/coreTypes.ts) and [`entrypoints/agentSdkTypes.ts:29`](../../entrypoints/agentSdkTypes.ts) re-export `coreTypes.generated.js` and `settingsTypes.generated.js`—build-time generated type declarations that carry no runtime code.
4. **Inlined non-code text and Markdown assets (33 targets).**
   29 Markdown reference files imported by [`skills/bundled/claudeApiContent.ts`](../../skills/bundled/claudeApiContent.ts) and [`skills/bundled/verifyContent.ts`](../../skills/bundled/verifyContent.ts), plus 4 prompt `.txt` files (`utils/permissions/yolo-classifier-prompts/*.txt` and `utils/ultraplan/prompt.txt`), are loaded as static text blobs rather than JS modules.

### The Archaeology Protocol: Reconstructing Without Guessing

Whenever you cross an absent module boundary in this codebase, apply a four-step verification discipline so you never hallucinate unverified fields:

1. **Harvest the symbol table first.** Scan every `import type { ... }` and `require(...) as typeof import(...)` referencing the absent path. TypeScript's `as typeof import(...)` casts preserve exact method and property names at every call site.
2. **Anchor on constructors and exhaustive switches.** Factory functions (`createUserMessage`, `createSystemMessage`, `createCompactBoundaryMessage`) and exhaustive `switch (x.type)` statements (`utils/messages.ts:750-821`, `QueryEngine.ts:757-965`, `commands/compact/compact.ts:185-194`) prove exact required fields and union discriminators.
3. **Cross-check persistence boundaries.** Disk/wire schemas in [`types/logs.ts`](../../types/logs.ts), [`utils/sessionStorage.ts`](../../utils/sessionStorage.ts), and [`services/api/claude.ts`](../../services/api/claude.ts) often live *outside* feature gates and therefore preserve verbatim field layouts of missing internal subsystems (e.g., `ContextCollapseCommitEntry` and `CachedMCEditsBlock`).
4. **Label epistemic boundaries explicitly.** Distinguish **directly observed** fields/signatures (backed by file:line citations) from **unobserved internals** (marked with explicit comments rather than invented implementation details).

---

## 1. Master Inventory of Missing Snapshot Boundaries

### 1.1 Core Type, Schema & State-Machine Modules

These 31 pure type-only modules (plus 2 `.d.ts` / type-barrel targets and 2 generated SDK type files) define shared contracts across the repository.

| Missing Target | Importers | Kind | Key Consumers & Role |
| --- | ---: | --- | --- |
| `types/message.ts` | 183 | Type-only | `utils/messages.ts`, `query.ts`, `QueryEngine.ts`, `Tool.ts`, `utils/sessionStorage.ts` (39 symbols; note typo `src//types/message.js` at `cli/structuredIO.ts:7`) |
| `constants/querySource.ts` | 21 | Type-only | `Tool.ts`, `query.ts`, `services/api/claude.ts`, `query/stopHooks.ts` (`QuerySource` union, e.g. `'repl_main_thread'`, `'sdk'`, `'session_memory'`) |
| `entrypoints/sdk/controlTypes.ts` | 19 | Type-only | `cli/structuredIO.ts`, `cli/remoteIO.ts`, `bridge/*`, `cli/transports/*` (SDK bidirectional control-plane request/response types) |
| `keybindings/types.ts` | 17 | Type-only | `keybindings/*`, `components/ConfigurableShortcutHint.tsx`, `hooks/useExitOnCtrlCD.ts` (`KeybindingAction`, `KeybindingContextName`, `ParsedKeystroke`) |
| `types/tools.ts` | 15 | Type-only | `Tool.ts`, `tools/AgentTool/AgentTool.tsx`, `components/BashModeProgress.tsx` (shared tool progress/result helper types) |
| `types/utils.ts` | 15 | Type-only | `Tool.ts`, `state/AppStateStore.ts`, `components/tasks/*`, `utils/messages.ts` (`DeepImmutable`, utility type aliases) |
| `components/agents/new-agent-creation/types.ts` | 13 | Type-only | `CreateAgentWizard.tsx` and 12 wizard step components |
| `components/mcp/types.ts` | 10 | Type-only | `components/mcp/*`, `commands/plugin/ManagePlugins.tsx` |
| `services/oauth/types.ts` | 9 | Type-only | `cli/handlers/auth.ts`, `services/oauth/getOauthProfile.ts`, `services/api/referral.ts` |
| `components/FeedbackSurvey/utils.ts` | 8 | Type-only | `components/FeedbackSurvey/*` |
| `components/Spinner/types.ts` | 8 | Type-only | `components/Spinner/*` |
| `commands/plugin/types.ts` & `unifiedTypes.ts` | 6 / 2 | Type-only | `commands/plugin/*` marketplace and installed-plugin views |
| `utils/secureStorage/types.ts` | 6 | Type-only | `utils/secureStorage/*`, `services/mcp/auth.ts` (`SecureStorage` interface) |
| `services/lsp/types.ts` | 5 | Type-only | `services/lsp/{LSPServerInstance,LSPServerManager,config}.ts` |
| `commands/install-github-app/types.ts` | 5 | Type-only | `commands/install-github-app/*` |
| `cli/transports/Transport.ts` | 4 | Type-only | `cli/remoteIO.ts`, `cli/transports/{SSE,WebSocket}Transport.ts` |
| `components/wizard/types.ts` | 4 | Type-only | `components/wizard/*`, `CreateAgentWizard.tsx` |
| `types/connectorText.ts` | 4 | Static (DCE) | `components/Message.tsx`, `services/api/{claude,logging}.ts`, `utils/messages.ts` (`ConnectorTextBlock`, `ConnectorTextDelta`, `isConnectorTextBlock`, guarded by `feature('CONNECTOR_TEXT')`) |
| `entrypoints/sdk/{sdkUtilityTypes,runtimeTypes,toolTypes}.ts` | 3 / 2 / 1 | Type-only | `entrypoints/agentSdkTypes.ts`, `entrypoints/sdk/coreTypes.ts`, `utils/effort.ts` |
| `entrypoints/sdk/{coreTypes,settingsTypes}.generated.ts` | 1 / 1 | Generated | Re-exported by `entrypoints/sdk/coreTypes.ts:19` and `entrypoints/agentSdkTypes.ts:29` |
| `types/{messageQueueTypes,notebook,fileSuggestion,statusLine}.ts` | 3 / 3 / 2 / 2 | Type-only | `utils/messageQueueManager.ts`, `tools/NotebookEditTool/*`, `utils/hooks.ts`, `components/StatusLine.tsx` |
| `utils/filePersistence/types.ts` & `services/tips/types.ts` | 2 / 2 | Type-only | `utils/filePersistence/*`, `services/tips/*` |
| `ink/{cursor.ts,global.d.ts,events/paste-event.ts,events/resize-event.ts}` | 1–2 | Type-only | `ink/frame.ts`, `ink/components/{Box,ScrollBox}.tsx`, `ink/events/event-handlers.ts` |
| `query/transitions.ts` | 1 | Type-only | `query.ts:104` (`Continue`, `Terminal`) |

### 1.2 Feature-Gated & Internal-Only Subsystems Stripped at Build Time

The remaining **119 missing code targets** (109 dynamic-only, 4 dynamic+type, and 6 statically imported behind constant-folded gates) belong to feature-flagged or `USER_TYPE === 'ant'` subsystems:

| Subsystem | Compile-Time Gate(s) | Absent Targets (Representative Paths) | Observed Entry Points |
| --- | --- | --- | --- |
| **Context Collapse** | `feature('CONTEXT_COLLAPSE')` | `services/contextCollapse/{index,operations,persist}.ts`, `tools/CtxInspectTool/CtxInspectTool.ts` | `query.ts`, `utils/sessionRestore.ts`, `commands/context/*`, `components/{TokenWarning,ContextVisualization}.tsx`, `services/compact/postCompactCleanup.ts`, `tools.ts` |
| **Compaction Extensions** | `feature('HISTORY_SNIP')`, `feature('REACTIVE_COMPACT')`, `feature('CACHED_MICROCOMPACT')` | `services/compact/{snipCompact,snipProjection,reactiveCompact,cachedMicrocompact,cachedMCConfig}.ts`, `tools/SnipTool/{SnipTool,prompt}.ts`, `commands/force-snip.ts`, `components/messages/SnipBoundaryMessage.tsx` | `query.ts`, `QueryEngine.ts`, `services/compact/microCompact.ts`, `services/api/claude.ts`, `commands/compact/compact.ts`, `utils/messages.ts`, `constants/prompts.ts` |
| **Proactive / Kairos & Assistant** | `feature('PROACTIVE')`, `feature('KAIROS')`, `feature('KAIROS_GITHUB_WEBHOOKS')`, `feature('KAIROS_PUSH_NOTIFICATION')` | `proactive/{index,useProactive}.ts`, `assistant/{index,gate,sessionDiscovery,AssistantSessionChooser}.ts`, `tools/SleepTool/SleepTool.ts`, `tools/SendUserFileTool/*`, `tools/PushNotificationTool/*`, `tools/SubscribePRTool/*`, `commands/{proactive,assistant/*,subscribe-pr}.ts`, `bridge/webhookSanitizer.ts` | `screens/REPL.tsx`, `cli/print.ts`, `main.tsx`, `constants/prompts.ts`, `bridge/initReplBridge.ts`, `hooks/useReplBridge.tsx`, `tools.ts`, `commands.ts` |
| **Experimental Skill Search** | `feature('EXPERIMENTAL_SKILL_SEARCH')` | `services/skillSearch/{featureCheck,prefetch,localSearch,remoteSkillState,remoteSkillLoader,signals,telemetry}.ts`, `tools/DiscoverSkillsTool/prompt.ts` | `query.ts`, `utils/attachments.ts`, `tools/SkillTool/SkillTool.ts`, `constants/prompts.ts`, `commands.ts`, `services/mcp/useManageMCPConnections.ts` |
| **Daemon, Server, SSH & Runners** | `feature('DAEMON')`, `feature('BG_SESSIONS')`, `feature('CCR_MIRROR')`, `feature('DIRECT_CONNECT')`, `USER_TYPE === 'ant'` | `daemon/{main,workerRegistry}.ts`, `server/{server,sessionManager,connectHeadless,lockfile,parseConnectUrl,serverBanner,serverLog,backends/dangerousBackend}.ts`, `ssh/{createSSHSession,SSHSessionManager}.ts`, `environment-runner/main.ts`, `self-hosted-runner/main.ts`, `cli/{bg,rollback,up,handlers/ant,handlers/templateJobs}.ts` | `entrypoints/cli.tsx`, `main.tsx`, `hooks/useSSHSession.ts`, `screens/REPL.tsx` |
| **Tasks, Workflows & Coordinator** | `feature('WORKFLOW_SCRIPTS')`, `feature('MONITOR_TOOL')`, `feature('COORDINATOR_MODE')` | `tasks/LocalWorkflowTask/LocalWorkflowTask.ts`, `tasks/MonitorMcpTask/MonitorMcpTask.ts`, `tools/WorkflowTool/*`, `tools/MonitorTool/MonitorTool.ts`, `coordinator/workerAgent.ts`, `components/tasks/{MonitorMcp,Workflow}DetailDialog.tsx` | `tasks.ts`, `tasks/types.ts`, `tools.ts`, `tools/AgentTool/builtInAgents.ts`, `components/tasks/BackgroundTasksDialog.tsx`, `components/permissions/PermissionRequest.tsx` |
| **Peer Messaging & UDS IPC** | `feature('UDS_INBOX')`, `feature('PEERS')` / `USER_TYPE === 'ant'` | `bridge/peerSessions.ts`, `utils/{udsMessaging,udsClient}.ts`, `tools/ListPeersTool/ListPeersTool.ts`, `commands/peers/index.ts`, `components/messages/UserCrossSessionMessage.tsx` | `tools/SendMessageTool/SendMessageTool.ts`, `utils/conversationRecovery.ts`, `cli/print.ts`, `setup.ts`, `utils/messages/systemInit.ts` |
| **Internal Tools, Skills & Diagnostics** | `USER_TYPE === 'ant'`, `feature('COMMIT_ATTRIBUTION')`, `feature('BUDDY')`, `feature('TEMPLATES')`, etc. | `tools/{TungstenTool,REPLTool,TerminalCaptureTool,WebBrowserTool,ReviewArtifactTool,VerifyPlanExecutionTool,SuggestBackgroundPRTool,OverflowTestTool}/*`, `utils/{attributionHooks,attributionTrailer,postCommitAttribution,taskSummary,ccshareResume,eventLoopStallDetector,sdkHeapDumpMonitor,sessionDataUploader,protectedNamespace,systemThemeWatcher}.ts`, `jobs/classifier.ts`, `services/sessionTranscript/sessionTranscript.ts`, `memdir/memoryShapeTelemetry.ts`, `skills/mcpSkills.ts`, `skills/bundled/{dream,hunter,runSkillGenerator}.ts`, `commands/{buddy,fork,torch,workflows,agents-platform,remoteControlServer}/*`, `ink/devtools.ts` | `tools.ts`, `commands.ts`, `main.tsx`, `screens/REPL.tsx`, `setup.ts`, `query.ts`, `skills/bundled/index.ts`, `ink/reconciler.ts` |

### 1.3 Inlined Text & Markdown Assets (33 Targets)

- **29 Markdown files** under `skills/bundled/claude-api/**/*.md` (26 files) and `skills/bundled/verify/**/*.md` (3 files), imported via static asset imports in [`skills/bundled/claudeApiContent.ts`](../../skills/bundled/claudeApiContent.ts) and [`skills/bundled/verifyContent.ts`](../../skills/bundled/verifyContent.ts).
- **4 prompt `.txt` files**: `utils/permissions/yolo-classifier-prompts/{auto_mode_system_prompt,permissions_anthropic,permissions_external}.txt` (imported in [`utils/permissions/yoloClassifier.ts`](../../utils/permissions/yoloClassifier.ts)) and `utils/ultraplan/prompt.txt` (imported in [`commands/ultraplan.tsx`](../../commands/ultraplan.tsx)).

### 1.4 External, Internal (`@ant/*`), and Bun Runtime Packages

Because no `package.json` or `node_modules/` ships in this checkout, 13 notable Anthropic/Bun package boundaries sit outside the source tree:

| Package | Importers | Role Observed at Call Sites |
| --- | ---: | --- |
| `bun:bundle` | 196 | Compile-time `feature('...')` dead-code elimination predicate |
| `bun:ffi` | 1 | Native dynamic library loading (`utils/computerUse/` / platform bindings) |
| `@anthropic-ai/sdk` | 116 | Anthropic Messages API client, streaming types, `BetaContentBlock`, `MessageParam`, `APIError` |
| `@anthropic-ai/bedrock-sdk`, `vertex-sdk`, `foundry-sdk` | 1 each | 3P cloud provider clients in [`services/api/client.ts`](../../services/api/client.ts) |
| `@anthropic-ai/claude-agent-sdk` | 1 | SDK interoperability types in [`cli/print.ts`](../../cli/print.ts) |
| `@anthropic-ai/sandbox-runtime` | 1 | OS-level filesystem/network sandbox wrapper in [`utils/sandbox/sandbox-adapter.ts`](../../utils/sandbox/sandbox-adapter.ts) ([Chapter 12](../chapters/12-shell-execution-sandboxing-and-workspace-tools.md)) |
| `@anthropic-ai/mcpb` | 2 | MCP Bundle (`.mcpb`/DXT) manifest & extraction helpers in [`utils/dxt/helpers.ts`](../../utils/dxt/helpers.ts) and [`utils/plugins/mcpbHandler.ts`](../../utils/plugins/mcpbHandler.ts) |
| `@ant/computer-use-mcp` | 7 | Internal GUI computer-use MCP server & approval protocol (`utils/computerUse/*`, `components/permissions/ComputerUseApproval/*`) |
| `@ant/claude-for-chrome-mcp` | 4 | Internal browser-extension MCP bridge (`utils/claudeInChrome/*`, `skills/bundled/claudeInChrome.ts`) |
| `@ant/computer-use-input`, `@ant/computer-use-swift` | 1 each | Native OS input injection and macOS Swift bindings (`utils/computerUse/{inputLoader,swiftLoader}.ts`) |

---

## 2. Reconstructed from Call Sites: `types/message.ts`

> [!NOTE]
> **Reconstructed from Call Sites — Absent from Snapshot.**
> `types/message.ts` is imported by **183 files** for **39 distinct exported symbols**, making it the single most heavily referenced absent file in the checkout. Every type below is reconstructed strictly from verified constructors and switches in [`utils/messages.ts`](../../utils/messages.ts), [`utils/attachments.ts`](../../utils/attachments.ts), [`query.ts`](../../query.ts), [`QueryEngine.ts`](../../QueryEngine.ts), [`services/api/claude.ts`](../../services/api/claude.ts), [`utils/plans.ts`](../../utils/plans.ts), and [`utils/sessionStorage.ts`](../../utils/sessionStorage.ts).

### The Three-Tier Message Hierarchy

The single most important architectural invariant hidden inside `types/message.ts` is that **not every object yielded by `query()` is a `Message`**. Cross-checking [`utils/messages.ts:750-821`](../../utils/messages.ts), [`utils/sessionStorage.ts:2456-2472`](../../utils/sessionStorage.ts), [`query.ts:221-226`](../../query.ts), and [`QueryEngine.ts:757-965`](../../QueryEngine.ts) proves a strict three-tier split:

1. **Tier 1 — Persisted `Message` (5 variants):** `'user' | 'assistant' | 'attachment' | 'system' | 'progress'`. Only these five enter `mutableMessages`, `normalizeMessages()`, and the JSONL transcript (`SerializedMessage = Message & { ... }` in [`types/logs.ts:8-17`](../../types/logs.ts)).
2. **Tier 2 — `query()` Stream Envelope (adds 4 control/ephemeral signals):** `StreamEvent | RequestStartEvent | Message | TombstoneMessage | ToolUseSummaryMessage` ([`query.ts:221-226`](../../query.ts)). `QueryEngine.ts` handles these in its top-level `switch (message.type)` ([`QueryEngine.ts:757-965`](../../QueryEngine.ts)) without pushing `stream_event`, `stream_request_start`, `tombstone`, or `tool_use_summary` into `mutableMessages`.
3. **Tier 3 — Normalized & UI-Renderable Views:** `NormalizedMessage` splits multi-block `UserMessage`/`AssistantMessage` instances into single-block records with derived UUIDs (`deriveUUID`, [`utils/messages.ts:725-823`](../../utils/messages.ts)), and `RenderableMessage` extends that with UI-only grouping wrappers (`GroupedToolUseMessage`, `CollapsedReadSearchGroup`, [`utils/groupToolUses.ts:147-151`](../../utils/groupToolUses.ts), [`utils/collapseReadSearch.ts:697-701`](../../utils/collapseReadSearch.ts)).

### Reconstructed Contract (`types/message.ts`)

```ts
// RECONSTRUCTED FROM CALL SITES — ABSENT FROM SNAPSHOT
// Verified against utils/messages.ts, utils/attachments.ts, query.ts,
// QueryEngine.ts, services/api/claude.ts, utils/plans.ts, utils/sessionStorage.ts

export type MessageOrigin =
  | { kind: 'human' } | { kind: 'task-notification' }           // utils/messages.ts:5501, 5506
  | { kind: 'coordinator' } | { kind: 'channel'; server: string } // utils/messages.ts:5503, 5505

export type PartialCompactDirection = 'from' | 'up_to'          // services/compact/prompt.ts:276-279, MessageSelector.tsx:196

export type UserMessage = {                                     // utils/messages.ts:460-522
  type: 'user'
  message: { role: 'user'; content: string | ContentBlockParam[] }
  uuid: UUID; timestamp: string
  isMeta?: true; isVisibleInTranscriptOnly?: true; isVirtual?: true; isCompactSummary?: true
  summarizeMetadata?: { messagesSummarized: number; userContext?: string; direction?: PartialCompactDirection }
  toolUseResult?: unknown
  mcpMeta?: { _meta?: Record<string, unknown>; structuredContent?: Record<string, unknown> }
  imagePasteIds?: number[]; sourceToolAssistantUUID?: UUID
  permissionMode?: PermissionMode; origin?: MessageOrigin
}

export type AssistantMessage = {                                // utils/messages.ts:355-409, 757-772
  type: 'assistant'; uuid: UUID; timestamp: string
  message: BetaMessage                                          // id, model, role:'assistant', content: BetaContentBlock[], usage, stop_reason, context_management
  requestId: string | undefined
  apiError?: unknown                                            // exact APIError/string union unobserved
  error?: SDKAssistantMessageError; errorDetails?: string
  isApiErrorMessage?: boolean; isMeta?: true; isVirtual?: true  // utils/messages.ts:407, 765
  advisorModel?: string                                         // utils/messages.ts:771
}

export type AttachmentMessage = {                               // utils/attachments.ts:3201-3209
  type: 'attachment'; attachment: Attachment; uuid: UUID; timestamp: string
}

export type ProgressMessage<P extends Progress = Progress> = {  // utils/messages.ts:603-620
  type: 'progress'; data: P; toolUseID: string; parentToolUseID: string
  uuid: UUID; timestamp: string
}

export type SystemMessageLevel = 'info' | 'warning' | 'error' | 'suggestion' // utils/messages.ts:4362,4594; processUserInput.ts:203; teleport.tsx:56
export type CompactMetadata = {                                 // utils/messages.ts:4545-4550
  trigger: 'manual' | 'auto'; preTokens: number
  userContext?: string; messagesSummarized?: number
}

// 14 SystemMessage subtypes observed across utils/messages.ts:4335-4603,
// utils/plans.ts:381-385, and components/messages/SystemTextMessage.tsx:19:
export type SystemCompactBoundaryMessage = {                    // utils/messages.ts:4530-4555
  type: 'system'; subtype: 'compact_boundary'; content: string; isMeta: false
  timestamp: string; uuid: UUID; level: 'info'
  compactMetadata: CompactMetadata; logicalParentUuid?: UUID
}
export type SystemMicrocompactBoundaryMessage = {               // utils/messages.ts:4557-4583
  type: 'system'; subtype: 'microcompact_boundary'; content: string; isMeta: false
  timestamp: string; uuid: UUID; level: 'info'
  microcompactMetadata: {
    trigger: 'auto'; preTokens: number; tokensSaved: number
    compactedToolIds: string[]; clearedAttachmentUUIDs: string[]
  }
}
export type SystemAPIErrorMessage = {                           // utils/messages.ts:4585-4603
  type: 'system'; subtype: 'api_error'; level: 'error'
  cause?: Error; error: APIError; retryInMs: number; retryAttempt: number; maxRetries: number
  timestamp: string; uuid: UUID
}
// Other SystemMessage subtypes (utils/messages.ts:4335-4528, utils/plans.ts:381, SystemTextMessage.tsx:19):
// 'informational' (SystemInformationalMessage), 'permission_retry' (SystemPermissionRetryMessage),
// 'bridge_status' (SystemBridgeStatusMessage), 'scheduled_task_fire' (SystemScheduledTaskFireMessage),
// 'stop_hook_summary' (SystemStopHookSummaryMessage, holding StopHookInfo[]),
// 'turn_duration' (SystemTurnDurationMessage), 'away_summary' (SystemAwaySummaryMessage),
// 'memory_saved' (SystemMemorySavedMessage), 'agents_killed' (SystemAgentsKilledMessage),
// 'api_metrics' (SystemApiMetricsMessage), 'local_command' (SystemLocalCommandMessage),
// 'file_snapshot' (SystemFileSnapshotMessage), 'thinking' (SystemThinkingMessage).

export type Message =
  | UserMessage | AssistantMessage | AttachmentMessage | SystemMessage | ProgressMessage

// Tier 2 — query() stream-only signals (query.ts:221-226):
export type RequestStartEvent = { type: 'stream_request_start' }                          // query.ts:337
export type StreamEvent = { type: 'stream_event'; event: BetaRawMessageStreamEvent; ttftMs?: number } // claude.ts:2299-2303
export type TombstoneMessage = { type: 'tombstone'; message: AssistantMessage }           // query.ts:717
export type ToolUseSummaryMessage = {                                                     // utils/messages.ts:5105-5115
  type: 'tool_use_summary'; summary: string; precedingToolUseIds: string[]; uuid: UUID; timestamp: string
}

// Tier 3 — Normalized & UI Renderable unions (utils/messages.ts:731-823):
export type NormalizedUserMessage = Omit<UserMessage, 'message'> & {
  message: { role: 'user'; content: [ContentBlockParam] }
}
export type NormalizedAssistantMessage = Omit<AssistantMessage, 'message'> & {
  message: Omit<BetaMessage, 'content'> & { content: [BetaContentBlock] }
}
export type NormalizedMessage =
  | NormalizedUserMessage | NormalizedAssistantMessage | AttachmentMessage | ProgressMessage | SystemMessage
// Plus HookResultMessage (AttachmentMessage narrowed to hook_* subtypes, utils/hooks.ts:712-725),
// GroupedToolUseMessage ({ type: 'grouped_tool_use', ... }), CollapsedReadSearchGroup ({ type: 'collapsed_read_search', ... }),
// CollapsibleMessage, and RenderableMessage.
```

> [!IMPORTANT]
> **Hidden Invariant — Tombstone Cleanup and the 50 MB Rewrite Guard:**
> When a streaming model retry fails mid-stream after yielding partial assistant blocks, [`query.ts:716-718`](../../query.ts) yields `{ type: 'tombstone', message: msg }` so callers remove orphaned messages before retrying (preventing `"thinking blocks cannot be modified"` API errors). In [`utils/sessionStorage.ts:121-123,925-933,1472-1474`](../../utils/sessionStorage.ts), `removeTranscriptMessage(targetUuid)` checks the last 64 KB first and falls back to rewriting the JSONL file—*unless* the session file exceeds `MAX_TOMBSTONE_REWRITE_BYTES` (50 MB, added after `inc-3930` to prevent OOM on multi-GB transcripts).

---

## 3. Reconstructed from Call Sites: `query/transitions.ts`

> [!NOTE]
> **Reconstructed from Call Sites — Absent from Snapshot.**
> Only [`query.ts:104`](../../query.ts) imports `query/transitions.ts` (`import type { Terminal, Continue } from './query/transitions.js'`). Because `queryLoop` carries `transition: Continue | undefined` on its `State` struct ([`query.ts:216`](../../query.ts)) and returns `Terminal` from every exit branch ([`query.ts:250`](../../query.ts)), every variant of both unions is directly visible in `query.ts`.

### Reconstructed Contract (`query/transitions.ts`)

```ts
// RECONSTRUCTED FROM CALL SITES — ABSENT FROM SNAPSHOT
// Exhaustively verified across all 7 state.transition assignments and 12 return sites in query.ts

export type Continue =
  | { reason: 'collapse_drain_retry'; committed: number }      // query.ts:1109-1112
  | { reason: 'reactive_compact_retry' }                       // query.ts:1162
  | { reason: 'max_output_tokens_escalate' }                   // query.ts:1217
  | { reason: 'max_output_tokens_recovery'; attempt: number }  // query.ts:1245-1248
  | { reason: 'stop_hook_blocking' }                           // query.ts:1302
  | { reason: 'token_budget_continuation' }                    // query.ts:1338
  | { reason: 'next_turn' }                                    // query.ts:1725

export type Terminal =
  | { reason: 'blocking_limit' }                               // query.ts:646
  | { reason: 'image_error' }                                  // query.ts:977, 1175
  | { reason: 'model_error'; error: unknown }                  // query.ts:996
  | { reason: 'aborted_streaming' }                            // query.ts:1051
  | { reason: 'prompt_too_long' }                              // query.ts:1175, 1182
  | { reason: 'completed' }                                    // query.ts:1264, 1357
  | { reason: 'stop_hook_prevented' }                          // query.ts:1279
  | { reason: 'aborted_tools' }                                // query.ts:1515
  | { reason: 'hook_stopped' }                                 // query.ts:1520
  | { reason: 'max_turns'; turnCount: number }                 // query.ts:1711
```

### Hidden Invariants Revealed by the Transitions

Three production scars sit directly on these discriminated unions:

1. **One-shot drain loop-breaker (`query.ts:1090-1093`).**
   `state.transition` is not just for tests—it actively drives control flow. On a withheld HTTP 413, `query.ts` only invokes `contextCollapse.recoverFromOverflow(...)` if `state.transition?.reason !== 'collapse_drain_retry'`. If draining staged collapses still overflows on the retry, the loop refuses to drain again and falls through to `reactiveCompact.tryReactiveCompact(...)`.
2. **Preserving `hasAttemptedReactiveCompact` across `stop_hook_blocking` (`query.ts:1292-1297`).**
   Unlike `next_turn` and `token_budget_continuation` (which reset `hasAttemptedReactiveCompact: false`), `stop_hook_blocking` explicitly preserves `hasAttemptedReactiveCompact`. Resetting it previously caused an infinite loop (`compact → still 413 → error → stop hook blocking → compact → ...`) burning thousands of API calls.
3. **Why API errors return `{ reason: 'completed' }` instead of running stop hooks (`query.ts:1262-1265`).**
   When `lastMessage?.isApiErrorMessage` is true and no recovery path claimed it, `queryLoop` fires `executeStopFailureHooks(...)` asynchronously and exits immediately with `{ reason: 'completed' }`—bypassing `handleStopHooks` so a blocking stop hook can never inject more tokens onto a failing turn.

---

## 4. Reconstructed from Call Sites: Context Collapse & Compaction Extensions

> [!NOTE]
> **Reconstructed from Call Sites — Absent from Snapshot.**
> Four compaction/context-management subsystems discussed in [Chapter 09](../chapters/09-five-layer-compaction-pipeline.md) are compiled out of external builds via `feature('CONTEXT_COLLAPSE')`, `feature('REACTIVE_COMPACT')`, `feature('HISTORY_SNIP')`, and `feature('CACHED_MICROCOMPACT')`. Their call sites in `query.ts`, `QueryEngine.ts`, `services/compact/microCompact.ts`, `services/api/claude.ts`, `commands/compact/compact.ts`, `utils/sessionRestore.ts`, and `types/logs.ts` specify almost their entire public contracts.

### 4.1 `services/contextCollapse/{index,operations,persist}.ts` (`feature('CONTEXT_COLLAPSE')`)

Context collapse (internally codenamed `marble-origami` in [`types/logs.ts:256,283`](../../types/logs.ts)) maintains a background-staged queue of message-span summaries and applies them as a **read-time projection** over the REPL's full history before autocompact runs ([`query.ts:428-447`](../../query.ts)). Nothing is yielded to the REPL; instead, commit and snapshot entries are appended to the JSONL transcript via [`utils/sessionStorage.ts:1541-1581`](../../utils/sessionStorage.ts).

```ts
// RECONSTRUCTED FROM CALL SITES — ABSENT FROM SNAPSHOT

// --- services/contextCollapse/index.ts ---
export type ContextCollapseStats = {                            // TokenWarning.tsx:40-42, ContextVisualization.tsx:37-56, context-noninteractive.ts:119-145
  collapsedSpans: number; collapsedMessages: number; stagedSpans: number
  health: {
    totalSpawns: number; totalErrors: number; totalEmptySpawns: number
    emptySpawnWarningEmitted: boolean; lastError?: string | null
  }
}
export function isContextCollapseEnabled(): boolean             // query.ts:618, utils/analyzeContext.ts:1121
export function getStats(): ContextCollapseStats                // TokenWarning.tsx:34, ContextVisualization.tsx:30
export function subscribe(cb: () => void): () => void           // TokenWarning.tsx:35, 48 (useSyncExternalStore)
export function resetContextCollapse(): void                    // postCompactCleanup.ts:47, screens/REPL.tsx:3686
export function applyCollapsesIfNeeded(
  messages: Message[], toolUseContext: ToolUseContext, querySource: QuerySource,
): Promise<{ messages: Message[] }>                             // query.ts:441-446
export function isWithheldPromptTooLong(
  message: Message, isPromptTooLongMessage: (m: Message) => boolean, querySource: QuerySource,
): boolean                                                      // query.ts:802-806
export function recoverFromOverflow(
  messages: Message[], querySource: QuerySource,
): { committed: number; messages: Message[] }                   // query.ts:1094-1112

// --- services/contextCollapse/operations.ts & persist.ts ---
export function projectView(messages: Message[]): Message[]     // commands/context/{context.tsx:23-26,context-noninteractive.ts:52-55}
export function restoreFromEntries(                             // utils/sessionRestore.ts:130-134, 497-501; ResumeConversation.tsx:267
  commits: ContextCollapseCommitEntry[],                        // types/logs.ts:255-269 ('marble-origami-commit', replay-all)
  snapshot: ContextCollapseSnapshotEntry | undefined,           // types/logs.ts:282-295 ('marble-origami-snapshot', last-wins)
): void
```

Notice the persistence asymmetry documented in [`types/logs.ts:239-295`](../../types/logs.ts): commits (`'marble-origami-commit'`) are **append-only and replayed in order** (storing only `firstArchivedUuid`, `lastArchivedUuid`, `collapseId`, `summaryUuid`, `summaryContent`, and `summary`, never the archived messages themselves), while snapshots (`'marble-origami-snapshot'`) are **last-wins** and store the `staged[]` queue plus `armed: boolean` and `lastSpawnTokens: number` so the background spawn timer resumes where it left off.

### 4.2 `services/compact/reactiveCompact.ts` (`feature('REACTIVE_COMPACT')`)

```ts
// RECONSTRUCTED FROM CALL SITES — ABSENT FROM SNAPSHOT
// Verified at query.ts:627, 633, 811, 816, 1084, 1120-1166 and commands/compact/compact.ts:35-37, 87-94, 175-218

export type ReactiveCompactOutcome =
  | { ok: true; result: CompactionResult }
  | { ok: false; reason: 'too_few_groups' | 'aborted' | 'exhausted' | 'error' | 'media_unstrippable' } // compact.ts:185-194

export function isReactiveCompactEnabled(): boolean                   // query.ts:627, 633
export function isReactiveOnlyMode(): boolean                         // commands/compact/compact.ts:87
export function isWithheldPromptTooLong(message: Message): boolean    // query.ts:811
export function isWithheldMediaSizeError(message: Message): boolean   // query.ts:816, 1084
export function tryReactiveCompact(params: {                          // query.ts:1120-1132
  hasAttempted: boolean; querySource: QuerySource; aborted: boolean
  messages: Message[]; cacheSafeParams: CacheSafeParams
}): Promise<CompactionResult | null>
export function reactiveCompactOnPromptTooLong(                       // commands/compact/compact.ts:175-179
  messages: Message[], cacheSafeParams: CacheSafeParams,
  options?: { customInstructions?: string; trigger?: 'manual' | 'auto' },
): Promise<ReactiveCompactOutcome>
```

Note the hook-ordering invariant documented at [`commands/compact/compact.ts:205-208`](../../commands/compact/compact.ts): `reactiveCompactOnPromptTooLong` runs `PostCompact` hooks internally, but leaves `PreCompact` hooks to its callers (`compactViaReactive` and `tryReactiveCompact`) so both callers can merge `PreCompact` and `PostCompact` `userDisplayMessage` strings.

### 4.3 `services/compact/{snipCompact,snipProjection}.ts` (`feature('HISTORY_SNIP')`)

```ts
// RECONSTRUCTED FROM CALL SITES — ABSENT FROM SNAPSHOT
// Verified at query.ts:401-410, QueryEngine.ts:122-128, 906-916, 1277-1283,
// utils/messages.ts:2351-2355, 2422-2425, 4150-4156, 4648-4653, components/Message.tsx:249-277

// --- services/compact/snipCompact.ts ---
export const SNIP_NUDGE_TEXT: string                            // utils/messages.ts:4150-4155
export function isSnipRuntimeEnabled(): boolean                 // utils/messages.ts:2352, 2422
export function isSnipMarkerMessage(message: Message | NormalizedMessage): boolean // components/Message.tsx:254, 276
export function snipCompactIfNeeded(                            // query.ts:403-408, QueryEngine.ts:911-914, 1281
  messages: Message[], options?: { force?: boolean },
): { messages: Message[]; tokensFreed: number; boundaryMessage?: SystemMessage; executed?: boolean }

// --- services/compact/snipProjection.ts ---
export function isSnipBoundaryMessage(message: Message | NormalizedMessage): boolean // QueryEngine.ts:1279, components/Message.tsx:251
export function projectSnippedView(messages: Message[]): Message[]                   // utils/messages.ts:4650-4653
```

### 4.4 `services/compact/{cachedMicrocompact,cachedMCConfig}.ts` (`feature('CACHED_MICROCOMPACT')`)

Unlike disk-persisting microcompact, cached microcompact leaves local message content intact and asks the API server to delete stale tool results out of the cached prefix via `cache_edits` blocks ([`services/compact/microCompact.ts:300-399`](../../services/compact/microCompact.ts), [`services/api/claude.ts:3052-3165`](../../services/api/claude.ts)).

```ts
// RECONSTRUCTED FROM CALL SITES — ABSENT FROM SNAPSHOT
// Verified at services/compact/microCompact.ts:56-135, 305-399,
// services/api/claude.ts:1190-1205, 3052-3162, constants/prompts.ts:66-70, 821-829

// --- services/compact/cachedMCConfig.ts (also re-exported by cachedMicrocompact.ts) ---
export type CachedMCConfig = { triggerThreshold: number; keepRecent: number; supportedModels?: string[] }
export function getCachedMCConfig(): CachedMCConfig             // constants/prompts.ts:68-69, microCompact.ts:311, claude.ts:1194

// --- services/compact/cachedMicrocompact.ts ---
export type CacheEditsBlock = { type: 'cache_edits'; edits: { type: 'delete'; cache_reference: string }[] } // claude.ts:3052-3055
export type PinnedCacheEdits = { userMessageIndex: number; block: CacheEditsBlock }                         // claude.ts:3057-3060
export type CachedMCState = {                                   // microCompact.ts:104, 116, 322, 351
  registeredTools: Set<string>; toolOrder: string[]; deletedRefs: Set<string>; pinnedEdits: PinnedCacheEdits[]
}
export function isCachedMicrocompactEnabled(): boolean          // claude.ts:1192
export function isModelSupportedForCacheEditing(model: string): boolean // claude.ts:1193, 1199
export function createCachedMCState(): CachedMCState            // microCompact.ts:73
export function resetCachedMCState(state: CachedMCState): void  // microCompact.ts:132
export function markToolsSentToAPI(state: CachedMCState): void  // microCompact.ts:126
export function registerToolResult(state: CachedMCState, toolUseId: string): void   // microCompact.ts:324
export function registerToolMessage(state: CachedMCState, groupIds: string[]): void // microCompact.ts:328
export function getToolResultsToDelete(state: CachedMCState): string[]              // microCompact.ts:332
export function createCacheEditsBlock(state: CachedMCState, toolsToDelete: string[]): CacheEditsBlock | null // microCompact.ts:336
```

---

## 5. Reconstructed from Call Sites: `services/skillSearch/` & `proactive/`

> [!NOTE]
> **Reconstructed from Call Sites — Absent from Snapshot.**
> Both subsystems are stripped completely from external builds via `feature('EXPERIMENTAL_SKILL_SEARCH')` and `feature('PROACTIVE') || feature('KAIROS')`. Their call sites across `query.ts`, `utils/attachments.ts`, `tools/SkillTool/SkillTool.ts`, `screens/REPL.tsx`, `cli/print.ts`, `main.tsx`, and `commands.ts` expose every integration hook.

### 5.1 `services/skillSearch/*` (`feature('EXPERIMENTAL_SKILL_SEARCH')`)

Seven files live behind this gate: `featureCheck.ts`, `prefetch.ts`, `localSearch.ts`, `remoteSkillState.ts`, `remoteSkillLoader.ts`, `signals.ts`, and `telemetry.ts`. Turn-0 user-input discovery runs synchronously inside `getAttachmentMessages` ([`utils/attachments.ts:801-812`](../../utils/attachments.ts)), while inter-turn discovery is launched concurrently at the top of each `queryLoop` iteration (`startSkillDiscoveryPrefetch`, [`query.ts:331-335`](../../query.ts)) and awaited post-tools (`collectSkillDiscoveryPrefetch`, [`query.ts:1620-1628`](../../query.ts)) so its ~250–573 ms latency hides behind the main turn.

```ts
// RECONSTRUCTED FROM CALL SITES — ABSENT FROM SNAPSHOT

// --- services/skillSearch/signals.ts ---
export type DiscoverySignal = string                            // Exact string union unobserved; used on Attachment { type: 'skill_discovery', signal: DiscoverySignal, source: 'native' | 'aki' | 'both' } at utils/attachments.ts:538-541

// --- services/skillSearch/featureCheck.ts ---
export function isSkillSearchEnabled(): boolean                 // constants/prompts.ts:779, utils/attachments.ts:2694, tools/SkillTool/SkillTool.ts:141, 663

// --- services/skillSearch/localSearch.ts ---
// Outer lodash-memoized getSkillIndex cache over getSkillToolCommands/getCommands (commands.ts:527-531)
export function clearSkillIndexCache(): void                    // commands.ts:96-100, 531; services/mcp/useManageMCPConnections.ts:27-31, 694, 738

// --- services/skillSearch/prefetch.ts ---
export type PendingSkillPrefetch = unknown                                            // opaque handle passed from start -> collect
export function getTurnZeroSkillDiscovery(
  input: string | ContentBlockParam[], messages: Message[], context: ToolUseContext,
): Promise<Attachment[]>                                                              // utils/attachments.ts:806-810
export function startSkillDiscoveryPrefetch(
  input: null, messages: Message[], toolUseContext: ToolUseContext,
): PendingSkillPrefetch | null                                                        // query.ts:331-335
export function collectSkillDiscoveryPrefetch(
  pending: PendingSkillPrefetch,
): Promise<Attachment[]>                                                              // query.ts:1621-1623

// --- services/skillSearch/remoteSkillState.ts ---
export type DiscoveredRemoteSkillMeta = { url: string; /* other fields unobserved */ } // SkillTool.ts:981, 988
export function stripCanonicalPrefix(commandName: string): string | null               // SkillTool.ts:381, 496, 609 (strips `_canonical_<slug>`)
export function getDiscoveredRemoteSkill(slug: string): DiscoveredRemoteSkillMeta | undefined // SkillTool.ts:385, 981

// --- services/skillSearch/remoteSkillLoader.ts & telemetry.ts ---
export function loadRemoteSkill(slug: string, url: string): Promise<{                 // SkillTool.ts:991, 1004-1012
  cacheHit: boolean; latencyMs: number; skillPath: string; content: string
  fileCount: number; totalBytes: number; fetchMethod: string
}>
export function logRemoteSkillLoaded(params: {                                        // SkillTool.ts:994-1000, 1014-1022
  slug: string; cacheHit: boolean; latencyMs: number; urlScheme: string
  error?: string; fileCount?: number; totalBytes?: number; fetchMethod?: string
}): void
```

### 5.2 `proactive/index.ts` & `proactive/useProactive.ts` (`feature('PROACTIVE') || feature('KAIROS')`)

`proactive/index.ts` is imported by **11 files** (`constants/prompts.ts`, `cli/print.ts`, `main.tsx`, `services/compact/prompt.ts`, `utils/systemPrompt.ts`, `components/PromptInput/{usePromptInputPlaceholder,PromptInputFooterLeftSide}.tsx`, `components/Messages.tsx`, `screens/REPL.tsx`, `commands/clear/conversation.ts`, `tools/AgentTool/AgentTool.tsx`). Together they reveal a classic external-store state machine wired into React via `useSyncExternalStore` ([`screens/REPL.tsx:687`](../../screens/REPL.tsx), [`components/PromptInput/PromptInputFooterLeftSide.tsx:76,264`](../../components/PromptInput/PromptInputFooterLeftSide.tsx)):

```ts
// RECONSTRUCTED FROM CALL SITES — ABSENT FROM SNAPSHOT

// --- proactive/index.ts ---
export function isProactiveActive(): boolean                    // 10 callers: prompts.ts:468,854,862; print.ts:541,1839,2478,3884; REPL.tsx:687,2776; main.tsx:4617; AgentTool.tsx:567; etc.
export function isProactivePaused(): boolean                    // cli/print.ts:1840, 2479
export function activateProactive(source: 'command' | string): void // main.tsx:4618, cli/print.ts:544, 3885
export function deactivateProactive(): void                     // cli/print.ts:3889
export function pauseProactive(): void                          // screens/REPL.tsx:2116
export function resumeProactive(): void                         // screens/REPL.tsx:3155
export function setContextBlocked(blocked: boolean): void       // screens/REPL.tsx:2606, 2636, 2638, 2739, 4969; commands/clear/conversation.ts:116
export function subscribeToProactiveChanges(cb: () => void): () => void // screens/REPL.tsx:687; PromptInputFooterLeftSide.tsx:76, 264
export function getNextTickAt(): number | null                  // PromptInputFooterLeftSide.tsx:76, 264

// --- proactive/useProactive.ts ---
export function useProactive(options: {                         // screens/REPL.tsx:4079-4095
  isLoading: boolean
  queuedCommandsLength: number
  hasActiveLocalJsxUI: boolean
  isInPlanMode: boolean
  onSubmitTick: (prompt: string) => void
  onQueueTick: (prompt: string) => void
}): void
```

Notice the subtle cross-subsystem coupling revealed by those 11 call sites: when `isProactiveActive()` is true, [`tools/AgentTool/AgentTool.tsx:567`](../../tools/AgentTool/AgentTool.tsx) forces subagents to run asynchronously (`shouldRunAsync`), [`services/compact/prompt.ts:361-368`](../../services/compact/prompt.ts) injects an autonomous-continuation instruction so compaction does not reset the loop into greeting the user, [`components/Messages.tsx:603`](../../components/Messages.tsx) disables the terminal progress bar, and [`commands/clear/conversation.ts:112-117`](../../commands/clear/conversation.ts) calls `setContextBlocked(false)` so proactive ticks resume after `/clear`.

---

## Putting the Boundary Map Together

The diagram below shows how the upstream monorepo passes through four build-time filters to produce the exact 1,903-file snapshot—and which surviving artifacts anchor each forensic reconstruction:

```mermaid
flowchart LR
    U["Upstream Monorepo"] --> F1["TS Type Erasure (31 type-only + 2 .generated.ts)"]
    U --> F2["Bun DCE: feature() & USER_TYPE='ant' (119 modules)"]
    U --> F3["Asset Inlining (33 .md / .txt files)"]
    U --> F4["External & @ant/* Packages (13 packages)"]
    U --> S["Tracked Snapshot (1,903 JS/TS/TSX files)"]

    S --> R1["Constructors & Exhaustive Switches -> types/message.ts & query/transitions.ts"]
    S --> R2["as typeof import() & Obfuscated Logs -> contextCollapse & compact/*"]
    S --> R3["Feature-Gated Call Sites -> skillSearch/* & proactive/*"]
```

---

## Reading Exercises & Code Checkpoints

1. **Audit every `excluded-strings` boundary in the repo.**
   Run:
   ```sh
   rg -n "excluded-strings|excluded string|would leak into external builds|leak into external" --glob '!book/**'
   ```
   Inspect each match (including [`types/logs.ts:249-253`](../../types/logs.ts), [`QueryEngine.ts:903-904`](../../QueryEngine.ts), [`utils/attachments.ts:89-93`](../../utils/attachments.ts), and [`query.ts:868-870`](../../query.ts)) to see how build-time string-leak guards shape module boundaries across the codebase.
2. **Reconstruct `constants/querySource.ts` from its 21 call sites.**
   Run:
   ```sh
   rg -n "querySource\s*[!=]==|querySource:\s*'" --glob '!book/**'
   ```
   Collect every string literal compared against or passed as `querySource` (such as `'repl_main_thread'`, `'sdk'`, `'session_memory'`, and `'compact'`) and verify which prefixes [`services/compact/microCompact.ts`](../../services/compact/microCompact.ts) treats as main-thread sources.
3. **Trace constant-folded `USER_TYPE` gates in React-Compiler-transformed `.tsx` files.**
   Run:
   ```sh
   rg -n '"external" === .ant.' --glob '!book/**'
   ```
   Compare those matches against raw `process.env.USER_TYPE === 'ant'` checks in `.ts` files (`rg -n "USER_TYPE === 'ant'" --glob '!book/**' | head -n 20`) to observe how the `.tsx` snapshot files were captured post-transform with `USER_TYPE` already folded to `"external"`.


---

<!-- appendices/C-mini-harness-blueprint.md — https://reverseengineeringclaudecode.com/appendices/C-mini-harness-blueprint -->

# Appendix C — Mini-Harness Blueprint: Building a 500-Line Working Toy Clone Using the Patterns in This Book

> **Layer:** Capstone Synthesis (Layers 0–8)
> **Prerequisites:** [Chapters 00](../chapters/00-how-to-read-a-1900-file-agent.md)–[24](../chapters/24-across-the-wire-remote-sessions-bridge-and-direct-connect.md), [Appendix A](A-feature-flags-and-env-knobs.md), and [Appendix B](B-missing-snapshot-boundaries.md)
> **Scope:** Standalone educational TypeScript blueprint (~440 lines of TypeScript across 12 miniature modules). Because this repository snapshot is source-only with no `package.json` or `tsconfig.json` ([Chapter 00](../chapters/00-how-to-read-a-1900-file-agent.md)), treat this as a self-contained blueprint to drop into a fresh TypeScript project rather than a command to run inside this checkout.
> **Primary Production Counterparts:** [state/store.ts](../../state/store.ts), [utils/fileStateCache.ts](../../utils/fileStateCache.ts), [utils/generators.ts](../../utils/generators.ts), [Tool.ts](../../Tool.ts), [tools.ts](../../tools.ts), [constants/prompts.ts](../../constants/prompts.ts), [constants/systemPromptSections.ts](../../constants/systemPromptSections.ts), [utils/api.ts](../../utils/api.ts), [services/tools/toolOrchestration.ts](../../services/tools/toolOrchestration.ts), [query.ts](../../query.ts), [utils/toolResultStorage.ts](../../utils/toolResultStorage.ts), [services/compact/autoCompact.ts](../../services/compact/autoCompact.ts), [services/compact/compact.ts](../../services/compact/compact.ts), [utils/permissions/permissions.ts](../../utils/permissions/permissions.ts), [services/tools/toolHooks.ts](../../services/tools/toolHooks.ts), [utils/forkedAgent.ts](../../utils/forkedAgent.ts), [tools/AgentTool/forkSubagent.ts](../../tools/AgentTool/forkSubagent.ts), [QueryEngine.ts](../../QueryEngine.ts), [utils/sessionStorage.ts](../../utils/sessionStorage.ts), [utils/cleanupRegistry.ts](../../utils/cleanupRegistry.ts)

## Why Build a Mini-Harness?

Across 1,884 TypeScript files, Claude Code layers enterprise policy, build-time `feature()` flags ([Appendix A](A-feature-flags-and-env-knobs.md)), 60+ tools, a vendored terminal React renderer, and remote bridges. Strip away every product feature and keep only the load-bearing beams, and the entire runtime distills to **eight architectural patterns** in ~440 lines of TypeScript:

1. **Zero-dependency Layer 0 atoms** (`store.ts`, `fileStateCache.ts`, `generators.ts`) — identity-guarded reactivity, path-normalized staleness, bounded async-generator multiplexing.
2. **Fail-closed tool contracts & partitioned sorting** (`tool.ts`) — unsafe concurrency opt-in and cache-stable built-in tool prefixes.
3. **Static/dynamic prompt boundaries** (`prompt.ts`) — isolating globally cacheable system instructions from volatile session context.
4. **Concurrent-read / serial-write batching with ordered context replay** (`orchestration.ts`) — parallelism without non-deterministic `ToolUseContext` races.
5. **An `AsyncGenerator` turn loop** (`query.ts`) — keyed on extracted `tool_use` blocks (never `stop_reason`), with withheld `max_output_tokens` recovery.
6. **Two-stage context survival** (`compact.ts`) — atomic `'wx'` disk spills (`Infinity` opt-out) plus boundary-preserving summarization with a 3-failure circuit breaker.
7. **Bypass-immune permissions & hook arbitration** (`permissions.ts`, `hooks.ts`) — neither `bypassPermissions` nor a `PreToolUse` `allow` overrides explicit deny/ask rules.
8. **Scoped subagent forking & append-only session envelopes** (`subagent.ts`, `engine.ts`) — frozen prompt caches, root-wired `setAppStateForTasks` (no `PPID=1` zombies), and crash-recoverable `parentUuid` JSONL transcripts.

> [!NOTE]
> **Snapshot boundary note:** `types/message.ts` and `query/transitions.ts` are absent from this source checkout (reconstructed from call sites in [Appendix B](B-missing-snapshot-boundaries.md)). The local `Message`, `Continue`, and `Terminal` types below reflect the exact shapes observed at call sites in [query.ts](../../query.ts) and [QueryEngine.ts](../../QueryEngine.ts).

```text
               ┌────────────────────────────────────────┐
 L8 engine.ts  │ QueryEngine + JSONL parentUuid +       │
               │ registerCleanup() shutdown registry    │
               └───────────────────┬────────────────────┘
                                   │ submitMessage()
               ┌───────────────────▼────────────────────┐
 L2 query.ts   │ AsyncGenerator<QueryEvent, Terminal>   │
               │ (toolUseBlocks exit + recovery loop)   │
               └───┬───────────────┬────────────────┬───┘
       prompt.ts ◄─┘   compact.ts  │                └─► orchestration.ts
 (cache boundary)  (spill + 3x CB) │                    (batch + replay)
                                   │                     │            │
                            subagent.ts           permissions.ts   hooks.ts
                         (clone+taskStore)        (deny > mode)  (no override)
                                   │                     │
               ┌───────────────────▼─────────────────────▼─┐
 L1 tool.ts    │ buildTool() fail-closed + assembleToolPool│
               └───────────────────┬───────────────────────┘
               ┌───────────────────▼───────────────────────┐
 L0 atoms      │ store.ts │ fileStateCache.ts │ generators │
               └───────────────────────────────────────────┘
```

## 1. Layer 0: Zero-Dependency Atoms (`store.ts`, `fileStateCache.ts`, `generators.ts`)

Before calling a model, the harness needs synchronous reactivity that suppresses no-op renders, a bounded path-normalized cache to stop blind stale overwrites, and concurrency-capped multiplexing over async generators ([Chapter 01](../chapters/01-atoms-types-stores-and-primitives.md)).

```ts
// mini/store.ts — mirrors state/store.ts:1-34
export type Store<T> = {
  getState: () => T; setState: (updater: (prev: T) => T) => void; subscribe: (fn: () => void) => () => void
}
export function createStore<T>(initial: T, onChange?: (a: { newState: T; oldState: T }) => void): Store<T> {
  let state = initial
  const listeners = new Set<() => void>()
  return {
    getState: () => state,
    setState(updater) {
      const prev = state, next = updater(prev)
      if (Object.is(next, prev)) return // Identity bailout prevents render storms
      state = next
      onChange?.({ newState: next, oldState: prev })
      for (const fn of listeners) fn()
    },
    subscribe: fn => (listeners.add(fn), () => listeners.delete(fn)),
  }
}

// mini/fileStateCache.ts — mirrors utils/fileStateCache.ts:4-142
import { normalize } from 'path'
export type FileState = { content: string; timestamp: number; isPartialView?: boolean }
export class FileStateCache {
  private map = new Map<string, FileState>()
  private bytes = 0
  constructor(private maxEntries = 100, private maxBytes = 25 * 1024 * 1024) {}
  get(filePath: string): FileState | undefined {
    const key = normalize(filePath), hit = this.map.get(key)
    if (!hit) return undefined
    this.map.delete(key); this.map.set(key, hit) // Refresh LRU recency
    return hit
  }
  set(filePath: string, value: FileState): this {
    const key = normalize(filePath), prev = this.map.get(key)
    if (prev) { this.bytes -= Math.max(1, Buffer.byteLength(prev.content)); this.map.delete(key) }
    this.map.set(key, value); this.bytes += Math.max(1, Buffer.byteLength(value.content))
    while (this.map.size > this.maxEntries || this.bytes > this.maxBytes) {
      const oldest = this.map.keys().next().value
      if (oldest === undefined || oldest === key) break
      this.bytes -= Math.max(1, Buffer.byteLength(this.map.get(oldest)!.content))
      this.map.delete(oldest)
    }
    return this
  }
  isStale(filePath: string, currentMtimeMs: number): boolean {
    const entry = this.get(filePath)
    return !entry || entry.isPartialView === true || currentMtimeMs > entry.timestamp
  }
  clone(): FileStateCache {
    const copy = new FileStateCache(this.maxEntries, this.maxBytes)
    for (const [k, v] of this.map) copy.set(k, { ...v })
    return copy
  }
}

// mini/generators.ts — mirrors utils/generators.ts:32-72
type Queued<A> = { done?: boolean; value?: A; gen: AsyncGenerator<A, void>; p: Promise<Queued<A>> }
export async function* all<A>(gens: AsyncGenerator<A, void>[], cap = Infinity): AsyncGenerator<A, void> {
  const step = (gen: AsyncGenerator<A, void>): Promise<Queued<A>> => {
    const p: Promise<Queued<A>> = gen.next().then(({ done, value }) => ({ done, value, gen, p }))
    return p
  }
  const waiting = [...gens], active = new Set<Promise<Queued<A>>>()
  while (active.size < cap && waiting.length > 0) active.add(step(waiting.shift()!))
  while (active.size > 0) {
    const { done, value, gen, p } = await Promise.race(active)
    active.delete(p)
    if (!done) { active.add(step(gen)); if (value !== undefined) yield value }
    else if (waiting.length > 0) active.add(step(waiting.shift()!))
  }
}
```

**Production invariants preserved:** `Object.is` identity short-circuit ([state/store.ts:23](../../state/store.ts#L23)); path normalization + 25 MB byte-weighted LRU + `isPartialView` edit guard ([utils/fileStateCache.ts:14,41-48](../../utils/fileStateCache.ts#L41-L48)); self-referencing promise handles in `all()` ([utils/generators.ts:37-45](../../utils/generators.ts#L37-L45)).

## 2. Layer 1: Fail-Closed Tool Contract & Cache-Stable Pool (`tool.ts`)

Omitting a safety flag on a mutating tool must never default to parallel execution, and dynamic MCP tools must never interleave with built-in tools in alphabetical sort order or they shift tool indices and bust server-side global prompt caching ([Chapter 02](../chapters/02-the-tool-contract.md)).

```ts
// mini/tool.ts — mirrors Tool.ts:743-792 and tools.ts:345-367
import type { FileStateCache } from './fileStateCache.js'
import type { Store } from './store.js'

export type PermissionMode = 'default' | 'bypassPermissions'
export type PermissionRule = { toolName: string; pattern?: string }
export type ToolPermissionContext = {
  mode: PermissionMode
  alwaysDenyRules: PermissionRule[]; alwaysAskRules: PermissionRule[]; alwaysAllowRules: PermissionRule[]
}
export type PermissionDecision =
  | { behavior: 'allow'; updatedInput?: Record<string, unknown>; reason: string }
  | { behavior: 'deny'; message: string; reason: string }
  | { behavior: 'ask'; message: string; reason: string }
  | { behavior: 'passthrough' }
export type AppState = { permissionContext: ToolPermissionContext; tasks: Record<string, { status: 'running' | 'stopped' }> }
export type ToolUseContext = {
  tools: Tool[]; readFileState: FileStateCache; abortController: AbortController
  getAppState: () => AppState; setAppState: Store<AppState>['setState']
  setAppStateForTasks: Store<AppState>['setState'] // Root-wired even inside subagents
  renderedSystemPrompt?: string[]; agentId?: string
}
export type Tool<Input = Record<string, unknown>, Output = string> = {
  name: string; description: string; isEnabled: () => boolean
  isConcurrencySafe: (input: Input) => boolean; isReadOnly: (input: Input) => boolean
  maxResultSizeChars: number // Infinity opts out of spill-to-disk (e.g. FileReadTool)
  checkPermissions: (input: Input, ctx: ToolUseContext) => Promise<PermissionDecision>
  call: (input: Input, ctx: ToolUseContext) => Promise<{ data: Output; contextModifier?: (c: ToolUseContext) => ToolUseContext }>
}
const TOOL_DEFAULTS = {
  isEnabled: () => true,
  isConcurrencySafe: () => false, // Fail-closed: assume unsafe unless proven read-only
  isReadOnly: () => false,        // Fail-closed: assume writes
  maxResultSizeChars: 50_000,
  checkPermissions: async (): Promise<PermissionDecision> => ({ behavior: 'passthrough' }),
}
export function buildTool<Input = Record<string, unknown>, Output = string>(
  def: Omit<Tool<Input, Output>, keyof typeof TOOL_DEFAULTS> & Partial<Pick<Tool<Input, Output>, keyof typeof TOOL_DEFAULTS>>,
): Tool<Input, Output> {
  return { ...TOOL_DEFAULTS, ...def }
}
export function assembleToolPool(builtIns: Tool[], mcpTools: Tool[], permCtx: ToolPermissionContext): Tool[] {
  const denied = new Set(permCtx.alwaysDenyRules.filter(r => !r.pattern).map(r => r.toolName))
  const byName = (a: Tool, b: Tool) => a.name.localeCompare(b.name)
  // Partition-sort so built-ins remain a contiguous global-cache prefix; built-ins win collisions
  const sortedBuiltIns = builtIns.filter(t => t.isEnabled() && !denied.has(t.name)).sort(byName)
  const sortedMcp = mcpTools.filter(t => t.isEnabled() && !denied.has(t.name)).sort(byName)
  const seen = new Set<string>()
  return [...sortedBuiltIns, ...sortedMcp].filter(t => (seen.has(t.name) ? false : (seen.add(t.name), true)))
}
```

**Production invariants preserved:** Fail-closed defaults in `buildTool()` ([Tool.ts:748-792](../../Tool.ts#L748-L792)) and two-partition sorting in `assembleToolPool()` ([tools.ts:354-366](../../tools.ts#L354-L366)).

## 3. Layer 2: Prompt Boundaries, Tool Orchestration, and the `query()` Turn Loop

Layer 2 solves three interlocking hazards: (1) keeping volatile context below `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` so global prompt caching stays hot ([Chapter 04](../chapters/04-prompt-engineering-and-cache-boundaries.md)); (2) running read-only tool batches concurrently while replaying `contextModifier` updates in strict block order ([Chapter 06](../chapters/06-executing-tools.md)); and (3) driving the turn state machine from extracted `tool_use` blocks rather than `stop_reason`, withholding `max_output_tokens` errors until recovery exhausts ([Chapter 05](../chapters/05-talking-to-the-model.md), [Chapter 07](../chapters/07-the-heartbeat-query-loop.md)).

```ts
// mini/prompt.ts — mirrors constants/prompts.ts:114-115, systemPromptSections.ts:20-58, utils/api.ts:362-397
export const SYSTEM_PROMPT_DYNAMIC_BOUNDARY = '__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__'
export type PromptSection = { name: string; compute: () => Promise<string | null>; cacheBreak: boolean }
export type SystemPromptBlock = { text: string; cacheScope: 'global' | null }
export const systemPromptSection = (name: string, compute: () => Promise<string | null>): PromptSection =>
  ({ name, compute, cacheBreak: false })
export const DANGEROUS_uncachedSystemPromptSection = (
  name: string, compute: () => Promise<string | null>, _reason: string,
): PromptSection => ({ name, compute, cacheBreak: true })
export function splitSystemPromptForCache(sections: string[]): SystemPromptBlock[] {
  const idx = sections.indexOf(SYSTEM_PROMPT_DYNAMIC_BOUNDARY)
  if (idx === -1) return [{ text: sections.filter(Boolean).join('\n\n'), cacheScope: null }]
  const staticText = sections.slice(0, idx).filter(Boolean).join('\n\n')
  const dynamicText = sections.slice(idx + 1).filter(Boolean).join('\n\n')
  return [
    ...(staticText ? [{ text: staticText, cacheScope: 'global' as const }] : []),
    ...(dynamicText ? [{ text: dynamicText, cacheScope: null }] : []),
  ]
}

// mini/orchestration.ts — mirrors services/tools/toolOrchestration.ts:19-160
import { all } from './generators.js'
import type { Tool, ToolUseContext } from './tool.js'
export type ToolUseBlock = { type: 'tool_use'; id: string; name: string; input: Record<string, unknown> }
export type ToolResultBlock = { type: 'tool_result'; tool_use_id: string; content: string; is_error?: boolean }
export type ToolRunResult = {
  result: ToolResultBlock; contextModifier?: { toolUseID: string; modify: (ctx: ToolUseContext) => ToolUseContext }
}
type Batch = { isConcurrencySafe: boolean; blocks: ToolUseBlock[] }
export function partitionToolCalls(blocks: ToolUseBlock[], tools: Tool[]): Batch[] {
  return blocks.reduce<Batch[]>((acc, block) => {
    const tool = tools.find(t => t.name === block.name)
    let safe = false
    try { safe = Boolean(tool?.isConcurrencySafe(block.input)) } catch { safe = false }
    if (safe && acc.at(-1)?.isConcurrencySafe) acc.at(-1)!.blocks.push(block)
    else acc.push({ isConcurrencySafe: safe, blocks: [block] })
    return acc
  }, [])
}
export async function* runTools(
  blocks: ToolUseBlock[], ctx: ToolUseContext,
  executeOne: (b: ToolUseBlock, c: ToolUseContext) => AsyncGenerator<ToolRunResult, void>, maxConcurrency = 10,
): AsyncGenerator<{ result?: ToolResultBlock; newContext: ToolUseContext }, void> {
  let current = ctx
  for (const batch of partitionToolCalls(blocks, current.tools)) {
    if (batch.isConcurrencySafe) {
      const queued = new Map<string, ((c: ToolUseContext) => ToolUseContext)[]>()
      for await (const upd of all(batch.blocks.map(b => executeOne(b, current)), maxConcurrency)) {
        if (upd.contextModifier) {
          const list = queued.get(upd.contextModifier.toolUseID) ?? []
          list.push(upd.contextModifier.modify); queued.set(upd.contextModifier.toolUseID, list)
        }
        yield { result: upd.result, newContext: current }
      }
      // Replay contextModifiers deterministically in original assistant block order
      for (const block of batch.blocks) for (const mod of queued.get(block.id) ?? []) current = mod(current)
      yield { newContext: current }
    } else {
      for (const block of batch.blocks) {
        for await (const upd of executeOne(block, current)) {
          if (upd.contextModifier) current = upd.contextModifier.modify(current)
          yield { result: upd.result, newContext: current }
        }
      }
    }
  }
}

// mini/query.ts — mirrors query.ts:204-239, 554-558, 826-835, 1062-1256
import { randomUUID } from 'crypto'
import { autoCompactIfNeeded, type AutoCompactTracking } from './compact.js'
import { runTools, type ToolResultBlock, type ToolUseBlock, type ToolRunResult } from './orchestration.js'
import { splitSystemPromptForCache, type SystemPromptBlock } from './prompt.js'
import type { ToolUseContext } from './tool.js'
export type ContentBlock = { type: 'text'; text: string } | ToolUseBlock | ToolResultBlock
export type Message = {
  uuid: string; role: 'user' | 'assistant' | 'system'; subtype?: 'compact_boundary'
  isMeta?: boolean; stopReason?: string; content: ContentBlock[]
}
export type Continue = { reason: 'next_turn' } | { reason: 'max_output_tokens_recovery'; attempt: number }
export type Terminal = { reason: 'completed' | 'aborted' | 'max_turns' | 'max_output_tokens' }
export type QueryEvent = { type: 'message'; message: Message } | { type: 'transition'; next: Continue }
export type ModelAdapter = (a: {
  system: SystemPromptBlock[]; messages: Message[]; tools: ToolUseContext['tools']; signal: AbortSignal
}) => AsyncGenerator<Message, void>

const MAX_OUTPUT_TOKENS_RECOVERY_LIMIT = 3
export async function* query(params: {
  messages: Message[]; systemPrompt: string[]; toolUseContext: ToolUseContext; maxTurns?: number
  callModel: ModelAdapter; summarize: (msgs: Message[]) => Promise<string>
  executeOne: (b: ToolUseBlock, c: ToolUseContext) => AsyncGenerator<ToolRunResult, void>
}): AsyncGenerator<QueryEvent, Terminal> {
  let state = {
    messages: params.messages, ctx: { ...params.toolUseContext, renderedSystemPrompt: params.systemPrompt },
    compactTracking: { consecutiveFailures: 0 } as AutoCompactTracking,
    maxOutputTokensRecoveryCount: 0, turnCount: 0, transition: undefined as Continue | undefined,
  }
  const systemBlocks = splitSystemPromptForCache(params.systemPrompt)
  while (true) {
    if (state.ctx.abortController.signal.aborted) return { reason: 'aborted' }
    const compacted = await autoCompactIfNeeded(state.messages, state.compactTracking, params.summarize)
    state.compactTracking = compacted.tracking
    if (compacted.wasCompacted) state.messages = compacted.messages

    const assistantMessages: Message[] = [], toolUseBlocks: ToolUseBlock[] = []
    let needsFollowUp = false // Sole continuation signal — NEVER trust stop_reason === 'tool_use'
    let withheldMaxTokens: Message | undefined
    for await (const msg of params.callModel({
      system: systemBlocks, messages: state.messages, tools: state.ctx.tools, signal: state.ctx.abortController.signal,
    })) {
      assistantMessages.push(msg)
      const extracted = msg.content.filter((b): b is ToolUseBlock => b.type === 'tool_use')
      if (extracted.length > 0) { toolUseBlocks.push(...extracted); needsFollowUp = true }
      if (msg.stopReason === 'max_tokens' && !needsFollowUp) { withheldMaxTokens = msg; continue }
      yield { type: 'message', message: msg }
    }
    if (!needsFollowUp) {
      if (withheldMaxTokens && state.maxOutputTokensRecoveryCount < MAX_OUTPUT_TOKENS_RECOVERY_LIMIT) {
        const attempt = state.maxOutputTokensRecoveryCount + 1
        const nudge: Message = {
          uuid: randomUUID(), role: 'user', isMeta: true,
          content: [{ type: 'text', text: 'Output token limit hit. Resume directly without recap.' }],
        }
        state = {
          ...state, messages: [...state.messages, ...assistantMessages, nudge],
          maxOutputTokensRecoveryCount: attempt, transition: { reason: 'max_output_tokens_recovery', attempt },
        }
        yield { type: 'transition', next: state.transition! }; continue
      }
      if (withheldMaxTokens) { yield { type: 'message', message: withheldMaxTokens }; return { reason: 'max_output_tokens' } }
      return { reason: 'completed' }
    }
    const resultBlocks: ToolResultBlock[] = []
    for await (const upd of runTools(toolUseBlocks, state.ctx, params.executeOne)) {
      state.ctx = upd.newContext; if (upd.result) resultBlocks.push(upd.result)
    }
    const toolResultMsg: Message = { uuid: randomUUID(), role: 'user', content: resultBlocks }
    yield { type: 'message', message: toolResultMsg }
    const nextTurn = state.turnCount + 1
    if (params.maxTurns && nextTurn >= params.maxTurns) return { reason: 'max_turns' }
    state = {
      ...state, messages: [...state.messages, ...assistantMessages, toolResultMsg],
      maxOutputTokensRecoveryCount: 0, turnCount: nextTurn, transition: { reason: 'next_turn' },
    }
    yield { type: 'transition', next: state.transition! }
  }
}
```

**Production invariants preserved:** Loudly named `DANGEROUS_uncachedSystemPromptSection(_reason)` and cache split ([constants/systemPromptSections.ts:32-38](../../constants/systemPromptSections.ts#L32-L38), [utils/api.ts:363-396](../../utils/api.ts#L363-L396)); block-ordered `contextModifier` replay ([services/tools/toolOrchestration.ts:54-62](../../services/tools/toolOrchestration.ts#L54-L62)); `needsFollowUp` over `stop_reason` plus withheld `max_output_tokens` recovery ([query.ts:554-558,829-835,1188-1255](../../query.ts#L554-L558)).

## 4. Layer 3: Two-Stage Context Survival (`compact.ts`)

A single huge command output can blow past the context limit, while multi-hour sessions fill history gradually. Spilling `FileReadTool` outputs would create a circular Read→file→Read loop, and retrying broken compaction calls forever hammers the API ([Chapter 06](../chapters/06-executing-tools.md), [Chapter 09](../chapters/09-five-layer-compaction-pipeline.md)).

```ts
// mini/compact.ts — mirrors utils/toolResultStorage.ts:55-226 and services/compact/autoCompact.ts:70,241-351
import { randomUUID } from 'crypto'
import { mkdir, writeFile } from 'fs/promises'
import { join } from 'path'
import type { ToolResultBlock } from './orchestration.js'
import type { Message } from './query.js'

const PREVIEW_CHARS = 2_000, COMPACT_TOKEN_THRESHOLD = 140_000
export const MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES = 3
export type AutoCompactTracking = { consecutiveFailures: number; compacted?: boolean }

export async function maybePersistLargeToolResult(
  block: ToolResultBlock, maxResultSizeChars: number, spillDir: string,
): Promise<ToolResultBlock> {
  // Infinity = hard opt-out (e.g. FileReadTool); spilling Read output would recurse
  if (!Number.isFinite(maxResultSizeChars) || block.content.length <= maxResultSizeChars) return block
  await mkdir(spillDir, { recursive: true })
  const filepath = join(spillDir, `${block.tool_use_id}.txt`)
  try { await writeFile(filepath, block.content, { flag: 'wx' }) } // Atomic create avoids stat/write race
  catch (err: unknown) { if ((err as NodeJS.ErrnoException).code !== 'EEXIST') return block }
  return {
    ...block,
    content: `<persisted-output>\nSaved (${block.content.length} chars) to ${filepath}\n${block.content.slice(0, PREVIEW_CHARS)}\n...\n</persisted-output>`,
  }
}

export async function autoCompactIfNeeded(
  messages: Message[], tracking: AutoCompactTracking, summarize: (msgs: Message[]) => Promise<string>,
): Promise<{ wasCompacted: boolean; messages: Message[]; tracking: AutoCompactTracking }> {
  if (tracking.consecutiveFailures >= MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES) return { wasCompacted: false, messages, tracking }
  if (Math.ceil(JSON.stringify(messages).length / 4) < COMPACT_TOKEN_THRESHOLD) return { wasCompacted: false, messages, tracking }
  try {
    const summaryText = await summarize(messages)
    const boundary: Message = { uuid: randomUUID(), role: 'system', subtype: 'compact_boundary', content: [{ type: 'text', text: 'Conversation compacted' }] }
    const summary: Message = { uuid: randomUUID(), role: 'user', isMeta: true, content: [{ type: 'text', text: summaryText }] }
    return { wasCompacted: true, messages: [boundary, summary], tracking: { consecutiveFailures: 0, compacted: true } }
  } catch {
    return { wasCompacted: false, messages, tracking: { ...tracking, consecutiveFailures: tracking.consecutiveFailures + 1 } }
  }
}
```

**Production invariants preserved:** `maxResultSizeChars: Infinity` + `'wx'` exclusive create ([utils/toolResultStorage.ts:59-60,157-160](../../utils/toolResultStorage.ts#L59-L60)) and `compact_boundary` + 3-failure circuit breaker ([services/compact/autoCompact.ts:70,257-265,338-349](../../services/compact/autoCompact.ts#L257-L265)).

## 5. Layer 4: Bypass-Immune Permissions & Hook Arbitration (`permissions.ts`, `hooks.ts`)

Evaluating `bypassPermissions` first silently defeats deny/ask rules and safety checks, while accepting a `PreToolUse` `allow` without re-checking rules lets any permissive plugin smuggle blocked commands past policy ([Chapter 11](../chapters/11-the-permission-engine.md), [Chapter 13](../chapters/13-the-hook-system.md)).

```ts
// mini/permissions.ts — mirrors utils/permissions/permissions.ts:1071-1310
import type { PermissionDecision, PermissionRule, Tool, ToolUseContext } from './tool.js'
const matchesRule = (r: PermissionRule, name: string, input: Record<string, unknown>): boolean =>
  r.toolName === name && (!r.pattern || JSON.stringify(input).includes(r.pattern))

export function checkRuleBasedPermissions(tool: Tool, input: Record<string, unknown>, ctx: ToolUseContext): PermissionDecision | null {
  const perms = ctx.getAppState().permissionContext
  const deny = perms.alwaysDenyRules.find(r => matchesRule(r, tool.name, input))
  if (deny) return { behavior: 'deny', reason: 'deny_rule', message: `Denied by rule: ${deny.toolName}` }
  const ask = perms.alwaysAskRules.find(r => matchesRule(r, tool.name, input))
  if (ask) return { behavior: 'ask', reason: 'ask_rule', message: `Confirmation required for ${tool.name}` }
  return null
}

export async function evaluatePermission(
  tool: Tool, input: Record<string, unknown>, ctx: ToolUseContext,
  promptUser: (t: Tool, i: Record<string, unknown>) => Promise<PermissionDecision>,
): Promise<PermissionDecision> {
  // 1. Bypass-immune deny/ask rules & tool safety checks run BEFORE bypassPermissions mode
  const rule = checkRuleBasedPermissions(tool, input, ctx)
  if (rule?.behavior === 'deny') return rule
  if (rule?.behavior === 'ask') return promptUser(tool, input)
  const toolDec = await tool.checkPermissions(input, ctx)
  if (toolDec.behavior === 'deny') return toolDec
  if (toolDec.behavior === 'ask') return promptUser(tool, input)
  // 2. Mode bypass and allow rules apply only AFTER deny/ask/safety gates clear
  const perms = ctx.getAppState().permissionContext
  if (perms.mode === 'bypassPermissions') return { behavior: 'allow', updatedInput: input, reason: 'mode' }
  if (perms.alwaysAllowRules.some(r => matchesRule(r, tool.name, input))) return { behavior: 'allow', updatedInput: input, reason: 'allow_rule' }
  return promptUser(tool, input)
}

// mini/hooks.ts — mirrors services/tools/toolHooks.ts:332-410
import { checkRuleBasedPermissions, evaluatePermission } from './permissions.js'
import type { PermissionDecision, Tool, ToolUseContext } from './tool.js'
export async function resolveHookPermissionDecision(
  hookResult: PermissionDecision | undefined, tool: Tool, input: Record<string, unknown>, ctx: ToolUseContext,
  promptUser: (t: Tool, i: Record<string, unknown>) => Promise<PermissionDecision>,
): Promise<{ decision: PermissionDecision; input: Record<string, unknown> }> {
  if (hookResult?.behavior === 'deny') return { decision: hookResult, input }
  if (hookResult?.behavior === 'allow') {
    const effectiveInput = hookResult.updatedInput ?? input
    // Critical invariant: hook 'allow' skips the prompt, NEVER a deny or ask rule
    const ruleCheck = checkRuleBasedPermissions(tool, effectiveInput, ctx)
    if (ruleCheck === null) return { decision: hookResult, input: effectiveInput }
    if (ruleCheck.behavior === 'deny') return { decision: ruleCheck, input: effectiveInput }
    return { decision: await promptUser(tool, effectiveInput), input: effectiveInput }
  }
  return { decision: await evaluatePermission(tool, input, ctx, promptUser), input }
}
```

**Production invariants preserved:** Strict step 1a–1g precedence before step 2a `bypassPermissions` ([utils/permissions/permissions.ts:1169-1281](../../utils/permissions/permissions.ts#L1169-L1281)) and post-rewrite rule enforcement in `resolveHookPermissionDecision()` ([services/tools/toolHooks.ts:372-405](../../services/tools/toolHooks.ts#L372-L405)).

## 6. Layer 6: Subagent Context Forking (`subagent.ts`)

Sharing raw parent context races on `readFileState` and corrupts parent UI; naively stubbing `setAppState` orphans child background shells (`PPID=1` zombies); rebuilding the child prompt destroys prefix cache sharing ([Chapter 18](../chapters/18-subagents-context-forking-and-worktrees.md)).

```ts
// mini/subagent.ts — mirrors utils/forkedAgent.ts:345-420 and tools/AgentTool/forkSubagent.ts:93-155
import { randomUUID } from 'crypto'
import type { ToolUseBlock } from './orchestration.js'
import type { Message } from './query.js'
import type { ToolUseContext } from './tool.js'

const FORK_PLACEHOLDER = 'Fork started — processing in background'
export function createSubagentContext(parent: ToolUseContext): ToolUseContext {
  const childAbort = new AbortController()
  parent.abortController.signal.addEventListener('abort', () => childAbort.abort(), { once: true })
  return {
    ...parent, agentId: randomUUID(), abortController: childAbort,
    readFileState: parent.readFileState.clone(), // Isolated staleness snapshot
    setAppState: () => {},                       // Block child mutations to parent UI store
    // Keep task registration root-wired so async subagent tasks are tracked and killed on shutdown
    setAppStateForTasks: parent.setAppStateForTasks ?? parent.setAppState,
    renderedSystemPrompt: parent.renderedSystemPrompt, // Frozen parent bytes for cache-sharing forks
  }
}
export function buildForkedMessages(history: Message[], parentAssistant: Message, directive: string): Message[] {
  const placeholders = parentAssistant.content
    .filter((b): b is ToolUseBlock => b.type === 'tool_use')
    .map(b => ({ type: 'tool_result' as const, tool_use_id: b.id, content: FORK_PLACEHOLDER }))
  return [...history, parentAssistant, { uuid: randomUUID(), role: 'user', content: [...placeholders, { type: 'text', text: directive }] }]
}
```

**Production invariants preserved:** Root-wired `setAppStateForTasks` ([utils/forkedAgent.ts:410-417](../../utils/forkedAgent.ts#L410-L417)) and byte-identical fork prefixes via frozen `renderedSystemPrompt` + `FORK_PLACEHOLDER` ([tools/AgentTool/AgentTool.tsx:496-497](../../tools/AgentTool/AgentTool.tsx#L496-L497), [tools/AgentTool/forkSubagent.ts:93-155](../../tools/AgentTool/forkSubagent.ts#L93-L155)).

## 7. Layer 8: Session Envelope, `parentUuid` Transcript, and Shutdown (`engine.ts`)

`query()` runs one turn; `QueryEngine` owns multi-turn state, appends crash-safe JSONL whose `parentUuid` chain survives compaction boundaries, and coordinates async teardown via a cycle-free leaf registry ([Chapter 08](../chapters/08-session-envelope-query-engine-and-transcripts.md), [Chapter 22](../chapters/22-cold-start-mastery-cli-init-main.md)).

```ts
// mini/engine.ts — mirrors QueryEngine.ts:184-230, utils/sessionStorage.ts:1001-1069, cleanupRegistry.ts:7-25
import { randomUUID } from 'crypto'
import { appendFile } from 'fs/promises'
import { FileStateCache } from './fileStateCache.js'
import type { ToolRunResult, ToolUseBlock } from './orchestration.js'
import { query, type Message, type ModelAdapter, type QueryEvent, type Terminal } from './query.js'
import type { Store } from './store.js'
import type { AppState, Tool, ToolUseContext } from './tool.js'

const cleanupFns = new Set<() => Promise<void>>()
export const registerCleanup = (fn: () => Promise<void>): (() => void) => (cleanupFns.add(fn), () => cleanupFns.delete(fn))
export const runCleanupFunctions = async (): Promise<void> => void (await Promise.all(Array.from(cleanupFns).map(fn => fn())))

export class QueryEngine {
  private mutableMessages: Message[] = []
  private readFileState = new FileStateCache()
  private lastUuid: string | null = null
  constructor(private config: {
    sessionId: string; transcriptPath: string; systemPrompt: string[]; tools: Tool[]
    store: Store<AppState>; callModel: ModelAdapter; summarize: (msgs: Message[]) => Promise<string>
    executeOne: (b: ToolUseBlock, c: ToolUseContext) => AsyncGenerator<ToolRunResult, void>
  }) {}
  private async appendTranscript(msg: Message): Promise<void> {
    const isBoundary = msg.subtype === 'compact_boundary'
    // parentUuid MUST serialize first so fast tail scanners match {"parentUuid": at offset 0
    const record = {
      parentUuid: isBoundary ? null : this.lastUuid,
      logicalParentUuid: isBoundary ? this.lastUuid : undefined,
      ...msg,
      sessionId: this.config.sessionId, // Re-stamped after spread so forked rows keep current sessionId
    }
    await appendFile(this.config.transcriptPath, JSON.stringify(record) + '\n', 'utf8')
    this.lastUuid = msg.uuid
  }
  async *submitMessage(prompt: string, signal?: AbortSignal): AsyncGenerator<QueryEvent, Terminal> {
    const abortController = new AbortController()
    signal?.addEventListener('abort', () => abortController.abort(), { once: true })
    const userMsg: Message = { uuid: randomUUID(), role: 'user', content: [{ type: 'text', text: prompt }] }
    this.mutableMessages.push(userMsg); await this.appendTranscript(userMsg)
    const ctx: ToolUseContext = {
      tools: this.config.tools, readFileState: this.readFileState, abortController,
      getAppState: this.config.store.getState, setAppState: this.config.store.setState, setAppStateForTasks: this.config.store.setState,
    }
    const gen = query({
      messages: this.mutableMessages, systemPrompt: this.config.systemPrompt, toolUseContext: ctx,
      callModel: this.config.callModel, executeOne: this.config.executeOne, summarize: this.config.summarize,
    })
    while (true) {
      const step = await gen.next()
      if (step.done) return step.value
      if (step.value.type === 'message') { this.mutableMessages.push(step.value.message); await this.appendTranscript(step.value.message) }
      yield step.value
    }
  }
}
```

**Production invariants preserved:** `parentUuid` first + `logicalParentUuid` on `compact_boundary` + post-spread `sessionId` re-stamping ([utils/sessionStorage.ts:1039-1064,3244-3310](../../utils/sessionStorage.ts#L1039-L1064)); cycle-free `registerCleanup()` leaf module ([utils/cleanupRegistry.ts:1-25](../../utils/cleanupRegistry.ts#L1-L25)).

## Pattern-to-Production Crosswalk

| Blueprint Module | Load-Bearing Pattern / Invariant | Production Claude Code Source | Chapter |
| --- | --- | --- | --- |
| `mini/store.ts` | 25-line reactive store with `Object.is` bailout | [state/store.ts](../../state/store.ts) | [Ch 01](../chapters/01-atoms-types-stores-and-primitives.md) |
| `mini/fileStateCache.ts` | Normalized paths, byte-capped LRU, `mtime` + `isPartialView` | [utils/fileStateCache.ts](../../utils/fileStateCache.ts) | [Ch 01](../chapters/01-atoms-types-stores-and-primitives.md), [Ch 12](../chapters/12-shell-execution-sandboxing-and-workspace-tools.md) |
| `mini/generators.ts` | Bounded `Promise.race` async-generator multiplexer `all()` | [utils/generators.ts](../../utils/generators.ts) | [Ch 01](../chapters/01-atoms-types-stores-and-primitives.md), [Ch 06](../chapters/06-executing-tools.md) |
| `mini/tool.ts` | Fail-closed `buildTool()` + two-partition `assembleToolPool()` | [Tool.ts](../../Tool.ts), [tools.ts](../../tools.ts) | [Ch 02](../chapters/02-the-tool-contract.md) |
| `mini/prompt.ts` | `SYSTEM_PROMPT_DYNAMIC_BOUNDARY` + `DANGEROUS_uncached...` | [constants/prompts.ts](../../constants/prompts.ts), [constants/systemPromptSections.ts](../../constants/systemPromptSections.ts), [utils/api.ts](../../utils/api.ts) | [Ch 04](../chapters/04-prompt-engineering-and-cache-boundaries.md) |
| `mini/orchestration.ts` | Read-batch concurrency + deterministic `contextModifier` replay | [services/tools/toolOrchestration.ts](../../services/tools/toolOrchestration.ts) | [Ch 06](../chapters/06-executing-tools.md) |
| `mini/query.ts` | `AsyncGenerator` turn loop, `toolUseBlocks` exit, withheld recovery | [query.ts](../../query.ts), [query/deps.ts](../../query/deps.ts), [query/config.ts](../../query/config.ts) | [Ch 05](../chapters/05-talking-to-the-model.md), [Ch 07](../chapters/07-the-heartbeat-query-loop.md) |
| `mini/compact.ts` | `'wx'` spill-to-disk (`Infinity` opt-out) + 3x circuit breaker | [utils/toolResultStorage.ts](../../utils/toolResultStorage.ts), [services/compact/autoCompact.ts](../../services/compact/autoCompact.ts), [services/compact/compact.ts](../../services/compact/compact.ts) | [Ch 06](../chapters/06-executing-tools.md), [Ch 09](../chapters/09-five-layer-compaction-pipeline.md) |
| `mini/permissions.ts` | Deny/ask/safety checks evaluated strictly before `bypassPermissions` | [utils/permissions/permissions.ts](../../utils/permissions/permissions.ts) | [Ch 11](../chapters/11-the-permission-engine.md) |
| `mini/hooks.ts` | `PreToolUse` `allow` re-checked against deny/ask rules | [services/tools/toolHooks.ts](../../services/tools/toolHooks.ts), [utils/hooks.ts](../../utils/hooks.ts) | [Ch 13](../chapters/13-the-hook-system.md) |
| `mini/subagent.ts` | Isolated `readFileState`, root `setAppStateForTasks`, frozen prompt | [utils/forkedAgent.ts](../../utils/forkedAgent.ts), [tools/AgentTool/forkSubagent.ts](../../tools/AgentTool/forkSubagent.ts), [tools/AgentTool/runAgent.ts](../../tools/AgentTool/runAgent.ts) | [Ch 18](../chapters/18-subagents-context-forking-and-worktrees.md) |
| `mini/engine.ts` | Session `QueryEngine`, `parentUuid` JSONL, `registerCleanup()` | [QueryEngine.ts](../../QueryEngine.ts), [utils/sessionStorage.ts](../../utils/sessionStorage.ts), [utils/cleanupRegistry.ts](../../utils/cleanupRegistry.ts) | [Ch 08](../chapters/08-session-envelope-query-engine-and-transcripts.md), [Ch 22](../chapters/22-cold-start-mastery-cli-init-main.md) |

## Extension Roadmap: Growing Without Rewriting `query()`

Every seam in this ~440-line core aligns with Claude Code's layer boundaries, allowing production subsystems to snap on without editing `mini/query.ts`:

```mermaid
flowchart LR
  MCP["MCP + Deferred ToolSearch (Ch 15)"] -->|"appends to 2nd sort partition"| ToolPool["mini/tool.ts: assembleToolPool()"]
  Sandbox["OS Sandbox + Shell AST (Ch 12)"] -->|"implements checkPermissions / isConcurrencySafe"| ToolPool
  ToolPool --> Core["mini/query.ts + mini/engine.ts (unchanged core)"]
  Core -->|"AsyncGenerator events + store.subscribe"| InkUI["ink/ Terminal React REPL (Ch 20-21)"]
  Core -->|"NDJSON / WebSocket framing + remote canUseTool"| Bridge["Headless SDK & Remote Bridge (Ch 23-24)"]
```

1. **MCP, Deferred Tool Search, Skills, and LSP ([Ch 15](../chapters/15-model-context-protocol-mcp.md), [Ch 16](../chapters/16-skills-plugins-output-styles-and-lsp.md)):** Wrap remote MCP tools ([services/mcp/client.ts](../../services/mcp/client.ts)) as `Tool` objects in `assembleToolPool()`'s second partition so built-in cache keys stay frozen; mark cold schemas `shouldDefer: true` and resolve on demand via [tools/ToolSearchTool/ToolSearchTool.ts](../../tools/ToolSearchTool/ToolSearchTool.ts) and [utils/toolSearch.ts](../../utils/toolSearch.ts).
2. **OS Sandboxing, Shell AST Inspection, Memory, and Enterprise Policy ([Ch 10](../chapters/10-memory-systems-claudemd-auto-memory-and-dream.md), [Ch 12](../chapters/12-shell-execution-sandboxing-and-workspace-tools.md), [Ch 14](../chapters/14-configuration-settings-and-enterprise-policy.md)):** Plug read-only shell AST analysis into `BashTool.isConcurrencySafe(input)` and OS isolation ([utils/sandbox/sandbox-adapter.ts](../../utils/sandbox/sandbox-adapter.ts), [tools/BashTool/BashTool.tsx](../../tools/BashTool/BashTool.tsx)) into `call()` and `checkPermissions()`, while populating `permissionContext` from enterprise settings and injecting `CLAUDE.md`/memories below `SYSTEM_PROMPT_DYNAMIC_BOUNDARY`.
3. **Streaming Tool Execution, Background Tasks, and Swarms ([Ch 06](../chapters/06-executing-tools.md), [Ch 17](../chapters/17-background-task-runtime.md), [Ch 19](../chapters/19-agent-teams-swarms-and-coordinator-mode.md)):** Swap `runTools()` for a streaming executor ([services/tools/StreamingToolExecutor.ts](../../services/tools/StreamingToolExecutor.ts)) that starts read-only tools mid-stream, and register background shells or teammate loops through `setAppStateForTasks`.
4. **Terminal UI (`ink/`), Headless SDK, and Remote Bridge ([Ch 20](../chapters/20-inside-ink-terminal-react-renderer.md)–[Ch 24](../chapters/24-across-the-wire-remote-sessions-bridge-and-direct-connect.md)):** Bind a terminal React renderer ([ink/ink.tsx](../../ink/ink.tsx), [ink/screen.ts](../../ink/screen.ts), [screens/REPL.tsx](../../screens/REPL.tsx)) directly to `store.subscribe()` and `QueryEngine.submitMessage()`. For headless SDK or remote control ([cli/structuredIO.ts](../../cli/structuredIO.ts), [cli/print.ts](../../cli/print.ts), [bridge/replBridge.ts](../../bridge/replBridge.ts), [bridge/remoteBridgeCore.ts](../../bridge/remoteBridgeCore.ts)), frame the identical `QueryEvent` stream over NDJSON/WebSockets and route `promptUser` over the wire.

## Reading Exercises & Code Checkpoints

1. **Trace the two-partition cache invariant:** Run `rg -n "assembleToolPool|SYSTEM_PROMPT_DYNAMIC_BOUNDARY" tools.ts constants/prompts.ts utils/api.ts` and verify how both the tool list and system prompt lock global cache prefixes *before* session-specific entries.
2. **Verify bypass-immune permission ordering:** Inspect [utils/permissions/permissions.ts:1169-1281](../../utils/permissions/permissions.ts#L1169-L1281) alongside [services/tools/toolHooks.ts:347-406](../../services/tools/toolHooks.ts#L347-L406) to confirm which rule checks still run under `mode === 'bypassPermissions'` or a `PreToolUse` `allow` decision.
3. **Audit subagent task wiring:** Run `rg -n "setAppStateForTasks" utils/forkedAgent.ts Tool.ts` and trace why stubbing `setAppState` while forwarding `setAppStateForTasks` prevents `PPID=1` orphaned child processes during shutdown.
4. **Compare toy vs. production turn transitions:** Run `rg -n "transition: \{" query.ts` to catalog every `Continue` transition Claude Code adds atop our two-variant loop (`next_turn` and `max_output_tokens_recovery`), including `reactive_compact_retry`, `max_output_tokens_escalate`, and stop-hook continuations.


---

<!-- GLOSSARY.md — https://reverseengineeringclaudecode.com/glossary -->

# Codebase Glossary

A living reference of the domain vocabulary, core types, and internal conventions encountered while reverse-engineering Claude Code. Terms are added and refined as chapters are drafted.

---

## Core Architectural Terms

### `AppState` & `AppStateStore`
The central immutable reactive state tree for an active session (`state/AppStateStore.ts`, `state/AppState.tsx`), backed by a 34-line custom store (`state/store.ts`) and consumed in React components via `useSyncExternalStore`. Holds UI/session state such as `settings`, `mainLoopModel`, `toolPermissionContext`, `tasks`, `mcp`, `plugins`, and bridge status. Distinct from `bootstrap/state.ts`.

### `autoDream`
The cross-session memory consolidation agent (`services/autoDream/autoDream.ts`, `services/autoDream/consolidationLock.ts`, `services/autoDream/config.ts`) triggered on stop hooks behind a cheapest-first three-gate funnel: a 24-hour time gate (`minHours`, one `stat` on `.consolidate-lock`), a 5-session scan (`minSessions`) throttled by a 10-minute `SESSION_SCAN_INTERVAL_MS` cooldown, and a cross-process PID+mtime lock with a 1-hour `HOLDER_STALE_MS` guard and `rollbackConsolidationLock()`. Controlled by `settings.autoDreamEnabled` over GrowthBook `tengu_onyx_plover` (`isAutoDreamEnabled()`), it registers a `dream` background task (`tasks/DreamTask/DreamTask.ts`) and runs a 4-phase consolidation prompt (`services/autoDream/consolidationPrompt.ts`) via `runForkedAgent()`.

### `bootstrap/state.ts` (Bootstrap State / Leaf Singleton)
Process-wide mutable singleton state initialized at startup (`originalCwd`, `projectRoot`, `sessionId`, `totalCostUSD`, `registeredHooks`, `invokedSkills`, `cachedClaudeMdContent`). Intentionally kept as a **leaf of the import DAG** (guarded by the `custom-rules/bootstrap-isolation` lint rule) so low-level utilities can read process identity and metrics without pulling in React or creating circular dependencies.

### `buildEffectiveSystemPrompt()` & `splitSysPromptPrefix()`
The two-stage system-prompt assembly and wire-splitting pipeline (`utils/systemPromptType.ts`, `utils/systemPrompt.ts`, `utils/api.ts`). `buildEffectiveSystemPrompt()` resolves a five-tier runtime precedence cascade—`overrideSystemPrompt` (which drops `appendSystemPrompt`) → `--agent` (`mainThreadAgentDefinition`, beating Coordinator mode via `!mainThreadAgentDefinition`) → Coordinator mode → `customSystemPrompt` → `defaultSystemPrompt`, with `appendSystemPrompt` added on non-override tiers—into the zero-dependency branded `SystemPrompt` leaf type (`asSystemPrompt()`). `splitSysPromptPrefix()` then separates `x-anthropic-billing-header`, `CLI_SYSPROMPT_PREFIXES`, `scope: 'global'` static instructions, and uncached dynamic blocks on the wire, falling back to `'org'` scope when `shouldUseGlobalCacheScope()` (`utils/betas.ts`) is false or when `services/api/claude.ts` passes `skipGlobalCacheForSystemPrompt` as `true` because a non-deferred MCP tool is present.

### `buildQueryConfig()` & `QueryDeps`
The two dependency-isolation seams at `query()` entry (`query/config.ts`, `query/deps.ts`, `query.ts`), producing `QueryConfig` and `QueryDeps`:
- **`QueryConfig` (`buildQueryConfig()` in `query/config.ts`)**: Snapshots `sessionId` and four runtime env/Statsig gates (`streamingToolExecution` via `'tengu_streaming_tool_execution2'`, `emitToolUseSummaries` via `CLAUDE_CODE_EMIT_TOOL_USE_SUMMARIES`, `isAnt`, and inlined `fastModeEnabled` respecting `CLAUDE_CODE_DISABLE_FAST_MODE`) once per turn while intentionally excluding `feature()` flags so Bun dead-code elimination stays intact.
- **`QueryDeps` (`productionDeps()` in `query/deps.ts`)**: Injects four narrow I/O seams (`callModel`, `microcompact`, `autocompact`, `uuid`) typed via `typeof fn` (plus `uuid: () => string`) so callers and harnesses can swap dependencies without module-level mocking.

### `buildTool()` & `TOOL_DEFAULTS`
The factory function in `Tool.ts` that wraps a partial `ToolDef` into a complete `Tool`, supplying **fail-closed defaults** (`isConcurrencySafe: false`, `isReadOnly: false`, `isDestructive: false`, `isEnabled: true`) while preserving exact literal types via the `BuiltTool<D>` mapped type.

### `CLAUDE.md` & `loadedNestedMemoryPaths`
Hierarchical instruction files loaded by `getMemoryFiles()` in `utils/claudemd.ts` in reverse priority—Managed → User → root-to-CWD Project/Local → opt-in `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD` `--add-dir`—with `.claude/rules/` YAML `paths:` frontmatter and recursive `@include` expansion capped at `MAX_INCLUDE_DEPTH = 5`. At conversation start, `getUserContext()` in `context.ts` formats them via `getClaudeMds()` and caches the result via `setCachedClaudeMdContent()` / `cachedClaudeMdContent` in `bootstrap/state.ts` as a cycle-breaker seam for downstream permission classifiers. Subdirectory `CLAUDE.md` files discovered lazily on file reads (`utils/attachments.ts`, `memoryFilesToAttachments()`) are deduplicated in the non-evicting `loadedNestedMemoryPaths` `Set` on `ToolUseContext` (`Tool.ts`) rather than the 100-entry LRU `FileStateCache`, and cached with `isPartialView: true` whenever frontmatter or HTML comments are stripped.

### `Command` (`prompt` | `local` | `local-jsx`)
The discriminated union in `types/command.ts` unifying all slash commands, skills, plugin commands, and MCP prompts:
- **`prompt`**: Expands into `ContentBlockParam[]` and sends them to the model (either `inline` or `fork`ed into a subagent).
- **`local`**: Executes locally without hitting the LLM and returns `{ type: 'text' | 'compact' | 'skip' }`.
- **`local-jsx`**: Lazy-loads and mounts an interactive Ink/React component inside the terminal UI.

### `ContentReplacementState` & Tool Result Budget
Per-conversation tracking (`utils/toolResultStorage.ts`, carried on `ToolUseContext`) that enforces an aggregate size cap on tool results in a message turn and spills oversized outputs to disk wrapped in `<persisted-output>` tags. Tools like `FileReadTool` set `maxResultSizeChars: Infinity` to opt out and avoid a circular Read→file→Read loop.

### `DANGEROUS_uncachedSystemPromptSection()` & `systemPromptSection()`
The post-boundary dynamic prompt registry (`constants/systemPromptSections.ts`) that memoizes dynamic prompt sections per session by default (`systemPromptSection()`, including `null` results in `bootstrap/state.ts`) so mid-session state churn does not bust org-level prompt caches. Opting out requires `DANGEROUS_uncachedSystemPromptSection(name, compute, _reason)`, whose unused `_reason` argument enforces code-review friction (currently used only for `'mcp_instructions'` in `constants/prompts.ts`). `clearSystemPromptSections()` resets the section cache together with `clearBetaHeaderLatches()` (`bootstrap/state.ts`: `afkModeHeaderLatched`, `fastModeHeaderLatched`, `cacheEditingHeaderLatched`, `thinkingClearLatched`) on `/clear`, `/compact`, and worktree switches.

### `FileHistoryState` & `/rewind`
Three-phase async file checkpointing (`utils/fileHistory.ts`: `fileHistoryMakeSnapshot()`, `fileHistoryTrackEdit()`, `fileHistoryRewind()`) that pairs disk rollback with append-only conversation rewind. Stores path-hashed `{sha256(filePath).slice(0,16)}@v{version}` backups under `{configDir}/file-history/{sessionId}/` (capped at `MAX_SNAPSHOTS = 100`, hard-linked across forks by `copyFileHistoryForResume()`), replays dual-keyed `isSnapshotUpdate` entries along the active `parentUuid` branch, and defaults on interactively (`CLAUDE_CODE_DISABLE_FILE_CHECKPOINTING` disables) vs. off in SDK mode (`CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING` enables).

### `FileStateCache`
A path-normalizing, byte-size-bounded `LRUCache<string, FileState>` (`utils/fileStateCache.ts`) carried on `ToolUseContext.readFileState`. Tracks every file read in a conversation (content, mtime timestamp, offset/limit, and `isPartialView`) so edit tools can verify a file was read and hasn't changed on disk before modifying it. `FileReadTool` (`tools/FileReadTool/FileReadTool.ts`) stores numeric `offset` (default `1`) and returns `FILE_UNCHANGED_STUB` when `(offset, limit)` and floored `mtimeMs` match (unless `tengu_read_dedup_killswitch` is set), while `FileEditTool` (`tools/FileEditTool/FileEditTool.ts`) and `FileWriteTool` (`tools/FileWriteTool/FileWriteTool.ts`) enforce a two-phase TOCTOU guard (`FILE_UNEXPECTEDLY_MODIFIED_ERROR`) and write `offset: undefined` so subsequent reads bypass dedup.

### `lazySchema()`
An 8-line memoizing thunk (`utils/lazySchema.ts`) used across tools and permissions to defer Zod schema construction from module import time to first access, avoiding startup CPU/memory spikes across 60+ tools.

### `memdir/` (Auto-Memory) & Relevant Memory Prefetch
Persistent cross-session memory stored outside the repository (`memdir/memdir.ts`, `memdir/memoryTypes.ts`, `memdir/paths.ts`), shared across git worktrees via `findCanonicalGitRoot()`, indexed by `MEMORY.md` (dual-capped at `MAX_ENTRYPOINT_LINES = 200` and `MAX_ENTRYPOINT_BYTES = 25_000`), and structured into a 4-type taxonomy (`user`, `feedback`, `project`, `reference`). Two orthogonal security boundaries guard auto-memory paths: `getAutoMemPathSetting()` (`memdir/paths.ts`) excludes `projectSettings` from `autoMemoryDirectory` resolution to defend against hostile repos, while `utils/permissions/filesystem.ts` gates the silent auto-memory write carve-out on `!hasAutoMemPathOverride() && isAutoMemPath()` (excluding `CLAUDE_COWORK_MEMORY_PATH_OVERRIDE`). Under GrowthBook `tengu_moth_copse`, static `MEMORY.md` injection swaps for zero-wait `using pendingMemoryPrefetch = startRelevantMemoryPrefetch(...)` (`query.ts`, `utils/attachments.ts`, `memdir/memoryScan.ts`, `memdir/findRelevantMemories.ts`), while `feature('EXTRACT_MEMORIES')` (`query/stopHooks.ts`) runs turn-end topic extraction (`services/extractMemories/extractMemories.ts`).

### `normalizeMessagesForAPI()` & `ensureToolResultPairing()`
The two-stage transcript-to-wire normalization boundary (`utils/messages.ts`, `services/api/claude.ts`):
- **Stage 1 (`normalizeMessagesForAPI()` in `utils/messages.ts`)**: Model-agnostic cleanup that drops `isVirtual`, `progress`, UI-only `system` subtypes (promoting `system/local_command`), and synthetic API errors; merges consecutive user turns and split assistant chunks; and runs four strictly ordered assistant cleanup passes (`filterOrphanedThinkingOnlyMessages` → `filterTrailingThinkingFromLastAssistant` → `filterWhitespaceOnlyAssistantMessages` → `ensureNonEmptyAssistantContent`).
- **Stage 2 (`services/api/claude.ts`)**: Runs bidirectional `ensureToolResultPairing()` (`utils/messages.ts`, injecting `is_error: true` `SYNTHETIC_TOOL_RESULT_PLACEHOLDER` blocks or throwing under `getStrictToolResultPairing()` in `bootstrap/state.ts`), then emits wire `MessageParam[]` via `addCacheBreakpoints()` (one message-level `cache_control` marker, shifted to `length - 2` under `skipCacheWrite`), `userMessageToMessageParam()`, and `assistantMessageToMessageParam()`.

### `parentUuid`, `logicalParentUuid` & `preservedSegment` (Transcript DAG)
The append-only JSONL graph linking conversation entries (`utils/sessionStorage.ts`, `utils/sessionStoragePortable.ts`, `utils/sessionRestore.ts`) without rewriting transcript files on `/rewind`, `--fork-session` (which keeps the fresh `sessionId` and re-stamps entries without remapping UUIDs), or compaction. `compact_boundary` resets `parentUuid: null`, preserves `logicalParentUuid`, and optionally carries `preservedSegment` (`{ headUuid, anchorUuid, tailUuid }`, relinked on load by `applyPreservedSegmentRelinks()`). Scale and crash resilience pair `SKIP_PRECOMPACT_THRESHOLD` (`5 MiB`) + `walkChainBeforeParse()` (50%-dead-bytes pre-filter) and `MAX_TRANSCRIPT_READ_BYTES` (`50 MiB`) with `parseJSONL()` (`utils/json.ts`) and `deserializeMessagesWithInterruptDetection()` (`utils/conversationRecovery.ts`).

### `parseForSecurity()` & `PARSE_ABORTED` (Fail-Closed Shell AST)
The fail-closed shell security gate (`utils/bash/ast.ts`, `utils/bash/bashParser.ts`, `utils/bash/parser.ts`) powered by a pure-TypeScript tree-sitter-compatible parser (`feature('TREE_SITTER_BASH')`; shadow rollout via `feature('TREE_SITTER_BASH_SHADOW')` and GrowthBook `tengu_birch_trellis` in `tools/BashTool/bashPermissions.ts`). Returns `'simple' | 'too-complex' | 'parse-unavailable'`; when adversarial input trips `PARSE_TIMEOUT_MS` (`50` ms) or `MAX_NODES` (`50_000`), `parseCommandRaw()` returns `PARSE_ABORTED` so `parseForSecurity()` fails closed as `'too-complex'` instead of degrading to legacy checks. `PowerShellTool` mirrors this with native `pwsh` `.NET Language.Parser` parsing (`utils/powershell/parser.ts`, `parsePowerShellCommand()`) and `isProvablySafeStatement()` (`tools/PowerShellTool/readOnlyValidation.ts`).

### `PermissionMode` & `PermissionRuleSource`
The concentric permission contract (`types/permissions.ts`, `utils/permissions/PermissionMode.ts`) defining 5 external modes (`default`, `acceptEdits`, `plan`, `dontAsk`, `bypassPermissions`), `feature('TRANSCRIPT_CLASSIFIER')` `'auto'`, and internal fork-only `'bubble'`, paired with 8 ordered rule sources (`userSettings`, `projectSettings`, `localSettings`, `flagSettings`, `policySettings`, `cliArg`, `command`, `session`; managed lockdown via `allowManagedPermissionRulesOnly` in `utils/permissions/permissionsLoader.ts`). Evaluation splits into bypass-immune inner checks `1a`–`1g` (`hasPermissionsToUseToolInner()` in `utils/permissions/permissions.ts`, including `checkPathSafetyForAutoEdit()` in `utils/permissions/filesystem.ts` and hook mirror `checkRuleBasedPermissions()`), an outer mode wrapper (`hasPermissionsToUseTool()`), and interactive two-phase `createResolveOnce()` `claim()` locking (`hooks/useCanUseTool.tsx`, `hooks/toolPermission/PermissionContext.ts`).

### `query()` vs. `QueryEngine`
- **`query()` (`query.ts`)**: The inner multi-iteration **turn state machine** (`AsyncGenerator`). Runs compaction, streams the model API response, executes tool calls (concurrently or while streaming), handles error recovery (`max_output_tokens`, `prompt_too_long`), runs stop hooks, and yields stream/message events until returning a `Terminal` reason.
- **`QueryEngine` (`QueryEngine.ts`)**: The outer **conversation/session envelope** owning cross-turn state (`mutableMessages`, `readFileState`, `permissionDenials`, `totalUsage`, `abortController`, transcript recording) and adapting `query()` events into `SDKMessage` streams via `submitMessage()`.

### `resolveHookPermissionDecision()`
The hook-vs-rule permission arbiter (`services/tools/toolHooks.ts`) enforcing the `inc-4788` security invariant during `PreToolUse` execution. A hook returning `'allow'` skips interactive prompting only when `requiresUserInteraction()` / `requireCanUseTool` are satisfied and `checkRuleBasedPermissions()` (`utils/permissions/permissions.ts`) returns `null`, ensuring hooks can never bypass `settings.json` `deny`/`ask` rules or sensitive-path guards; `'ask'` forwards `forceDecision` to `canUseTool()`.

### `runForkedAgent()` & `CacheSafeParams`
The prompt-cache-sharing background subagent runner and five-field cache-prefix snapshot (`utils/forkedAgent.ts`: `systemPrompt`, `userContext`, `systemContext`, `toolUseContext` [carrying `tools`, `model`, and `thinkingConfig`], and `forkContextMessages`), saved at the end of every main-thread or SDK turn by `handleStopHooks()` (`query/stopHooks.ts` via `saveCacheSafeParams(createCacheSafeParams(...))`). Used by LLM compaction (`services/compact/compact.ts`), `SessionMemory`, `extractMemories`, `autoDream`, `/btw`, and prompt suggestions so forked turns hit the parent's warm prompt cache alongside a cloned `ContentReplacementState` (`cloneContentReplacementState()`), enforcing least privilege via scoped `CanUseToolFn` callbacks (`createCompactCanUseTool()`, `createMemoryFileCanUseTool()`, `createAutoMemCanUseTool()`) rather than mutating cached tool schemas.

### `runTools()` & `partitionToolCalls()`
The batch-mode tool execution scheduler (`services/tools/toolOrchestration.ts`) used when `StreamingToolExecutor` is disabled. `partitionToolCalls()` fails closed (`safeParse` failure or throwing `isConcurrencySafe()` → `false`) to coalesce contiguous read-only calls into concurrent batches bounded by `all()` (`utils/generators.ts`, `CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY`, default `10`) while isolating unsafe tools into singleton serial batches, buffering `contextModifier` callbacks (`Tool.ts`) during concurrent batches and replaying them in original block order.

### `SandboxManager` & `shouldUseSandbox()`
The OS-sandboxing adapter (`utils/sandbox/sandbox-adapter.ts`) and per-command gate (`tools/BashTool/shouldUseSandbox.ts`) wrapping the external npm package `@anthropic-ai/sandbox-runtime` (macOS Seatbelt / Linux & WSL2 `bubblewrap`+`socat`; external package internals live outside this checkout). Translates `Edit`, `Read`, and `WebFetch` permission rules into sandbox configs, duplicates rule parsers locally to break the `utils/permissions/permissions.ts` → `SandboxManager` → `tools/BashTool/bashPermissions.ts` import cycle, scrubs planted bare-git files via `bareGitRepoScrubPaths`/`scrubBareGitRepoFiles()`, and coordinates `sandbox.autoAllowBashIfSandboxed` while keeping `excludedCommands` a convenience fallback to permission prompts rather than a security bypass.

### `StreamingToolExecutor`
The streaming scheduler (`services/tools/StreamingToolExecutor.ts`) that begins executing `tool_use` blocks *as they arrive during an active LLM stream* rather than waiting for the full assistant turn to end. Runs concurrency-safe tools in parallel (yielding their results in completion order, while non-concurrency-safe tools act as strict ordering barriers in `getCompletedResults()`), serializes mutating tools, and isolates bash sibling cancellation via a child `siblingAbortController`.

### `SYSTEM_PROMPT_DYNAMIC_BOUNDARY`
A sentinel marker (`__SYSTEM_PROMPT_DYNAMIC_BOUNDARY__` in `constants/prompts.ts`) splitting the system prompt array into a static prefix eligible for global cross-org prompt caching (`scope: 'global'`) and a dynamic suffix containing user/session-specific data.

### `TaskStateBase` & `TaskType`
The unified background execution record (`Task.ts`, `tasks/types.ts`) covering 7 background task types: `local_bash` (`b*`), `local_agent` (`a*`), `remote_agent` (`r*`), `in_process_teammate` (`t*`), `local_workflow` (`w*`), `monitor_mcp` (`m*`), and `dream` (`d*`). Outputs stream to disk files tracked via `outputFile` and `outputOffset`.

### `ToolUseContext`
The capability bag (`Tool.ts`) threaded into every tool execution, hook, and query iteration. Carries read-only options (`tools`, `commands`, `mcpClients`, `mainLoopModel`), mutable session handles (`abortController`, `readFileState`, `getAppState`, `setAppState`, `setAppStateForTasks`), UI hooks (`setToolJSX`, `addNotification`), and cache/budget state (`renderedSystemPrompt`, `contentReplacementState`).

### Withheld Error Recovery
The turn-level suppression and four-stage recovery ladder in `query.ts`. During streaming, `queryLoop()` sets `withheld = true` on recoverable synthetic `isApiErrorMessage` responses to avoid premature SDK teardown—checking `isPromptTooLongMessage()` directly from `services/api/errors.ts` and delegating media-size withholding to `reactiveCompact?.isWithheldMediaSizeError()` on snapshot-absent `services/compact/reactiveCompact.js` (while `services/api/errors.ts` exports `isMediaSizeErrorMessage()` and populates `errorDetails`). It then attempts up to four recoveries: `collapse_drain_retry` under `feature('CONTEXT_COLLAPSE')` (`services/contextCollapse/index.js`, absent from this snapshot — observed at call sites), `reactive_compact_retry` under `feature('REACTIVE_COMPACT')` (`services/compact/reactiveCompact.js`, absent from this snapshot — observed at call sites), `max_output_tokens_escalate` under GrowthBook `'tengu_otk_slot_v1'` (`8,000` → `64,000` via `ESCALATED_MAX_TOKENS` in `utils/context.ts`), and up to `MAX_OUTPUT_TOKENS_RECOVERY_LIMIT` (`3`) `max_output_tokens_recovery` nudges. Unrecovered errors surface once and fire `executeStopFailureHooks()` before exiting via a `Terminal` transition (`Continue` and `Terminal` unions from `query/transitions.ts`, absent from this snapshot — observed at `query.ts` call sites).

### `withRetry()` & `FallbackTriggeredError`
The `AsyncGenerator<SystemAPIErrorMessage, T>` retry harness (`services/api/withRetry.ts`) wrapping model API calls run with SDK `maxRetries: 0` (`services/api/claude.ts`). Yields `SystemAPIErrorMessage` retry updates (and 30-second keep-alive heartbeats under `feature('UNATTENDED_RETRY')` + `CLAUDE_CODE_UNATTENDED_RETRY`), refreshes expired OAuth/Bedrock/Vertex credentials and stale sockets, sheds non-foreground 529s outside `FOREGROUND_529_RETRY_SOURCES`, and throws `FallbackTriggeredError` once cumulative `consecutive529Errors` reaches `MAX_529_RETRIES` (`3`) when `fallbackModel` is set for eligible primary models (`FALLBACK_FOR_ALL_PRIMARY_MODELS` or non-subscriber non-custom Opus), triggering a model switch in `query.ts`.

### `yoloClassifier` (Auto-Mode Classifier) & `DENIAL_LIMITS`
The `feature('TRANSCRIPT_CLASSIFIER')` auto-mode risk classifier (`utils/permissions/yoloClassifier.ts`, `classifyYoloAction()`) judging non-allowlisted mutations (`isAutoModeAllowlistedTool()` in `utils/permissions/classifierDecision.ts`) via two-stage XML (`<block>yes/no</block>`) or `classify_result` over a prompt-injection-hardened transcript (`buildTranscriptEntries()` strips `tool_result`s and assistant prose, while `buildClaudeMdMessage()` prepends `getCachedClaudeMdContent()` via `bootstrap/state.ts`; prompt `.txt` files under `utils/permissions/yolo-classifier-prompts/` are absent from this snapshot). Paired with reversible dangerous-rule stripping (`stripDangerousPermissionsForAutoMode()` in `utils/permissions/permissionSetup.ts`), fail-closed `tengu_iron_gate_closed` (`utils/permissions/permissions.ts`), and the immutable `DENIAL_LIMITS` (`maxConsecutive: 3`, `maxTotal: 20`) fallback circuit breaker (`utils/permissions/denialTracking.ts`, `shouldFallbackToPrompting()`).

---

## Hooks, Configuration, MCP & Extension Terms

- **`AsyncHookRegistry` / `asyncRewake`** (`utils/hooks/AsyncHookRegistry.ts`, `utils/hooks.ts`): Dual background-hook delivery layer—standard async hooks spill to `TaskOutput` and emit `async_hook_response` attachments via `checkForAsyncHookResponses()`, while `asyncRewake: true` retains in-memory buffers and enqueues a `task-notification` on exit code `2` to wake the model.
- **`hooksConfigSnapshot` & `SessionHooksState`** (`utils/hooks/hooksConfigSnapshot.ts`, `utils/hooks/sessionHooks.ts`): Startup-captured enterprise-filtered settings-hook snapshot (enforcing `disableAllHooks`, `allowManagedHooksOnly`, and `strictPluginOnlyCustomization`) paired with an ephemeral per-session/per-agent `Map` holding skill/subagent frontmatter hooks and non-serializable `FunctionHook` validators.
- **`ssrfGuardedLookup`** (`utils/hooks/ssrfGuard.ts`): Axios `lookup` hook validating all resolved IPv4/IPv6 addresses (including RFC 6598 CGNAT and hex IPv4-mapped IPv6) at connect time to prevent DNS-rebinding SSRF in HTTP hooks while allowing loopback (`127.0.0.0/8`, `::1`).
- **`SETTING_SOURCES` & `fanOut()`** (`utils/settings/constants.ts`, `utils/settings/settings.ts`, `utils/settings/changeDetector.ts`): The five-tier declarative settings cascade (`userSettings` → `projectSettings` → `localSettings` → `flagSettings` → `policySettings` above `pluginSettingsBase`, with first-source-wins `policySettings`) paired with single-producer cache invalidation in `changeDetector.ts` (`fanOut()` calls `resetSettingsCache()` once before notifying interactive and headless subscribers).
- **`wouldLoseAuthState` & `PolicyLimits` (`ESSENTIAL_TRAFFIC_DENY_ON_MISS`)** (`utils/config.ts`, `services/policyLimits/index.ts`): Write-time auth-loss protection for `~/.claude.json` (GH #3117) and org-level feature kill-switches (`/api/claude_code/policy_limits`) that fail open on misses except `allow_product_feedback` under essential-traffic-only (HIPAA) mode.
- **`strictPluginOnlyCustomization`** (`utils/settings/pluginOnlyPolicy.ts`, `utils/settings/types.ts`): Managed enterprise policy (`true` or subset of `['skills', 'agents', 'hooks', 'mcp']`) blocking user/project customizations outside `ADMIN_TRUSTED_SOURCES`.
- **`ClaudeAuthProvider` & Cross-App Access (XAA / SEP-990)** (`services/mcp/auth.ts`, `services/mcp/xaa.ts`): MCP `OAuthClientProvider` supporting RFC 9728/8414 discovery, CIMD (SEP-991), cross-process lockfile refresh, 403 step-up scope capture, and enterprise RFC 8693 + RFC 7523 silent token exchange (`CLAUDE_CODE_ENABLE_XAA=1`).
- **Deferred Tool Loading (`defer_loading` / `tool_reference` / `deferred_tools_delta`)** (`utils/toolSearch.ts`, `tools/ToolSearchTool/ToolSearchTool.ts`, `services/api/claude.ts`): Dynamic schema-loading protocol that omits deferred MCP and `shouldDefer: true` tool schemas until discovered via `ToolSearchTool` while appending deltas at the tail of conversation history to preserve prompt-cache prefixes.
- **MCP Elicitation (`ElicitRequestSchema` / `-32042`)** (`services/mcp/elicitationHandler.ts`, `services/mcp/client.ts`): Server-initiated form/URL consent flow intercepted by `Elicitation`/`ElicitationResult` hooks or queued in `AppState.elicitation.queue`, with two-phase URL waiting and `ElicitationComplete` retries.
- **Conditional Skill & `SAFE_SKILL_PROPERTIES`** (`skills/loadSkillsDir.ts`, `tools/SkillTool/SkillTool.ts`): Disk-loaded skills withheld in `conditionalSkills` until a matching file path is touched (`paths:` frontmatter), governed by a fail-closed allowlist of auto-executable `PromptCommand` keys.
- **Three-Layer Plugin Lifecycle** (`utils/plugins/reconciler.ts`, `utils/plugins/refresh.ts`): Separation of plugin state into settings intent (Layer 1), `~/.claude/plugins/` disk materialization (`reconcileMarketplaces()`, Layer 2), and live `AppState`/`STATE.registeredHooks` activation (`refreshActivePlugins()` via `/reload-plugins`, Layer 3).
- **Output Style & `LSPDiagnosticRegistry`** (`constants/outputStyles.ts`, `services/lsp/LSPDiagnosticRegistry.ts`, `services/lsp/passiveFeedback.ts`): Persona framing injected above/below `SYSTEM_PROMPT_DYNAMIC_BOUNDARY`, and the 500-file `LRUCache` async diagnostic buffer delivering deduplicated, severity-sorted compiler feedback as turn attachments.

---

## Concurrency, Subagents, Swarms & Terminal Renderer Terms

- **`DiskTaskOutput` / `TaskOutput` & `<task-notification>`** (`utils/task/diskOutput.ts`, `utils/task/TaskOutput.ts`, `utils/task/framework.ts`): Symlink-hardened (`O_NOFOLLOW`/`O_EXCL`), 5 GB-capped disk output layer (file-fd mode for bash, 8 MB spill-to-disk pipe mode for hooks) paired with XML `<task-notification>` envelopes enqueued into `messageQueueManager.ts` on completion or prompt stall.
- **`CronScheduler`** (`utils/cronScheduler.ts`, `utils/cronTasks.ts`, `utils/cronTasksLock.ts`): Local 5-field cron engine combining `O_EXCL` multi-session lease locking (`.claude/scheduled_tasks.lock`), UUID-hashed anti-herd jitter tuned via `tengu_kairos_cron_config`, and 7-day auto-expiry.
- **`createSubagentContext()` & `FORK_AGENT`** (`utils/forkedAgent.ts`, `tools/AgentTool/forkSubagent.ts`): Subagent context factory cloning `readFileState`/`contentReplacementState`, stubbing `setAppState`, and keeping `setAppStateForTasks` root-wired; `FORK_AGENT` (`feature('FORK_SUBAGENT')`) freezes `renderedSystemPrompt`, matches tool pools, and emits identical `FORK_PLACEHOLDER_RESULT` blocks so parallel children achieve near-100% prompt-cache hits.
- **`runWithCwdOverride()` & `.meta.json` Sidecar** (`utils/cwd.ts`, `utils/sessionStorage.ts`, `tools/AgentTool/resumeAgent.ts`): `AsyncLocalStorage`-backed working-directory scope isolating concurrent worktree subagents without mutating `process.cwd()`, paired with per-subagent JSONL + `.meta.json` sidecars enabling `resumeAgentBackground()`.
- **`TeammateContext`, Teammate Mailbox & Leader Permission Bridge** (`utils/teammateContext.ts`, `utils/teammateMailbox.ts`, `utils/swarm/leaderPermissionBridge.ts`): `AsyncLocalStorage` teammate identity, file-locked JSON array inboxes (`~/.claude/teams/{team}/inboxes/{agent}.json`) multiplexing DMs and `isStructuredProtocolMessage()` control payloads, and the module registry bridging in-process worker `ToolUseConfirm` prompts to the leader's terminal UI.
- **Packed `Screen` Buffer & Pure-TS Yoga** (`ink/screen.ts`, `native-ts/yoga-layout/index.ts`, `ink/layout/yoga.ts`): Dual-view 8-byte-per-cell `Int32Array`/`BigInt64Array` terminal framebuffer paired with a synchronous 2,578-line pure-TypeScript Yoga flexbox engine with generation-stamped layout caching.
- **`DECSTBM` Scroll Fast Path, DA1 Sentinel (`TerminalQuerier`) & Declared Native Cursor** (`ink/render-node-to-output.ts`, `ink/log-update.ts`, `ink/terminal-querier.ts`, `ink/hooks/use-declared-cursor.ts`): Hardware-accelerated scroll regions gated on `DEC 2026` synchronized output, timeout-free PTY capability probing terminated by a VT100 Primary Device Attributes (`CSI c`) barrier, and post-diff cursor parking for CJK IME and screen readers.

---

## REPL, Startup, SDK & Remote Control Terms

- **`QueryGuard`, `ChordInterceptor` & `SliceAnchor`** (`utils/QueryGuard.ts`, `keybindings/KeybindingProviderSetup.tsx`, `components/Messages.tsx`): Generation-numbered 3-state turn guard (`idle` → `dispatching` → `running`), top-level chord/unbind interceptor mounted above child inputs, and monotonic `{ uuid, idx }` message-window anchor capping non-virtualized REPL rendering without scrollback resets.
- **`getFocusedInputDialog()` & `VimState`** (`screens/REPL.tsx`, `vim/types.ts`, `vim/transitions.ts`, `hooks/useVimInput.ts`): Single priority arbiter across ~19 competing interactive overlays, paired with a pure-functional Vim state machine (`INSERT` + 11 `NORMAL` sub-states) bridged into `BaseTextInput` via synchronous refs.
- **Early Input Capture, Pre-Import Prefetch Wave & API Preconnect** (`utils/earlyInput.ts`, `main.tsx`, `entrypoints/init.ts`, `utils/apiPreconnect.ts`): Cold-start optimizations overlapping TTY raw-mode buffering, MDM/keychain subprocesses, and fire-and-forget TCP+TLS `HEAD` warmup (strictly after `applyExtraCACertsFromConfig()` and `configureGlobalAgents()`) with module import and action-handler boot.
- **`registerCleanup()` & Startup Profiler** (`utils/cleanupRegistry.ts`, `utils/gracefulShutdown.ts`, `utils/startupProfiler.ts`): Zero-dependency teardown callback `Set` drained under a 2-second shutdown budget, paired with sampled `perf_hooks` checkpoints (`tengu_startup_perf`, `CLAUDE_CODE_PROFILE_STARTUP=1`).
- **`StructuredIO`, `installStreamJsonStdoutGuard` & `ndjsonSafeStringify`** (`cli/structuredIO.ts`, `utils/streamJsonStdoutGuard.ts`, `cli/ndjsonSafeStringify.ts`, `cli/print.ts`): Bidirectional NDJSON multiplexer for headless SDK control RPCs, runtime `process.stdout.write` guard diverting non-JSON lines to `stderr`, ECMA-262 `U+2028`/`U+2029` escaper, and `heldBackResult` turn-completion deferral for background tasks.
- **`startMCPServer` (`claude/tengu`)** (`entrypoints/mcp.ts`): Inverted MCP stdio server mode (`claude mcp serve`) exposing `getTools()` directly over `StdioServerTransport` without `QueryEngine` or `runToolUse()`.
- **Env-Less Bridge, `worker_epoch`, `FlushGate` & Race 4** (`bridge/remoteBridgeCore.ts`, `cli/transports/ccrClient.ts`, `bridge/flushGate.ts`, `bridge/bridgePermissionCallbacks.ts`): Direct REPL Remote Control via `POST /v1/code/sessions/{id}/bridge` (`tengu_bridge_repl_v2`), monotonic `409 Conflict` fencing tokens, history-vs-live ordering gate, and remote `claude.ai`/mobile permission approval racing atomically via `claim()`.
- **Upstream Proxy Relay (`upstreamproxy/`)** (`upstreamproxy/upstreamproxy.ts`, `upstreamproxy/relay.ts`): Fail-open container-side local HTTP `CONNECT`-over-WebSocket relay (`prctl(PR_SET_DUMPABLE, 0)`, post-bind token unlink) tunneling subprocess TLS through a credential-injecting MITM proxy without leaking raw secrets to child processes.

---

## Compaction & Context Terms

- **Tool Result Budget (`applyToolResultBudget`)**: Stage 1 in `query.ts`—replaces oversized tool outputs with `<persisted-output>` file references.
- **History Snip (`HISTORY_SNIP`)**: Feature-gated Stage 2 in `query.ts` that snips old history segments before microcompaction, subtracting `snipTokensFreed` before threshold checks (`services/compact/snipCompact.js` and `services/compact/snipProjection.js` are absent from this snapshot — observed via call sites only).
- **Microcompact (`services/compact/microCompact.ts`)**: Stage 3 lightweight pass clearing stale tool results from compactable tools (`Read`, `Bash`, `PowerShell`, `Grep`, `Glob`, `WebSearch`, `WebFetch`, `Edit`, `Write`) via cold-cache time-based clearing (`tengu_slate_heron` in `services/compact/timeBasedMCConfig.ts`, default 60 min idle) or optionally warm-cache API `cache_edits` (`CACHED_MICROCOMPACT`; `services/compact/cachedMicrocompact.js` is absent from this snapshot — observed via call sites only) to avoid invalidating the prompt cache.
- **Context Collapse (`CONTEXT_COLLAPSE`)**: Stage 4 feature-gated read-time projection (`services/contextCollapse/`, implementation absent from this snapshot — observed via `query.ts` call sites, `recoverFromOverflow()`, and `marble-origami-commit`/`marble-origami-snapshot` JSONL writers in `utils/sessionStorage.ts`) that collapses ranges of conversation history into summaries without mutating the REPL scrollback array.
- **Session Memory Compact (`services/compact/sessionMemoryCompact.ts`, `services/SessionMemory/`)**: Stage 5 zero-LLM fast path attempted by `autoCompactIfNeeded()` before LLM summarization, gated by `ENABLE_CLAUDE_CODE_SM_COMPACT`, `DISABLE_CLAUDE_CODE_SM_COMPACT`, or GrowthBook `tengu_session_memory && tengu_sm_compact`. It awaits `waitForSessionMemoryExtraction()` in `services/SessionMemory/sessionMemoryUtils.ts`, substitutes the post-sampling `summary.md` scratchpad maintained by an `Edit`-only forked agent (tracking a tool-pair-safe `lastSummarizedMessageId` watermark), and keeps a verbatim tail sized by `minTokens: 10_000` / `minTextBlockMessages: 5` up to `maxTokens: 40_000`, floored at the prior `compact_boundary` and repaired by `adjustIndexToPreserveAPIInvariants()`; returns `null` to fall back to LLM AutoCompact if empty or over threshold.
- **AutoCompact (`services/compact/autoCompact.ts`, `services/compact/compact.ts`)**: Stage 5 full conversation summarization triggered near the context limit after trying Session Memory Compact first, emitting a `compact_boundary` system message and re-attaching key state (active files, invoked skills, plan state). Guarded by a circuit breaker (`MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES = 3`), runs cache-sharing `runForkedAgent()` (`tengu_compact_cache_prefix`) with streaming fallback, executes `isMainThreadCompact`-guarded `runPostCompactCleanup()` (`services/compact/postCompactCleanup.ts`), and manually subtracts pre-compact tokens from `taskBudgetRemaining` (`query.ts`).
- **Reactive Compact (`REACTIVE_COMPACT`)**: Fallback compaction (`services/compact/reactiveCompact.js`, absent from this snapshot — observed via `query.ts` call sites only) triggered after withholding an API `prompt_too_long` (413) or media-size error (`isWithheldMediaSizeError`)—following optional Context Collapse drain—so the turn can retry transparently while also subtracting `taskBudgetRemaining`.
- **Server-Side Context Management (`services/compact/apiMicrocompact.ts`)**: Orthogonal wire-level `context_management` API edits (`getAPIContextManagement()`), independent of Stage 3 client-side microcompact, attached in `services/api/claude.ts` only when `CONTEXT_MANAGEMENT_BETA_HEADER` (`'context-management-2025-06-27'` in `constants/betas.ts`) is active via `utils/betas.ts` (first-party betas + model support or ant-only `USE_API_CONTEXT_MANAGEMENT`). Sends `clear_thinking_20251015` when thinking is active and `!isRedactThinkingActive` (latching to `{ type: 'thinking_turns', value: 1 }` after >1h idle) plus ant-only `clear_tool_uses_20250919` (`USE_API_CLEAR_TOOL_RESULTS` / `USE_API_CLEAR_TOOL_USES`).
- **Prompt Cache Break Detection (`PROMPT_CACHE_BREAK_DETECTION`, `services/api/promptCacheBreakDetection.ts`)**: Feature-gated two-phase cache telemetry (`recordPromptState()` pre-call, `checkResponseForCacheBreak()` post-call in `services/api/claude.ts`) hashing 12 prompt, tool, model, effort, and beta dimensions across up to `MAX_TRACKED_SOURCES` (`10`) sources, attributing `> 5%` and `>= 2,000`-token (`MIN_CACHE_MISS_TOKENS`) `cache_read_input_tokens` drops to client diffs, 1h/5m TTL expiry, or server eviction, and writing unified diff files via `writeCacheBreakDiff()`.
- **Token Budget (`TOKEN_BUDGET`, `query/tokenBudget.ts`) vs. `taskBudget` (`query.ts`)**: Two distinct turn budgets—client-side `checkTokenBudget()` (`feature('TOKEN_BUDGET')`) auto-continues main-thread turns below 90% (`COMPLETION_THRESHOLD`) until diminishing returns (two consecutive `< 500`-token deltas after 3 continuations), whereas server-side `params.taskBudget` sends `output_config.task_budget` (`TASK_BUDGETS_BETA_HEADER` in `services/api/claude.ts`) and subtracts pre-compaction context tokens from loop-local `taskBudgetRemaining`.

---

## Internal Build, Product & Feature Terms

- **Ant-only (`process.env.USER_TYPE === 'ant'`)**: Code paths active only in Anthropic internal builds (e.g., `REPLTool`, `ConfigTool`, `TungstenTool`, prompt dumping, dev telemetry). Stripped from external builds via dead-code elimination.
- **`feature('FLAG_NAME')` (`bun:bundle`)**: Bun's compile-time feature flag primitive. Must remain inline at `if` / ternary sites so the bundler tree-shakes entire gated subsystems out of external binaries.
- **CCR (`CLAUDE_CODE_REMOTE`)**: Claude Code Remote container environment; activates remote heap sizing (`--max-old-space-size=8192`), `upstreamproxy` CONNECT relay, and remote session ingress/bridge transports.
- **Kairos (`KAIROS`, `kairosEnabled`)**: Feature-gated proactive/assistant operating mode (`assistant/`, `SleepTool`, `BriefTool`, `PushNotificationTool`, `SendUserFileTool`).
- **Sidechain**: A separate JSONL transcript file tied to a subagent's `AgentId`, allowing subagent conversations to be inspected, isolated from the main transcript, and resumed later (`tools/AgentTool/resumeAgent.ts`).
- **Swarm / Teammate**: Multi-agent team execution (`utils/swarm/`, `tasks/InProcessTeammateTask/`, `tools/TeamCreateTool/`, `tools/SendMessageTool/`) where named worker agents coordinate via mailboxes and route permission prompts through the leader.
- **Speculation (`SpeculationState`)**: Predictive background execution of a suggested next turn in an isolated overlay (`state/AppStateStore.ts`), allowing instant commit if the user accepts the prompt suggestion.
- **Coordinator Mode (`COORDINATOR_MODE`, `CLAUDE_CODE_COORDINATOR_MODE`, `coordinator/coordinatorMode.ts`)**: Compile-time (`feature('COORDINATOR_MODE')`) and runtime (`CLAUDE_CODE_COORDINATOR_MODE`) orchestration mode that replaces the default system prompt with `getCoordinatorSystemPrompt()` in the Coordinator branch of `buildEffectiveSystemPrompt()` (`utils/systemPrompt.ts`), below `overrideSystemPrompt` and yielding to `--agent` via `!mainThreadAgentDefinition`, and converts main-thread inline prompt slash commands into delegation stubs (`utils/processUserInput/processSlashCommand.tsx`).
- **Team Memory (`TEAMMEM`, `memdir/teamMemPaths.ts`, `services/teamMemorySync/`)**: Feature-gated (`feature('TEAMMEM')` + GrowthBook `tengu_herring_clock`) shared repository memory under `<autoMemPath>/team/`, synchronized over first-party OAuth (`pullTeamMemory()` server-wins parallel pull, `pushTeamMemory()` local-wins `200_000`-byte `MAX_PUT_BODY_BYTES` batched delta push, and pull-before-watch `startTeamMemoryWatcher()` circuit-broken on `isPermanentFailure()`). Hardened with two-pass symlink containment (`realpathDeepestExisting()`) and dual-layer 36-rule gitleaks secret scanning (`checkTeamMemSecrets()` pre-write in `services/teamMemorySync/teamMemSecretGuard.ts` + full-file `scanForSecrets()` pre-push in `services/teamMemorySync/secretScanner.ts`).
- **DCE Cliff & `NATIVE_CLIENT_ATTESTATION` (`cch=00000;`)** (`tools/BashTool/bashPermissions.ts`, `constants/system.ts`): Per-function Bun bundler complexity ceiling that can silently fold `feature('BASH_CLASSIFIER')` to `false` if function shape shifts, and the fixed-width zero placeholder overwritten in place by Anthropic's custom Bun Zig HTTP stack for API attestation without changing `Content-Length`.
- **`SAFE_ENV_VARS`, `filterSettingsEnv()` & `GHA_SUBPROCESS_SCRUB`** (`utils/managedEnvConstants.ts`, `utils/managedEnv.ts`, `utils/subprocessEnv.ts`): Three-tier environment hygiene—pre-trust allowlist for untrusted project settings, three-layer host-protection strip filters (`withoutSSHTunnelVars`, `withoutHostManagedProviderVars`, `withoutCcdSpawnEnvKeys`), and 23-var (+ `INPUT_*`) credential scrubbing before child process spawns (`CLAUDE_CODE_SUBPROCESS_ENV_SCRUB`).
- **Excluded-Strings Check & `marble-origami-*`** (`types/logs.ts`, `utils/sessionStorage.ts`, `utils/attachments.ts`): CI hygiene check barring internal feature strings from leaking into external builds, motivating obfuscated JSONL transcript discriminators (`marble-origami-commit` / `marble-origami-snapshot` for `CONTEXT_COLLAPSE`) and conditional `require()` placement.
- **`TombstoneMessage` & `CacheEditsBlock`** (`query.ts`, `QueryEngine.ts`, `services/api/claude.ts`, `services/compact/microCompact.ts`): Non-persisted `{ type: 'tombstone', message }` signal removing orphaned mid-stream retry fragments from transcripts, and server-side `{ type: 'cache_edits', edits: [{ type: 'delete', cache_reference }] }` deletion blocks pinned to a `userMessageIndex` under `CACHED_MICROCOMPACT`.


---

<!-- EDITORIAL_GUIDE.md — https://reverseengineeringclaudecode.com/editorial-guide -->

# Editorial & Authoring Guide

This guide defines the voice, structure, and engineering rigor for every chapter in `book/`. Whether a chapter is drafted by a human author or an AI collaborator, it should read as if written by one clear-eyed systems engineer walking a peer through a real codebase at a whiteboard.

---

## 1. Core Voice & Pedagogical Principles

1. **Bottom-up, never encyclopedic.**
   Do not list every function in a file. Teach the *minimum set of load-bearing abstractions* that make the subsystem click, in dependency order.
2. **Problem → Mechanism → Invariant.**
   Never show a data structure before explaining the concrete bug, race condition, latency cliff, or security hazard that forced it to exist.
3. **Explain the scars.**
   Real production codebases are full of battle scars—`DANGEROUS_uncachedSystemPromptSection`, UNC path checks to stop NTLM leaks, `setAppStateForTasks`, `cachedClaudeMdContent` cycle breakers, `withheld` error suppression. Those comments and workarounds are the *most educational lines in the entire repo*. Highlight them.
4. **Build a mental model, not just prose.**
   Use small ASCII or Mermaid diagrams to show data flow, state transitions, and ownership boundaries. Summarize each chapter with a crisp **"Snap-In Point"** showing exactly how the next layer consumes what we just built.

---

## 2. Standard Chapter Anatomy

Every numbered chapter in `book/chapters/` should follow this repeatable rhythm:

```markdown
# Chapter NN — Title: Crisp Subtitle

> **Layer:** Layer X (Name)
> **Prerequisites:** Chapters ...
> **Primary Source Files:**
> - `path/to/fileA.ts` — one-line role
> - `path/to/fileB.ts` — one-line role

## Why This Layer Exists
Frame the exact engineering problem we are solving now that Layers 0..X-1 exist.

## 1. First Building Block
### The Problem
### The Real Implementation (short, annotated excerpt or exact symbol walkthrough)
### Hidden Invariants & Failure Modes

## 2. Second Building Block
...

## Putting the Layer Together
ASCII / Mermaid diagram showing how the pieces in this chapter compose.

## How This Snaps Into the Next Layer
Explicit handoff into Chapter NN+1 (naming the exact downstream caller/file).

## Reading Exercises & Code Checkpoints
2–4 targeted questions or `rg` commands the reader can run in this repo to verify their understanding.
```

---

## 3. Source Grounding & Honesty Rules

Because this is a reverse-engineering book written against a real source snapshot, **factual precision is non-negotiable**:

- **Verify before writing.** Never cite a file path, symbol name, line number, or behavior from memory. Read the file directly first.
- **Quote lightly and faithfully.** Include short, focused TypeScript excerpts (5–35 lines) that illuminate the design; paraphrase long boilerplate and point the reader to exact file paths and line ranges (e.g., `services/tools/toolOrchestration.ts:91-116`).
- **Flag build-time and runtime gates.** Whenever a code path is behind `feature('...')`, `process.env.USER_TYPE === 'ant'`, GrowthBook (`getFeatureValue_*`), or an env var, explicitly say so. Never present a gated experiment as universally active.
- **Flag snapshot absences transparently.** If an imported module is absent from this checkout (such as `types/message.ts`, `query/transitions.ts`, `services/contextCollapse/`, or `services/skillSearch/`), explicitly label what is **observed at call sites** vs. **absent from the snapshot**.
- **Do not invent build/test commands.** This checkout has no tracked `package.json`, `tsconfig.json`, or test harness. Exercises should use read-only inspection (`rg`, reading source files, tracing types) rather than claiming runnable CLI build commands.
- **Prefer repo-relative paths inside `book/`.** Use paths like `Tool.ts` or relative markdown links like `[Tool.ts](../../Tool.ts)` from `book/chapters/` (or `[Tool.ts](../Tool.ts)` from `book/`) so links work cleanly on GitHub and locally.

---

## 4. Diagram & Formatting Conventions

- **Mermaid diagrams:** Stick to `flowchart TD`, `flowchart LR`, `sequenceDiagram`, and `stateDiagram-v2`. Always quote node labels containing parentheses, brackets, or colons (e.g., `A["query() loop"]`).
- **ASCII diagrams:** Keep lines under 80 columns so they render cleanly in terminals, editors, and narrow viewports.
- **Callout boxes:** Use GitHub-style alerts purposefully:
  - `> [!NOTE]` — subtle codebase detail or snapshot caveat.
  - `> [!IMPORTANT]` — load-bearing architectural invariant (e.g., prompt-cache boundary).
  - `> [!WARNING]` — subtle trap or failure mode the code explicitly guards against.
- **Consistent naming:**
  - Refer to the application as "Claude Code" (or "the agent harness"); the source snapshot is Claude Code 2.1.88. Don't call it `cc`, which is only the local folder name.
  - Use `monospace` for file paths, symbols, env vars, feature flags, and type names.

---

## 5. Chapter Naming & File Convention

- Directory: `book/chapters/`
- Filename: `NN-kebab-case-slug.md` (zero-padded two-digit prefix: `00-...`, `01-...`, `02-...`, ... `24-...`).
- When a new chapter is drafted or updated, update the **Manuscript Progress** table in [README.md](README.md) and add any new domain terms to [GLOSSARY.md](GLOSSARY.md).
