返回 CodeWhale
ARCHITECTURE.md
根目录 / docs / ARCHITECTURE.md
1 # Codewhale Architecture
2
3 > 阅读简体中文版:[zh_hans/ARCHITECTURE.md](zh_hans/ARCHITECTURE.md)。
4
5 Codewhale Engine is the existing Rust execution runtime. The
6 [Runtime API](RUNTIME_API.md) is its client interface, and
7 [TypeScript mods](EXTENSIONS.md) contribute reviewed plugins.
8
9 Current boundary note (read the workspace version from `Cargo.toml`):
10 - `crates/tui` is still the live end-user runtime for the TUI, runtime API, task manager, and tool execution loop.
11 - Other workspace crates are being split out incrementally, but they are not yet the sole runtime source of truth.
12 - `crates/net` owns network policy/auditing, destination and DNS guards, proxy resolution, and Claude import planning. Host tool context, transport grants, redirects and response limits stay with their callers. Pure plugin-host settings belong to `crates/config`.
13 - `crates/notify` owns shared notification payload redaction, attention/category gates, sound policy, and local audio dispatch. TUI retains terminal sinks and native hosts retain banner submission.
14 - `crates/util` owns shared string/path/atomic-write helpers, confined workspace file access, link and file-identity checks, bundle file readers, the `.git` name rule and the exclusive file lock.
15 - `crates/dependencies` owns external-tool resolution and bounded subprocess probes (git, python, node, bun); `crates/snapshot` the pre/post-turn side-repo snapshots; `crates/lsp` the language-server client; `crates/repl` the Python REPL runtime and its stdin protocol.
16 - `crates/plugins` owns plugin manifests, discovery, trust review, install and marketplace parsing. Its test-only constructors and policy guards sit behind a dev-dependency-only `test-support` feature; the DSH composition reviewer is registered by the TUI at startup.
17 - `crates/skill-install` owns the community-skill installer (GitHub and tarball sources, the curated registry, bounded extraction, install and trust markers), the package content digest and the shared `SKILL.md` frontmatter reader. Its SSRF DNS pin and shortened timeouts are relaxed only under its dev-dependency-only `test-support` feature.
18
19 <img src="assets/architecture.webp" alt="Codewhale architecture: clients reach the one turn loop, Engine::run_turn, through the CLI or the Runtime API; the engine uses crates/core to build requests, runs tools under approval and sandbox policy, routes to any provider through crates/config, and logs everything model-visible to the session store." width="1000">
20
21 The diagram draws the Runtime API and the task manager as their own boxes; today
22 both are hosted inside `crates/tui`, as the note above says. The desktop
23 app and the VS Code extension live outside this repository. The arrow from the
24 engine to the session log follows the "model-visible means logged" contract
25 rather than a traced write path.
26 - `crates/tui` is being split into crates sized as agent work partitions:
27 contracts, utilities, services, providers, runtime, leaf feature crates,
28 TUI views and hosts, in the order `docs/design/TUI_DECONSTRUCTION.md`
29 records. The TUI stays the only crate that writes to the terminal. Until a
30 module has moved, its path under `crates/tui/src` is still where it lives.
31 - The LSP subsystem (`crates/lsp/src/`) is fully wired into the engine's
32 post-tool-execution path (`core/engine/lsp_hooks.rs`), providing inline
33 diagnostics after `File` write, edit, and patch actions.
34 - There is no separate swarm agent system. The active sub-agent surface is
35 the single `agent` tool; persistent RLM sessions are available through the
36 deferred `rlm` action family.
37 No model-visible swarm tool remains in the active codebase.
38
39 ## High-Level Overview
40
41 ```
42 ┌─────────────────────────────────────────────────────────────────┐
43 │ User Interface │
44 │ ┌─────────────────┐ ┌─────────────────┐ ┌────────────────┐ │
45 │ │ TUI (ratatui) │ │ One-shot Mode │ │ Config/CLI │ │
46 │ └────────┬────────┘ └────────┬────────┘ └────────┬───────┘ │
47 └───────────┼─────────────────────┼────────────────────┼──────────┘
48 │ │ │
49 ▼ ▼ ▼
50 ┌─────────────────────────────────────────────────────────────────┐
51 │ Core Engine │
52 │ ┌─────────────────────────────────────────────────────────┐ │
53 │ │ Agent Loop (core/engine.rs) │ │
54 │ │ ┌─────────┐ ┌─────────────┐ ┌──────────────────────┐ │ │
55 │ │ │ Session │ │ Turn Mgmt │ │ Tool Orchestration │ │ │
56 │ │ └─────────┘ └─────────────┘ └──────────────────────┘ │ │
57 │ └─────────────────────────────────────────────────────────┘ │
58 └─────────────────────────────────────────────────────────────────┘
59 │ │ │
60 ▼ ▼ ▼
61 ┌─────────────────────────────────────────────────────────────────┐
62 │ Tool & Extension Layer │
63 │ ┌──────────┐ ┌──────────┐ ┌─────────┐ ┌────────────────┐ │
64 │ │ Tools │ │ Skills │ │ Hooks │ │ MCP Servers │ │
65 │ │ (shell, │ │ (plugins)│ │ (pre/ │ │ (external) │ │
66 │ │ file) │ │ │ │ post) │ │ │ │
67 │ └──────────┘ └──────────┘ └─────────┘ └────────────────┘ │
68 └─────────────────────────────────────────────────────────────────┘
69 │ │ │
70 ▼ ▼ ▼
71 ┌─────────────────────────────────────────────────────────────────┐
72 │ Runtime API + Task Management │
73 │ ┌─────────────────────────────┐ ┌──────────────────────────┐ │
74 │ │ HTTP/SSE Runtime API │ │ Persistent Task Manager │ │
75 │ │ (runtime_api.rs) │ │ (task_manager.rs) │ │
76 │ └─────────────────────────────┘ └──────────────────────────┘ │
77 └─────────────────────────────────────────────────────────────────┘
78 │ │
79 ▼ ▼
80 ┌─────────────────────────────────────────────────────────────────┐
81 │ LLM Layer │
82 │ ┌──────────────────────────────────────────────────────────┐ │
83 │ │ LLM Client Layer (client.rs) │ │
84 │ │ ┌──────────────────┐ ┌─────────────────────────────┐ │ │
85 │ │ │ OpenAI-compatible │ │ Anthropic / Responses │ │ │
86 │ │ │ (chat adapter) │ │ (adapters) │ │ │
87 │ │ └──────────────────┘ └─────────────────────────────┘ │ │
88 │ └──────────────────────────────────────────────────────────┘ │
89 └─────────────────────────────────────────────────────────────────┘
90 ```
91
92 ## Module Organization
93
94 ### Entry Point
95
96 - **`crates/cli/src/main.rs`** - The canonical executable entry point. `crates/cli/src/lib.rs` owns its command interface; terminal and headless runtime startup runs in process through the `codewhale_tui` library in `crates/tui/src/lib.rs`.
97
98 ### Core Components
99
100 - **`core/`** - Main engine components
101 - `engine.rs` - Engine state, operation handling, message processing
102 - `engine/turn_loop.rs` - The existing Engine outer turn loop, shared tool
103 planner/executor/result handling, and stream decoder. Its private
104 `turn_loop/` phases contain request preparation (`preparation.rs`), model
105 dispatch and admission (`model_step.rs`), the ordered continuation ladder
106 (`continuation.rs`), inline REPL orchestration (`inline_repl.rs`), and the
107 direct model tool batch (`tool_batch.rs`). They borrow the same Engine and
108 TurnContext; they introduce no runtime, session, prompt, approval, event,
109 or persistence authority. Retry, loop termination, and immediate return
110 stay distinct, and only the existing productive paths advance the step.
111 - `session.rs` - Session state management
112 - `turn.rs` - Turn-based conversation handling
113 - `events.rs` - Event system for UI updates
114 - `ops.rs` - Core operations
115
116 ### Configuration
117
118 - **`config.rs`** - Configuration loading, profiles, environment variables
119 - **`settings.rs`** - Runtime settings management
120
121 ### Workspace Crates
122
123 The complete list, generated from the manifests, is in
124 [Workspace crates](reference/crates.md). The notes below explain the main ones.
125
126 - **`crates/cli`** - The canonical `codewhale` executable and command interface.
127 It owns commands such as `auth`, `metrics` and `update`, and invokes terminal
128 and headless modes (`run`, `exec`, `doctor`, `sessions`, ...) in process via
129 `codewhale_tui::run(RuntimeOptions, args)`. `crates/tui` is a library; the
130 `codew` and legacy release filename aliases contain the same executable.
131 - **`crates/tools`** - Shared tool invocation primitives, including tool result/error/capability types used by the TUI runtime.
132 - **`crates/agent-contract`** - Fleet role, child authority (`ChildAuthority`, `ChildGrant`) and worker runtime profile types the agent tool resolves before it spawns a child.
133 - **`crates/app-server`** - HTTP/SSE + JSON-RPC app server transport for
134 headless agent workflows. The canonical executable dispatches
135 `app-server --http`/`--mobile` in process to the runtime API hosted by the
136 `codewhale_tui` library.
137 - **`crates/config`** - Config loading, profiles, environment variable precedence, CLI runtime overrides.
138 - **`crates/cloud-facts`** - Fetches the signed Codewhale cloud facts channel
139 (`facts/v1`), verifies its Ed25519 envelope, and keeps a verified disk cache;
140 never a startup dependency.
141 - **`crates/command-contract`** - Prototype command capability and dispatch
142 shapes for the staged extraction of TUI commands; shapes only, not yet the
143 production dispatch path.
144 - **`crates/core`** - Provider-neutral request construction (`request.rs`),
145 bounded context fragments, the tool-call parser, and thread/session types.
146 It does **not** own the agent loop: the live turn loop is
147 `Engine::run_turn` in `crates/engine/src/core/engine/turn_loop.rs`, and
148 `crates/engine/src/core/` is a module inside the TUI crate, not this crate. A
149 placeholder `engine/` tree here once suggested otherwise — it had no callers
150 and emitted `TurnComplete` without contacting a model — and was removed in
151 v0.9.11. The source guard follows resolved local phase calls and still
152 rejects unlisted loop owners. ACP stdio now projects the existing Runtime
153 manager and Engine; it keeps no provider/tool round loop or separate history.
154 Recursive RLM and mounted Python RPCs now project captured caller authority
155 onto the same Engine producer and Session; no RLM loop exception remains.
156 Python retains its context and variables, while each round borrows the
157 captured route, Native selection, original code gate, cancellation and
158 deadline. Task guidance is bounded and additive to Core policy. Recursive
159 history is retained whole; overflow refuses rather than compacting it.
160 Persistent `rlm` contexts remain caller-session scoped and `share_session=true`
161 explicitly refuses. Child workers also use their captured admission in the
162 same Engine; neither nested host retains a turn-loop exception.
163 - **`crates/execpolicy`** - Approval/sandbox policy engine for tool execution decisions.
164 - **`crates/hooks`** - The opt-in lifecycle outbox (JSONL file and webhook
165 delivery of lifecycle events). User-configured shell hooks that run commands around tool
166 calls are a separate system in `crates/engine/src/hooks.rs`.
167 - **`crates/localization`** - Locale registry for user-facing UI chrome strings
168 (`crates/localization/locales/*.json`); it never changes prompts or model
169 output language.
170 - **`crates/mcp`** - MCP client + stdio server for Model Context Protocol tool servers.
171 - **`crates/memory`** - Local, scoped, provenance-bearing memory and
172 resumable state (a library, not a second agent loop).
173 - **`crates/models`** - Provider request/response models and the offline model
174 metadata catalog.
175 - **`crates/palette`** - Colour tokens, themes, and contrast math for the
176 terminal UI. Its `ratatui` feature (on by default) gates everything that
177 renders; theme ids, setting normalizers and hex parsing compile without it,
178 which is how the runtime links it.
179 - **`crates/paths`** - User-scoped runtime path authority (`CODEWHALE_HOME`
180 and platform home resolution).
181 - **`crates/protocol`** - Request/response framing and protocol types.
182 - **`crates/runtime`** - `codewhale-runtime`, the headless runtime being
183 split out of `crates/tui` (`docs/design/TUI_DECONSTRUCTION.md`). Today it
184 holds the leaf modules that moved first (retry status, safe labels, sleep
185 guard, session tree, ...) and `host_terminal`, the one port through which
186 runtime code asks the terminal UI for a terminal effect. It never depends on
187 the TUI, `ratatui` or `crossterm`; `scripts/check-command-crate-boundaries.py`
188 enforces that and ratchets the runtime -> UI references still in `crates/tui`.
189 - **`crates/sandbox`** - Command sandbox policy, platform wrapper preparation,
190 read denial, process hardening and the shared shell dispatcher. Runtime
191 config and terminal ports remain dependencies; this crate never owns a
192 turn loop or depends on the TUI.
193 - **`crates/secrets`** - Secret storage. API keys and MCP OAuth tokens live in
194 a private file store (`~/.codewhale/secrets/secrets.json`, mode `0600` on
195 Unix) by default; the OS keyring is used only when
196 `CODEWHALE_SECRET_BACKEND=system` opts in, and a keyring that fails its probe
197 falls back to the file store. Account sessions always use the file store.
198 The crate also re-exports the shared output sanitizer (`sanitize`) and
199 redaction (`redact`) from `crates/sanitize`, which UI and runtime code both
200 call.
201 - **`crates/state`** - SQLite thread/session persistence layer.
202 - **`crates/telemetry`** - Anonymous, user-disableable aggregate usage
203 counting; the only crate allowed to build or send a telemetry payload
204 (`docs/TELEMETRY.md`).
205 - **`crates/workflow`** / **`crates/workflow-js`** - Workflow engine and its
206 QuickJS scripting layer (renamed from the whaleflow crates).
207 - **`crates/lane`** - Lane runtime: durable, attachable running instances of
208 Fleet/Workflow work (`codewhale lane list/status/attach/logs/stop`).
209 - **`crates/release`** / **`crates/build-support`** - Release checks and build
210 plumbing.
211
212 ### Embedded turn terminal ownership
213
214 `TurnComplete` is the authoritative terminal event; `Error` remains advisory.
215 The engine and protocol projection preserve the operation's original identity:
216
217 - Model turns echo their actual `TurnStarted.turn_id` and the submitted
218 `submission_id` on completion, failure and interruption. Runtime self-starts
219 carry no host submission token.
220 - A route-install failure or an `edit_last_turn` rejection before
221 `TurnStarted` emits a failed terminal with the rejected `submission_id` and
222 no `turn_id`. It does not claim a previous turn. Image and constitution
223 rejections in `handle_send_message` still emit only `Error`.
224 - Manual compaction terminals carry only their `compaction_id`, including route
225 rejection and cancellation. Automatic compaction remains part of its owning
226 model turn. Purge operations carry none of these identities.
227
228 Wire fields are optional and default to absent for older producers. An embedded
229 host must match an owned receipt before closing a pending operation; it must
230 not infer ownership from advisory errors, an absent ID, or whichever request
231 happens to be busy. Hosts also need their own engine-incarnation fence: these
232 IDs do not authorize an event from an evicted runtime to mutate its
233 replacement. This contract adds no model prompt/context contributor and no
234 second turn loop.
235
236 ### LLM Integration
237
238 - **`client.rs`** - The live HTTP client layer: OpenAI-compatible, Anthropic,
239 and Responses wire adapters, DeepSeek request-boundary handling, retry
240 policy, and streaming. Provider routes land here through the shared config
241 and catalog layers.
242 - **`llm_client/`** - LLM client trait, retry logic, and error classification
243 (`LlmClient`, `RetryConfig`, `with_retry`) consumed by `client.rs`; `mock.rs`
244 is test-only (`#[cfg(test)]`).
245 - **`crates/models`** (`codewhale_models`) - Data structures for API
246 requests/responses; the TUI crate has no local `models.rs`.
247
248 #### DeepSeek API Endpoints
249
250 DeepSeek exposes OpenAI-compatible endpoints. The first-party route uses:
251 - `https://api.deepseek.com/beta` - default DeepSeek base URL (`provider_defaults.rs`)
252 - `https://api.deepseek.com/beta/models` - live model discovery and health checks
253
254 `https://api.deepseek.com/v1` is accepted for OpenAI SDK compatibility, and
255 can still be configured explicitly to opt out of beta-only features such as
256 strict tool mode, chat prefix completion, and FIM completion. The public
257 DeepSeek docs do not document a Responses API path for this workflow; the engine
258 drives turns through Chat Completions.
259
260 ### Tool System
261
262 - **`tools/`** - Built-in tool implementations
263 - `mod.rs` - Tool registry and common types
264 - `shell.rs` - Shell command execution
265 - `file.rs` - File read/write operations
266 - `todo.rs` - Checklist tools plus legacy todo aliases
267 - `tasks.rs` - Model-visible durable task, gate, background shell, and PR-attempt tools
268 - `git.rs` - Read-only `git_status` / `git_diff` inspection wrappers
269 - `git_tool.rs` - The canonical action-based `Git` tool (`status | diff | log | show | blame`); per-action legacy aliases have been removed
270 - `git_history.rs` - Read-only `git_log` / `git_show` / `git_blame`
271 - `github/` - Unified `github` tool family (read-only context plus guarded
272 comment/closure actions backed by `gh`); deferred by default and
273 discoverable on demand
274 - `automation.rs` - Model-visible scheduling tools over `AutomationManager`
275 - `plan.rs` - Planning tools
276 - `subagent/` - Sub-agent launch and supervision. `agent` is the only
277 sub-agent tool; `subagent/coord.rs` holds the handlers its message,
278 followup, interrupt, claim and release actions dispatch to over the
279 existing manager. The `agent_open`/`agent_eval`/`agent_close` lifecycle
280 surface was retired (see the `subagent/coord.rs` module doc)
281 - `spec.rs` - Tool specifications
282 - `rlm.rs` - Persistent Recursive Language Model (RLM) sessions — persistent local Python REPL subprocesses (started through the same sandboxed launcher as `code_execution`, environment-scrubbed) with semantic helper calls and `var_handle` output support
283
284 ### Extension Systems
285
286 - **`mcp.rs`** - Model Context Protocol client for external tool servers
287 - **`skills/`** - Skill discovery and registry for local `SKILL.md` files, plus audit and mutation (the installer lives in `crates/skill-install`; plugin loading lives in `crates/plugins`)
288 - **`hooks.rs`** - Pre/post execution hooks with conditions
289
290 ### User Interface
291
292 - **`tui/`** - Terminal UI components (ratatui-based; this is a representative
293 list, not exhaustive - the module has grown to 80+ focused files):
294 - `app.rs` - Application state and message handling
295 - `ui.rs` - Event handling, streaming state, and rendering logic
296 - `approval.rs` - Tool approval dialog
297 - `clipboard.rs` - Clipboard handling
298 - `underwater.rs` - Main shell chrome: status chips, mode labels, phase rail
299
300 ### LSP Integration
301
302 - **`lsp/`** - Post-edit diagnostics injection (#136)
303 - `mod.rs` - `LspManager` — lazy per-language transport pool + config
304 - `client.rs` - `StdioLspTransport` — JSON-RPC over stdio with `didOpen`/`didChange`/`publishDiagnostics`
305 - `diagnostics.rs` - Diagnostic types, severity, and HTML-block renderer
306 - `registry.rs` - Language detection and the default server map: `rust-analyzer`,
307 `gopls`, `pyright-langserver`, `typescript-language-server`, `jdtls`,
308 `intelephense` (PHP), `vue-language-server`, `clangd` (`lsp/registry.rs:98-110`)
309 - `approval.rs` - per-folder approval receipts; the manager checks trust and approval before every spawn
310 - Wired into the engine via `core/engine/lsp_hooks.rs` — called after every successful edit
311
312 ### Security
313
314 - **`crates/sandbox/src/`** - platform sandbox policy preparation and denial reporting
315 - `lib.rs` - Sandbox type definitions and manager
316 - `backend.rs` - Pluggable sandbox backend abstraction (routes shell
317 execution to a remote service, e.g. Alibaba OpenSandbox)
318 - `policy.rs` - Sandbox policy configuration
319 - `opensandbox.rs` - Alibaba OpenSandbox HTTP backend adapter
320 - `seatbelt.rs` - macOS Seatbelt profile generation
321 - `bwrap.rs` - Linux bubblewrap command wrapper
322 - `process_hardening.rs` - Startup Linux process hardening
323 - `read_guard.rs` - Shared protected-path read admission
324 - `shell_dispatcher.rs` - Shared shell detection and command construction
325 - `process_hardening.rs` - Linux kernel-level hardening for the TUI process
326 itself (defense-in-depth; not a child-command sandbox)
327 - `windows.rs` - Windows helper contract; not advertised until a Job
328 Object process-containment helper exists
329
330 ### Utilities
331
332 - **`utils.rs`** - Common utilities
333 - **`logging.rs`** - Logging infrastructure
334 - **`compaction.rs`** - Context compaction for long conversations
335 - **`purge.rs`** - Agent-driven context purging (surgical message removal/rewriting)
336 - **`pricing.rs`** - Cost estimation
337 - **`prompts.rs`** - System prompt templates
338 - **`runtime_api.rs`** - HTTP/SSE runtime API (`codewhale serve --http`)
339 - **`runtime_threads.rs`** - Durable thread/turn/item store + replayable event timeline
340 - **`task_manager.rs`** - Durable queue, worker pool, task timelines and artifacts
341
342 ## Data Flow
343
344 ### Interactive Session
345
346 1. User input received in TUI
347 2. Input processed by `core/engine.rs`
348 3. Message sent to LLM via `client.rs`
349 4. Response streamed back, parsed in `client.rs`
350 5. Tool calls extracted and executed via `tools/`
351 6. Hooks triggered before/after tool execution
352 7. Results aggregated and sent back to LLM
353 8. Final response rendered in TUI
354
355 ### Crash Recovery + Offline Queue
356
357 1. Before sending user input, the TUI writes a checkpoint snapshot to `~/.codewhale/sessions/checkpoints/latest.json`
358 2. Startup remains fresh by default; prior sessions are resumed explicitly via `--resume`/`--continue` (or `Ctrl+R` in TUI)
359 3. While degraded/offline, new prompts are queued in-memory and mirrored to `~/.codewhale/sessions/checkpoints/offline_queue.json`
360 4. Queue edits (`/queue ...`) are persisted continuously so drafts and queued prompts survive restarts. Messages restored from an earlier launch or another session are held: they are sent only by `/queue send <n>` and discarded by `/queue clear`
361 5. Successful turn completion clears the active checkpoint and writes a durable session snapshot
362 6. Action-capable turns also take pre/post-turn side-git workspace snapshots under `~/.codewhale/snapshots/<project_hash>/<worktree_hash>/.git`; `/restore N` and `revert_turn` restore file state without changing conversation history or the user's `.git`
363
364 ### Tool Execution
365
366 1. LLM requests tool via `tool_use` content block
367 2. Tool registry looks up handler
368 3. Pre-execution hooks run
369 4. Approval requested when the effective permission posture and policy require it
370 5. Tool executed (possibly wrapped by Seatbelt on macOS or bubblewrap on Linux)
371 6. Post-execution hooks run
372 7. Result metadata is retained on runtime item records
373 8. **LSP post-edit hook**: after a `File` write, edit, or patch action (including a replay-only legacy alias), the engine runs `run_post_edit_lsp_hook()` when LSP is enabled to collect diagnostics
374 9. **Diagnostics flush**: before the next API request, `flush_pending_lsp_diagnostics()` injects any collected errors as a synthetic user message
375 10. Result returned to agent loop
376
377 ### Background Tasks
378
379 1. Client enqueues task (`/task add ...` or `POST /v1/tasks`)
380 2. `task_manager.rs` persists task + queue entry under `~/.codewhale/tasks`
381 3. Worker picks queued task (bounded pool), transitions to `running`
382 4. Task creates/uses a runtime thread and starts a runtime turn
383 5. `runtime_threads.rs` persists thread/turn/item records + monotonic event sequence
384 6. Timeline/tool summaries/artifact references are persisted incrementally
385 7. Checklist state, verifier gates, PR attempts, and guarded GitHub events are applied from tool metadata to the active task
386 8. Final state (`completed|failed|canceled`) is durable and queryable via TUI/API
387
388 Model-visible durable task tools are a surface over this same manager. They do
389 not introduce a parallel work system: `task_create` enqueues normal tasks,
390 `checklist_*` updates task-local progress, `task_gate_run` and completed
391 `task_shell_wait` attach verification evidence, and automation runs enqueue
392 ordinary durable tasks.
393
394 ### Runtime Thread/Turn Timeline
395
396 1. API/TUI creates or resumes a thread (`/v1/threads*`)
397 2. Turn starts on the thread (`/v1/threads/{id}/turns`)
398 3. Engine events are mapped to item lifecycle events (`item.started|item.delta|item.completed`)
399 4. Interrupt/steer operations apply to the active turn only
400 5. Compaction (auto/manual) is emitted as `context_compaction` item lifecycle
401 6. Purge (agent-driven) is emitted as `context_purge` item lifecycle
402 7. Clients replay history and resume with `/v1/threads/{id}/events?since_seq=<n>`
403
404 ### Durable Schema Gates
405
406 - `session_manager.rs`, `runtime_threads.rs`, and `task_manager.rs` embed `schema_version` on persisted records.
407 - On load, newer schema versions are rejected with explicit errors instead of silently truncating/overwriting data.
408 - This allows safe forward migrations and prevents corruption when binaries and stored state are out of sync.
409
410 ## Extension Points
411
412 ### Adding a New Tool
413
414 1. Create handler in `tools/`
415 2. Register in `tools/registry.rs`
416 3. Add tool specification (name, description, input schema)
417
418 ### Adding an MCP Server
419
420 1. Configure in `~/.codewhale/mcp.json`
421 2. Server auto-discovered at startup
422 3. Tools exposed to LLM automatically
423
424 ### Creating a Skill
425
426 1. Create skill directory with `SKILL.md`
427 2. Define skill prompt and optional scripts
428 3. Place in a Codewhale-owned root (`~/.codewhale/skills/` or
429 `<workspace>/.codewhale/skills/`), or import from a compatible harness root
430 through `/skills`
431
432 See [SKILLS.md](SKILLS.md) for the Skills Manager, audit inventory, and the
433 rule that compatible roots (`.claude`, `.agents`, …) are never mutated in place.
434
435 ### Adding Hooks
436
437 Configure in `~/.codewhale/config.toml`:
438
439 ```toml
440 [[hooks]]
441 event = "tool_call_before"
442 command = "echo 'Running tool: $TOOL_NAME'"
443 ```
444
445 ## Key Design Decisions
446
447 1. **Streaming-first**: All LLM responses stream for responsiveness
448 2. **Tool safety**: Ask and Auto-Review require approval according to tool and
449 managed policy; Full Access removes ordinary prompts but not hard safety
450 holds. Side-effectful MCP tools use the same boundary.
451 3. **Extensibility**: MCP, skills, and hooks allow customization without code changes
452 4. **Cross-platform**: Core works on Linux/macOS/Windows. Sandbox guarantees
453 are platform-specific: macOS uses Seatbelt when available; Linux uses an
454 installed bubblewrap executable by default when a probe shows it works; Windows has
455 no advertised OS command sandbox. The Windows helper contract is not
456 wired into command execution.
457 5. **Minimal dependencies**: Careful dependency selection for build speed
458 6. **Local-first runtime API**: HTTP/SSE endpoints are intended for trusted localhost access and are served by the `crates/tui` runtime today
459 7. **Lock poison**: fail-stop by default. A poisoned lock means a holder
460 panicked mid-mutation, so `.expect()` with a message naming the lock is
461 the standard posture — never serve half-updated state. Recover with
462 `into_inner()` only where stale state is safe (caches, idempotent
463 rebuilds), with a comment saying why.
464
465 ## Configuration Files
466
467 - `~/.codewhale/config.toml` - Main configuration (`~/.deepseek/config.toml` is still read as a legacy fallback)
468 - `/etc/deepseek/managed_config.toml` - Optional managed defaults layer (Unix)
469 - `/etc/deepseek/requirements.toml` - Optional allowed-policy constraints (Unix)
470 - `~/.codewhale/mcp.json` - MCP server configuration
471 - `~/.codewhale/skills/` - User skills directory
472 - `~/.codewhale/sessions/` - Session history
473 - `~/.codewhale/sessions/checkpoints/` - Crash checkpoint + offline queue persistence
474 - `~/.codewhale/snapshots/` - Side-git pre/post-turn workspace snapshots for `/restore` and `revert_turn`
475 - `~/.codewhale/tasks/` - Background task records, queue, timelines, artifacts
476 - `~/.codewhale/audit.log` - Append-only security events: credential saves and clears, hook environment key names, compaction passes, goal completions, the terminal's approval routing, Auto-Review verdicts, and outbound network decisions when `[network]` auditing is on. Not an action record: it holds no commands or file changes, and app or `serve` turns write no approvals there. See `docs/RECEIPTS.md` for what a session did
477 - `~/.codewhale/sessions/<id>/approval_receipts.jsonl` - Every approval ask and decision for a session, including who decided
478
478 lines MARKDOWN