Reference
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()inquery/config.ts): SnapshotssessionIdand four runtime env/Statsig gates (streamingToolExecutionvia'tengu_streaming_tool_execution2',emitToolUseSummariesviaCLAUDE_CODE_EMIT_TOOL_USE_SUMMARIES,isAnt, and inlinedfastModeEnabledrespectingCLAUDE_CODE_DISABLE_FAST_MODE) once per turn while intentionally excludingfeature()flags so Bun dead-code elimination stays intact.QueryDeps(productionDeps()inquery/deps.ts): Injects four narrow I/O seams (callModel,microcompact,autocompact,uuid) typed viatypeof fn(plusuuid: () => 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 intoContentBlockParam[]and sends them to the model (eitherinlineorforked 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()inutils/messages.ts): Model-agnostic cleanup that dropsisVirtual,progress, UI-onlysystemsubtypes (promotingsystem/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 bidirectionalensureToolResultPairing()(utils/messages.ts, injectingis_error: trueSYNTHETIC_TOOL_RESULT_PLACEHOLDERblocks or throwing undergetStrictToolResultPairing()inbootstrap/state.ts), then emits wireMessageParam[]viaaddCacheBreakpoints()(one message-levelcache_controlmarker, shifted tolength - 2underskipCacheWrite),userMessageToMessageParam(), andassistantMessageToMessageParam().
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 aTerminalreason.QueryEngine(QueryEngine.ts): The outer conversation/session envelope owning cross-turn state (mutableMessages,readFileState,permissionDenials,totalUsage,abortController, transcript recording) and adaptingquery()events intoSDKMessagestreams viasubmitMessage().
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_results 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 toTaskOutputand emitasync_hook_responseattachments viacheckForAsyncHookResponses(), whileasyncRewake: trueretains in-memory buffers and enqueues atask-notificationon exit code2to wake the model.hooksConfigSnapshot&SessionHooksState(utils/hooks/hooksConfigSnapshot.ts,utils/hooks/sessionHooks.ts): Startup-captured enterprise-filtered settings-hook snapshot (enforcingdisableAllHooks,allowManagedHooksOnly, andstrictPluginOnlyCustomization) paired with an ephemeral per-session/per-agentMapholding skill/subagent frontmatter hooks and non-serializableFunctionHookvalidators.ssrfGuardedLookup(utils/hooks/ssrfGuard.ts): Axioslookuphook 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→policySettingsabovepluginSettingsBase, with first-source-winspolicySettings) paired with single-producer cache invalidation inchangeDetector.ts(fanOut()callsresetSettingsCache()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 exceptallow_product_feedbackunder essential-traffic-only (HIPAA) mode.strictPluginOnlyCustomization(utils/settings/pluginOnlyPolicy.ts,utils/settings/types.ts): Managed enterprise policy (trueor subset of['skills', 'agents', 'hooks', 'mcp']) blocking user/project customizations outsideADMIN_TRUSTED_SOURCES.ClaudeAuthProvider& Cross-App Access (XAA / SEP-990) (services/mcp/auth.ts,services/mcp/xaa.ts): MCPOAuthClientProvidersupporting 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 andshouldDefer: truetool schemas until discovered viaToolSearchToolwhile 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 byElicitation/ElicitationResulthooks or queued inAppState.elicitation.queue, with two-phase URL waiting andElicitationCompleteretries. - Conditional Skill &
SAFE_SKILL_PROPERTIES(skills/loadSkillsDir.ts,tools/SkillTool/SkillTool.ts): Disk-loaded skills withheld inconditionalSkillsuntil a matching file path is touched (paths:frontmatter), governed by a fail-closed allowlist of auto-executablePromptCommandkeys. - 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 liveAppState/STATE.registeredHooksactivation (refreshActivePlugins()via/reload-plugins, Layer 3). - Output Style &
LSPDiagnosticRegistry(constants/outputStyles.ts,services/lsp/LSPDiagnosticRegistry.ts,services/lsp/passiveFeedback.ts): Persona framing injected above/belowSYSTEM_PROMPT_DYNAMIC_BOUNDARY, and the 500-fileLRUCacheasync 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 intomessageQueueManager.tson completion or prompt stall.CronScheduler(utils/cronScheduler.ts,utils/cronTasks.ts,utils/cronTasksLock.ts): Local 5-field cron engine combiningO_EXCLmulti-session lease locking (.claude/scheduled_tasks.lock), UUID-hashed anti-herd jitter tuned viatengu_kairos_cron_config, and 7-day auto-expiry.createSubagentContext()&FORK_AGENT(utils/forkedAgent.ts,tools/AgentTool/forkSubagent.ts): Subagent context factory cloningreadFileState/contentReplacementState, stubbingsetAppState, and keepingsetAppStateForTasksroot-wired;FORK_AGENT(feature('FORK_SUBAGENT')) freezesrenderedSystemPrompt, matches tool pools, and emits identicalFORK_PLACEHOLDER_RESULTblocks so parallel children achieve near-100% prompt-cache hits.runWithCwdOverride()&.meta.jsonSidecar (utils/cwd.ts,utils/sessionStorage.ts,tools/AgentTool/resumeAgent.ts):AsyncLocalStorage-backed working-directory scope isolating concurrent worktree subagents without mutatingprocess.cwd(), paired with per-subagent JSONL +.meta.jsonsidecars enablingresumeAgentBackground().TeammateContext, Teammate Mailbox & Leader Permission Bridge (utils/teammateContext.ts,utils/teammateMailbox.ts,utils/swarm/leaderPermissionBridge.ts):AsyncLocalStorageteammate identity, file-locked JSON array inboxes (~/.claude/teams/{team}/inboxes/{agent}.json) multiplexing DMs andisStructuredProtocolMessage()control payloads, and the module registry bridging in-process workerToolUseConfirmprompts to the leader's terminal UI.- Packed
ScreenBuffer & Pure-TS Yoga (ink/screen.ts,native-ts/yoga-layout/index.ts,ink/layout/yoga.ts): Dual-view 8-byte-per-cellInt32Array/BigInt64Arrayterminal framebuffer paired with a synchronous 2,578-line pure-TypeScript Yoga flexbox engine with generation-stamped layout caching. DECSTBMScroll 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 onDEC 2026synchronized 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+ 11NORMALsub-states) bridged intoBaseTextInputvia 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+TLSHEADwarmup (strictly afterapplyExtraCACertsFromConfig()andconfigureGlobalAgents()) with module import and action-handler boot. registerCleanup()& Startup Profiler (utils/cleanupRegistry.ts,utils/gracefulShutdown.ts,utils/startupProfiler.ts): Zero-dependency teardown callbackSetdrained under a 2-second shutdown budget, paired with sampledperf_hookscheckpoints (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, runtimeprocess.stdout.writeguard diverting non-JSON lines tostderr, ECMA-262U+2028/U+2029escaper, andheldBackResultturn-completion deferral for background tasks.startMCPServer(claude/tengu) (entrypoints/mcp.ts): Inverted MCP stdio server mode (claude mcp serve) exposinggetTools()directly overStdioServerTransportwithoutQueryEngineorrunToolUse().- 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 viaPOST /v1/code/sessions/{id}/bridge(tengu_bridge_repl_v2), monotonic409 Conflictfencing tokens, history-vs-live ordering gate, and remoteclaude.ai/mobile permission approval racing atomically viaclaim(). - Upstream Proxy Relay (
upstreamproxy/) (upstreamproxy/upstreamproxy.ts,upstreamproxy/relay.ts): Fail-open container-side local HTTPCONNECT-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 inquery.ts—replaces oversized tool outputs with<persisted-output>file references. - History Snip (
HISTORY_SNIP): Feature-gated Stage 2 inquery.tsthat snips old history segments before microcompaction, subtractingsnipTokensFreedbefore threshold checks (services/compact/snipCompact.jsandservices/compact/snipProjection.jsare 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_heroninservices/compact/timeBasedMCConfig.ts, default 60 min idle) or optionally warm-cache APIcache_edits(CACHED_MICROCOMPACT;services/compact/cachedMicrocompact.jsis 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 viaquery.tscall sites,recoverFromOverflow(), andmarble-origami-commit/marble-origami-snapshotJSONL writers inutils/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 byautoCompactIfNeeded()before LLM summarization, gated byENABLE_CLAUDE_CODE_SM_COMPACT,DISABLE_CLAUDE_CODE_SM_COMPACT, or GrowthBooktengu_session_memory && tengu_sm_compact. It awaitswaitForSessionMemoryExtraction()inservices/SessionMemory/sessionMemoryUtils.ts, substitutes the post-samplingsummary.mdscratchpad maintained by anEdit-only forked agent (tracking a tool-pair-safelastSummarizedMessageIdwatermark), and keeps a verbatim tail sized byminTokens: 10_000/minTextBlockMessages: 5up tomaxTokens: 40_000, floored at the priorcompact_boundaryand repaired byadjustIndexToPreserveAPIInvariants(); returnsnullto 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 acompact_boundarysystem message and re-attaching key state (active files, invoked skills, plan state). Guarded by a circuit breaker (MAX_CONSECUTIVE_AUTOCOMPACT_FAILURES = 3), runs cache-sharingrunForkedAgent()(tengu_compact_cache_prefix) with streaming fallback, executesisMainThreadCompact-guardedrunPostCompactCleanup()(services/compact/postCompactCleanup.ts), and manually subtracts pre-compact tokens fromtaskBudgetRemaining(query.ts). - Reactive Compact (
REACTIVE_COMPACT): Fallback compaction (services/compact/reactiveCompact.js, absent from this snapshot — observed viaquery.tscall sites only) triggered after withholding an APIprompt_too_long(413) or media-size error (isWithheldMediaSizeError)—following optional Context Collapse drain—so the turn can retry transparently while also subtractingtaskBudgetRemaining. - Server-Side Context Management (
services/compact/apiMicrocompact.ts): Orthogonal wire-levelcontext_managementAPI edits (getAPIContextManagement()), independent of Stage 3 client-side microcompact, attached inservices/api/claude.tsonly whenCONTEXT_MANAGEMENT_BETA_HEADER('context-management-2025-06-27'inconstants/betas.ts) is active viautils/betas.ts(first-party betas + model support or ant-onlyUSE_API_CONTEXT_MANAGEMENT). Sendsclear_thinking_20251015when thinking is active and!isRedactThinkingActive(latching to{ type: 'thinking_turns', value: 1 }after >1h idle) plus ant-onlyclear_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 inservices/api/claude.ts) hashing 12 prompt, tool, model, effort, and beta dimensions across up toMAX_TRACKED_SOURCES(10) sources, attributing> 5%and>= 2,000-token (MIN_CACHE_MISS_TOKENS)cache_read_input_tokensdrops to client diffs, 1h/5m TTL expiry, or server eviction, and writing unified diff files viawriteCacheBreakDiff(). - Token Budget (
TOKEN_BUDGET,query/tokenBudget.ts) vs.taskBudget(query.ts): Two distinct turn budgets—client-sidecheckTokenBudget()(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-sideparams.taskBudgetsendsoutput_config.task_budget(TASK_BUDGETS_BETA_HEADERinservices/api/claude.ts) and subtracts pre-compaction context tokens from loop-localtaskBudgetRemaining.
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 atif/ 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),upstreamproxyCONNECT 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 withgetCoordinatorSystemPrompt()in the Coordinator branch ofbuildEffectiveSystemPrompt()(utils/systemPrompt.ts), belowoverrideSystemPromptand yielding to--agentvia!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')+ GrowthBooktengu_herring_clock) shared repository memory under<autoMemPath>/team/, synchronized over first-party OAuth (pullTeamMemory()server-wins parallel pull,pushTeamMemory()local-wins200_000-byteMAX_PUT_BODY_BYTESbatched delta push, and pull-before-watchstartTeamMemoryWatcher()circuit-broken onisPermanentFailure()). Hardened with two-pass symlink containment (realpathDeepestExisting()) and dual-layer 36-rule gitleaks secret scanning (checkTeamMemSecrets()pre-write inservices/teamMemorySync/teamMemSecretGuard.ts+ full-filescanForSecrets()pre-push inservices/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 foldfeature('BASH_CLASSIFIER')tofalseif function shape shifts, and the fixed-width zero placeholder overwritten in place by Anthropic's custom Bun Zig HTTP stack for API attestation without changingContent-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-snapshotforCONTEXT_COLLAPSE) and conditionalrequire()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 auserMessageIndexunderCACHED_MICROCOMPACT.
Manuscript GLOSSARY.md from AtlantisPleb/cc at 5aa286a, synced Nov 24, 2026.