返回 CodeWhale
ARCHITECTURE.md
根目录 / docs / ARCHITECTURE.md
1 # Codewhale Architecture
2
3 This document provides an overview of the codewhale architecture for developers and contributors.
4
5 Current boundary note (read the workspace version from `Cargo.toml`; this
6 boundary has held since v0.9.1):
7 - `crates/tui` is still the live end-user runtime for the TUI, runtime API, task manager, and tool execution loop.
8 - Other workspace crates are being split out incrementally, but they are not yet the sole runtime source of truth.
9 - The LSP subsystem (`crates/tui/src/lsp/`) is fully wired into the engine's
10 post-tool-execution path (`core/engine/lsp_hooks.rs`), providing inline
11 diagnostics after `File` write, edit, and patch actions.
12 - The swarm agent system was removed in v0.8.5. The active sub-agent surface is
13 the single `agent` tool; persistent RLM sessions are available through the
14 deferred `rlm` action family.
15 No model-visible swarm tool remains in the active codebase.
16
17 ## High-Level Overview
18
19 ```
20 ┌─────────────────────────────────────────────────────────────────┐
21 │ User Interface │
22 │ ┌─────────────────┐ ┌─────────────────┐ ┌────────────────┐ │
23 │ │ TUI (ratatui) │ │ One-shot Mode │ │ Config/CLI │ │
24 │ └────────┬────────┘ └────────┬────────┘ └────────┬───────┘ │
25 └───────────┼─────────────────────┼────────────────────┼──────────┘
26 │ │ │
27 ▼ ▼ ▼
28 ┌─────────────────────────────────────────────────────────────────┐
29 │ Core Engine │
30 │ ┌─────────────────────────────────────────────────────────┐ │
31 │ │ Agent Loop (core/engine.rs) │ │
32 │ │ ┌─────────┐ ┌─────────────┐ ┌──────────────────────┐ │ │
33 │ │ │ Session │ │ Turn Mgmt │ │ Tool Orchestration │ │ │
34 │ │ └─────────┘ └─────────────┘ └──────────────────────┘ │ │
35 │ └─────────────────────────────────────────────────────────┘ │
36 └─────────────────────────────────────────────────────────────────┘
37 │ │ │
38 ▼ ▼ ▼
39 ┌─────────────────────────────────────────────────────────────────┐
40 │ Tool & Extension Layer │
41 │ ┌──────────┐ ┌──────────┐ ┌─────────┐ ┌────────────────┐ │
42 │ │ Tools │ │ Skills │ │ Hooks │ │ MCP Servers │ │
43 │ │ (shell, │ │ (plugins)│ │ (pre/ │ │ (external) │ │
44 │ │ file) │ │ │ │ post) │ │ │ │
45 │ └──────────┘ └──────────┘ └─────────┘ └────────────────┘ │
46 └─────────────────────────────────────────────────────────────────┘
47 │ │ │
48 ▼ ▼ ▼
49 ┌─────────────────────────────────────────────────────────────────┐
50 │ Runtime API + Task Management │
51 │ ┌─────────────────────────────┐ ┌──────────────────────────┐ │
52 │ │ HTTP/SSE Runtime API │ │ Persistent Task Manager │ │
53 │ │ (runtime_api.rs) │ │ (task_manager.rs) │ │
54 │ └─────────────────────────────┘ └──────────────────────────┘ │
55 └─────────────────────────────────────────────────────────────────┘
56 │ │
57 ▼ ▼
58 ┌─────────────────────────────────────────────────────────────────┐
59 │ LLM Layer │
60 │ ┌──────────────────────────────────────────────────────────┐ │
61 │ │ LLM Client Layer (client.rs) │ │
62 │ │ ┌──────────────────┐ ┌─────────────────────────────┐ │ │
63 │ │ │ OpenAI-compatible │ │ Anthropic / Responses │ │ │
64 │ │ │ (chat adapter) │ │ (adapters) │ │ │
65 │ │ └──────────────────┘ └─────────────────────────────┘ │ │
66 │ └──────────────────────────────────────────────────────────┘ │
67 └─────────────────────────────────────────────────────────────────┘
68 ```
69
70 ## Module Organization
71
72 ### Entry Point
73
74 - **`main.rs`** - CLI argument parsing (clap), configuration loading, entry point routing
75
76 ### Core Components
77
78 - **`core/`** - Main engine components
79 - `engine.rs` - Engine state, operation handling, message processing
80 - `engine/turn_loop.rs` - Streaming turn loop and tool execution orchestration
81 - `session.rs` - Session state management
82 - `turn.rs` - Turn-based conversation handling
83 - `events.rs` - Event system for UI updates
84 - `ops.rs` - Core operations
85
86 ### Configuration
87
88 - **`config.rs`** - Configuration loading, profiles, environment variables
89 - **`settings.rs`** - Runtime settings management
90
91 ### Workspace Crates
92
93 - **`crates/tools`** - Shared tool invocation primitives, including tool result/error/capability types used by the TUI runtime.
94 - **`crates/agent`** - Model/provider registry (ModelRegistry) for resolving model IDs to provider endpoints.
95 - **`crates/app-server`** - HTTP/SSE + JSON-RPC app server transport for
96 headless agent workflows. Note that `app-server --http`/`--mobile` delegate
97 to the TUI binary, which is where the runtime API actually lives.
98 - **`crates/config`** - Config loading, profiles, environment variable precedence, CLI runtime overrides.
99 - **`crates/core`** - Provider-neutral request construction (`request.rs`),
100 bounded context fragments, the tool-call parser, and thread/session types.
101 It does **not** own the agent loop: the live turn loop is
102 `Engine::run_turn` in `crates/tui/src/core/engine/turn_loop.rs`, and
103 `crates/tui/src/core/` is a module inside the TUI crate, not this crate. A
104 placeholder `engine/` tree here once suggested otherwise — it had no callers
105 and emitted `TurnComplete` without contacting a model — and was removed in
106 v0.9.11 so there is exactly one turn loop in the workspace.
107 - **`crates/execpolicy`** - Approval/sandbox policy engine for tool execution decisions.
108 - **`crates/hooks`** - Lifecycle hooks (stdout, jsonl, webhook) for pre/post tool events.
109 - **`crates/mcp`** - MCP client + stdio server for Model Context Protocol tool servers.
110 - **`crates/protocol`** - Request/response framing and protocol types.
111 - **`crates/secrets`** - OS keyring integration for API key storage.
112 - **`crates/state`** - SQLite thread/session persistence layer.
113 - **`crates/workflow`** / **`crates/workflow-js`** - Workflow engine and its
114 QuickJS scripting layer (renamed from the whaleflow crates).
115 - **`crates/lane`** - Lane runtime: durable, attachable running instances of
116 Fleet/Workflow work (`codewhale lane list/status/attach/logs/stop`).
117 - **`crates/release`** / **`crates/build-support`** - Release checks and build
118 plumbing.
119
120 ### LLM Integration
121
122 - **`client.rs`** - The live HTTP client layer: OpenAI-compatible, Anthropic,
123 and Responses wire adapters, DeepSeek request-boundary handling, retry
124 policy, and streaming. Provider routes land here through the shared config
125 and catalog layers.
126 - **`llm_client/`** - LLM client trait, retry logic, and error classification
127 (`LlmClient`, `RetryConfig`, `with_retry`) consumed by `client.rs`; `mock.rs`
128 is test-only (`#[cfg(test)]`).
129 - **`models.rs`** - Data structures for API requests/responses
130
131 #### DeepSeek API Endpoints
132
133 DeepSeek exposes OpenAI-compatible endpoints. The first-party route uses:
134 - `https://api.deepseek.com/beta` - default DeepSeek base URL (`provider_defaults.rs`)
135 - `https://api.deepseek.com/beta/models` - live model discovery and health checks
136
137 `https://api.deepseek.com/v1` is accepted for OpenAI SDK compatibility, and
138 can still be configured explicitly to opt out of beta-only features such as
139 strict tool mode, chat prefix completion, and FIM completion. The public
140 DeepSeek docs do not document a Responses API path for this workflow; the engine
141 drives turns through Chat Completions.
142
143 ### Tool System
144
145 - **`tools/`** - Built-in tool implementations
146 - `mod.rs` - Tool registry and common types
147 - `shell.rs` - Shell command execution
148 - `file.rs` - File read/write operations
149 - `todo.rs` - Checklist tools plus legacy todo aliases
150 - `tasks.rs` - Model-visible durable task, gate, background shell, and PR-attempt tools
151 - `git.rs` - Read-only `git_status` / `git_diff` inspection wrappers
152 - `git_tool.rs` - The canonical action-based `Git` tool (`status | diff | log | show | blame`); per-action legacy aliases were removed in v0.9.3
153 - `git_history.rs` - Read-only `git_log` / `git_show` / `git_blame`
154 - `github/` - Unified `github` tool family (read-only context plus guarded
155 comment/closure actions backed by `gh`); deferred by default and
156 discoverable through `tool_search`
157 - `automation.rs` - Model-visible scheduling tools over `AutomationManager`
158 - `plan.rs` - Planning tools
159 - `subagent/` - Sub-agent launch and supervision. The one model-facing tool
160 is `agent`; the `agent_open`/`agent_eval`/`agent_close` lifecycle surface
161 was retired (see `subagent/coord.rs:5`)
162 - `spec.rs` - Tool specifications
163 - `rlm.rs` - Persistent Recursive Language Model (RLM) sessions — sandboxed Python REPLs with semantic helper calls and `var_handle` output support
164
165 ### Extension Systems
166
167 - **`mcp.rs`** - Model Context Protocol client for external tool servers
168 - **`skills.rs`** - Plugin/skill loading and execution
169 - **`hooks.rs`** - Pre/post execution hooks with conditions
170
171 ### User Interface
172
173 - **`tui/`** - Terminal UI components (ratatui-based; this is a representative
174 list, not exhaustive - the module has grown to 80+ focused files):
175 - `app.rs` - Application state and message handling
176 - `ui.rs` - Event handling, streaming state, and rendering logic
177 - `approval.rs` - Tool approval dialog
178 - `clipboard.rs` - Clipboard handling
179 - `underwater.rs` - Main shell chrome: status chips, mode labels, phase rail
180
181 ### LSP Integration
182
183 - **`lsp/`** - Post-edit diagnostics injection (#136)
184 - `mod.rs` - `LspManager` — lazy per-language transport pool + config
185 - `client.rs` - `StdioLspTransport` — JSON-RPC over stdio with `didOpen`/`didChange`/`publishDiagnostics`
186 - `diagnostics.rs` - Diagnostic types, severity, and HTML-block renderer
187 - `registry.rs` - Language detection and the default server map: `rust-analyzer`,
188 `gopls`, `pyright-langserver`, `typescript-language-server`, `jdtls`,
189 `intelephense` (PHP), `vue-language-server`, `clangd` (`lsp/registry.rs:98-110`)
190 - Wired into the engine via `core/engine/lsp_hooks.rs` — called after every successful edit
191
192 ### Security
193
194 - **`sandbox/`** - platform sandbox policy preparation and denial reporting
195 - `mod.rs` - Sandbox type definitions
196 - `backend.rs` - Pluggable sandbox backend abstraction (routes shell
197 execution to a remote service, e.g. Alibaba OpenSandbox)
198 - `policy.rs` - Sandbox policy configuration
199 - `opensandbox.rs` - Alibaba OpenSandbox HTTP backend adapter
200 - `seatbelt.rs` - macOS Seatbelt profile generation
201 - `bwrap.rs` - opt-in Linux bubblewrap command wrapper
202 - `seccomp.rs` - dormant Linux seccomp implementation; not wired into commands
203 - `process_hardening.rs` - Linux kernel-level hardening for the TUI process
204 itself (defense-in-depth; not a child-command sandbox)
205 - `windows.rs` - Windows helper contract; not advertised until a Job
206 Object process-containment helper exists
207
208 ### Utilities
209
210 - **`utils.rs`** - Common utilities
211 - **`logging.rs`** - Logging infrastructure
212 - **`compaction.rs`** - Context compaction for long conversations
213 - **`purge.rs`** - Agent-driven context purging (surgical message removal/rewriting)
214 - **`pricing.rs`** - Cost estimation
215 - **`prompts.rs`** - System prompt templates
216 - **`runtime_api.rs`** - HTTP/SSE runtime API (`codewhale serve --http`)
217 - **`runtime_threads.rs`** - Durable thread/turn/item store + replayable event timeline
218 - **`task_manager.rs`** - Durable queue, worker pool, task timelines and artifacts
219
220 ## Data Flow
221
222 ### Interactive Session
223
224 1. User input received in TUI
225 2. Input processed by `core/engine.rs`
226 3. Message sent to LLM via `client.rs`
227 4. Response streamed back, parsed in `client.rs`
228 5. Tool calls extracted and executed via `tools/`
229 6. Hooks triggered before/after tool execution
230 7. Results aggregated and sent back to LLM
231 8. Final response rendered in TUI
232
233 ### Crash Recovery + Offline Queue
234
235 1. Before sending user input, the TUI writes a checkpoint snapshot to `~/.codewhale/sessions/checkpoints/latest.json`
236 2. Startup remains fresh by default; prior sessions are resumed explicitly via `--resume`/`--continue` (or `Ctrl+R` in TUI)
237 3. While degraded/offline, new prompts are queued in-memory and mirrored to `~/.codewhale/sessions/checkpoints/offline_queue.json`
238 4. Queue edits (`/queue ...`) are persisted continuously so drafts and queued prompts survive restarts
239 5. Successful turn completion clears the active checkpoint and writes a durable session snapshot
240 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`
241
242 ### Tool Execution
243
244 1. LLM requests tool via `tool_use` content block
245 2. Tool registry looks up handler
246 3. Pre-execution hooks run
247 4. Approval requested when the effective permission posture and policy require it
248 5. Tool executed (possibly wrapped by Seatbelt on macOS or opt-in bubblewrap on Linux)
249 6. Post-execution hooks run
250 7. Result metadata is retained on runtime item records
251 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
252 9. **Diagnostics flush**: before the next API request, `flush_pending_lsp_diagnostics()` injects any collected errors as a synthetic user message
253 10. Result returned to agent loop
254
255 ### Background Tasks
256
257 1. Client enqueues task (`/task add ...` or `POST /v1/tasks`)
258 2. `task_manager.rs` persists task + queue entry under `~/.codewhale/tasks`
259 3. Worker picks queued task (bounded pool), transitions to `running`
260 4. Task creates/uses a runtime thread and starts a runtime turn
261 5. `runtime_threads.rs` persists thread/turn/item records + monotonic event sequence
262 6. Timeline/tool summaries/artifact references are persisted incrementally
263 7. Checklist state, verifier gates, PR attempts, and guarded GitHub events are applied from tool metadata to the active task
264 8. Final state (`completed|failed|canceled`) is durable and queryable via TUI/API
265
266 Model-visible durable task tools are a surface over this same manager. They do
267 not introduce a parallel work system: `task_create` enqueues normal tasks,
268 `checklist_*` updates task-local progress, `task_gate_run` and completed
269 `task_shell_wait` attach verification evidence, and automation runs enqueue
270 ordinary durable tasks.
271
272 ### Runtime Thread/Turn Timeline
273
274 1. API/TUI creates or resumes a thread (`/v1/threads*`)
275 2. Turn starts on the thread (`/v1/threads/{id}/turns`)
276 3. Engine events are mapped to item lifecycle events (`item.started|item.delta|item.completed`)
277 4. Interrupt/steer operations apply to the active turn only
278 5. Compaction (auto/manual) is emitted as `context_compaction` item lifecycle
279 6. Purge (agent-driven) is emitted as `context_purge` item lifecycle
280 7. Clients replay history and resume with `/v1/threads/{id}/events?since_seq=<n>`
281
282 ### Durable Schema Gates
283
284 - `session_manager.rs`, `runtime_threads.rs`, and `task_manager.rs` embed `schema_version` on persisted records.
285 - On load, newer schema versions are rejected with explicit errors instead of silently truncating/overwriting data.
286 - This allows safe forward migrations and prevents corruption when binaries and stored state are out of sync.
287
288 ## Extension Points
289
290 ### Adding a New Tool
291
292 1. Create handler in `tools/`
293 2. Register in `tools/registry.rs`
294 3. Add tool specification (name, description, input schema)
295
296 ### Adding an MCP Server
297
298 1. Configure in `~/.codewhale/mcp.json`
299 2. Server auto-discovered at startup
300 3. Tools exposed to LLM automatically
301
302 ### Creating a Skill
303
304 1. Create skill directory with `SKILL.md`
305 2. Define skill prompt and optional scripts
306 3. Place in a Codewhale-owned root (`~/.codewhale/skills/` or
307 `<workspace>/.codewhale/skills/`), or import from a compatible harness root
308 through `/skills`
309
310 See [SKILLS.md](SKILLS.md) for the Skills Manager, audit inventory, and the
311 rule that compatible roots (`.claude`, `.agents`, …) are never mutated in place.
312
313 ### Adding Hooks
314
315 Configure in `~/.codewhale/config.toml`:
316
317 ```toml
318 [[hooks]]
319 event = "tool_call_before"
320 command = "echo 'Running tool: $TOOL_NAME'"
321 ```
322
323 ## Key Design Decisions
324
325 1. **Streaming-first**: All LLM responses stream for responsiveness
326 2. **Tool safety**: Ask and Auto-Review require approval according to tool and
327 managed policy; Full Access removes ordinary prompts but not hard safety
328 holds. Side-effectful MCP tools use the same boundary.
329 3. **Extensibility**: MCP, skills, and hooks allow customization without code changes
330 4. **Cross-platform**: Core works on Linux/macOS/Windows. Sandbox guarantees
331 are platform-specific: macOS uses Seatbelt when available; Linux uses an
332 installed bubblewrap executable only when explicitly enabled; Windows has
333 no advertised OS command sandbox. Seccomp and the Windows helper contract
334 are not wired into command execution.
335 5. **Minimal dependencies**: Careful dependency selection for build speed
336 6. **Local-first runtime API**: HTTP/SSE endpoints are intended for trusted localhost access and are served by the `crates/tui` runtime today
337 7. **Lock poison**: fail-stop by default. A poisoned lock means a holder
338 panicked mid-mutation, so `.expect()` with a message naming the lock is
339 the standard posture — never serve half-updated state. Recover with
340 `into_inner()` only where stale state is safe (caches, idempotent
341 rebuilds), with a comment saying why.
342
343 ## Configuration Files
344
345 - `~/.codewhale/config.toml` - Main configuration (`~/.deepseek/config.toml` is still read as a legacy fallback)
346 - `/etc/deepseek/managed_config.toml` - Optional managed defaults layer (Unix)
347 - `/etc/deepseek/requirements.toml` - Optional allowed-policy constraints (Unix)
348 - `~/.codewhale/mcp.json` - MCP server configuration
349 - `~/.codewhale/skills/` - User skills directory
350 - `~/.codewhale/sessions/` - Session history
351 - `~/.codewhale/sessions/checkpoints/` - Crash checkpoint + offline queue persistence
352 - `~/.codewhale/snapshots/` - Side-git pre/post-turn workspace snapshots for `/restore` and `revert_turn`
353 - `~/.codewhale/tasks/` - Background task records, queue, timelines, artifacts
354 - `~/.codewhale/audit.log` - Append-only audit events for credential + approval/elevation actions
355
355 lines MARKDOWN