# 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`.
