返回 CodeWhale
RUNTIME_OWNERSHIP_DESIGN.md
根目录 / docs / design / RUNTIME_OWNERSHIP_DESIGN.md
1 # Runtime Ownership and Frontend Lifecycle Design
2
3 **Status:** Partially implemented (Phase A: store-derived control sockets) +
4 workspace drive-lease design below (§11). Decision record: per-client topology
5 ("Plan C" — A's mechanism, client-specific defaults), not single-owner-everywhere
6 ("Plan B"). Written against `wave/0.10.1-next` (`5cf09da77` and descendants).
7
8
9 This is a design record, not a claim that every phase is implemented. This PR
10 adds Unix control sockets for an explicit canonical runtime-directory override
11 and a shared workspace lease at Runtime API scope admission. Existing store,
12 principal, config, worker and workspace checks remain authoritative. Detached
13 owner election, scope retirement, standalone TUI/turn/CLI lease admission and
14 store-derived Windows pipe names remain follow-up work. Existing Windows named
15 pipe transport and owner recovery are retained.
16
17 **Audience:** Engine runtime maintainers, desktop client, web client, VS Code
18 extension owners.
19
20 **Problem in one line:** 0.10.1 gave the engine an authenticated single-owner
21 control plane, but left every client spawning self-contained engines — so two
22 legitimate clients of the same user now refuse each other
23 (`authenticated Runtime owner belongs to another selected store`).
24
25 ---
26
27 ## 1. What actually broke, precisely
28
29 The 0.10.1 owner model resolved two identities from **disjoint inputs**:
30
31 | Identity | Resolved from | Code |
32 |---|---|---|
33 | Runtime store (data_dir, execution_scope) | `CODEWHALE_RUNTIME_DIR` / `DEEPSEEK_RUNTIME_DIR`, else `default_tasks_dir()/runtime` | `runtime_threads.rs:runtime_dir_override`, `default_runtime_store_root` |
34 | Control plane (socket path) | explicit flag > `CODEWHALE_HOME/run` > `XDG_RUNTIME_DIR` > OS app-support default | `daemon_socket.rs:resolve_socket_path` |
35
36 A `serve` that finds a live owner on the socket compares the owner's receipt
37 store against its **own** store selection
38 (`runtime_api.rs:validate_selected_owner`). Same store → attach as a frontend.
39 Different store → exit 1. Store choice is client input; socket choice is not a
40 function of it; therefore two clients of the same user on one machine can
41 trivially construct a mismatch. The refusal is the correct *security* outcome
42 of an inconsistent *topology* model — the engine can't tell "another user's
43 engine" from "my user's other window", because nothing relates the two
44 identities.
45
46 The second structural flaw: **the owner is a child of whichever client won the
47 election.** The VS Code extension stops its child when the window closes
48 ("Stopping the engine started by this window"). Under a shared-owner model
49 that kills the engine hosting every other window's listeners. Ownership that
50 outlives frontends cannot live inside a frontend's process tree.
51
52 Everything needed to fix this already exists in 0.10.1 and is merely
53 under-composed:
54
55 - workspace scopes inside one owner (≤64, canonical-path verified, per-scope
56 MCP/LSP/worker admission) — `RuntimeWorkspaceScopes`;
57 - guest-requested listeners bound inside the owner with the **guest's own**
58 auth token, workspace, CORS, web/mobile flags — `RuntimeListenerSelection`;
59 - the attach stdout compatibility line (`Runtime API listening on …`) so a
60 guest child is indistinguishable from a standalone engine to a spawning
61 client — `run_attached_frontend`;
62 - stale-socket reclaim, peer-uid checks, receipt re-validation, version-skew
63 guard, lease generations.
64
65 ## 2. Design invariants
66
67 1. **One owner process per runtime boundary.** Not per window, not per
68 workspace, not per user-machine (see §3 for when a user legitimately has
69 several).
70 2. **Control-plane identity is a pure function of runtime identity.** The
71 socket path is derived from the same inputs that select the store. Same
72 boundary ⇒ same socket ⇒ the store always matches; different boundary ⇒
73 different socket ⇒ different owner, and the mismatch refusal becomes
74 structurally unreachable except for genuine races.
75 3. **The owner is nobody's child.** Election daemonizes the owner; every
76 client — including the one that triggered election — attaches as a guest.
77 No client's exit can take the engine down.
78 4. **Clients attach; they never demand a store.** `CODEWHALE_RUNTIME_DIR`
79 stops being a per-window workaround and becomes an explicit boundary
80 selector (isolation for CI, tests, experiments).
81 5. **Workspace multiplicity lives inside the owner.** A window is a frontend
82 scope over one workspace; threads carry their workspace; one store serves
83 all of them (this is already how the shared store filters per workspace).
84 6. **Engine lifetime is decoupled from any single client**: idle retirement
85 with a grace period, blocked by active turns/tasks/automations or an
86 explicit `linger` holder.
87 7. **Refusals are typed protocol outcomes** reserved for true races, version
88 skew, and trust denials — never for legitimate topology.
89
90 ## 3. The runtime boundary
91
92 A **boundary** is the tuple of everything that must be identical for two
93 engine processes to be interchangeable hosts of the same store. The key
94 insight: hash the **resolved store root**, not the env vars that produced it —
95 otherwise any input the store chain reads but the tuple omits (`DEEPSEEK_TASKS_DIR`
96 in the fallback chain) silently forks a second owner:
97
98 | Input | Canonicalization |
99 |---|---|
100 | Home root (`CODEWHALE_HOME` / default) | resolved absolute path |
101 | **Resolved runtime store root** (env overrides `CODEWHALE_RUNTIME_DIR`/`DEEPSEEK_RUNTIME_DIR`, else the tasks-dir fallback chain, all canonicalized) | canonical absolute path |
102 | Config source (`--config` / loaded path) | `canonical_runtime_config_source` |
103 | Config profile (`--profile` / env) | literal |
104 | ACP-only base (`serve --acp`) | boolean |
105
106 `boundary_id = sha256(canonical(serialization))[0..12]`.
107
108 Socket layout (unix; macOS path budget is 103 bytes — verified
109 `MAX_SOCKET_PATH_BYTES` — and this fits with room to spare):
110
111 - Default boundary (no overrides, default profile): **today's well-known
112 path stays** (`~/Library/Application Support/codewhale/daemon.sock` on
113 macOS, `$XDG_RUNTIME_DIR/codewhale/daemon.sock`, …). Discovery and doctor
114 keep one obvious place to look.
115 - Non-default boundaries: a **sibling** of the default socket in the same
116 0700 parent — `<default socket's parent>/b-<boundary_id>.sock`
117 (macOS ≈ 56 bytes, well inside the 103-byte kernel budget).
118 Receipts continue to ride beside their socket (`<name>.owner.json`), so
119 publication, re-validation, and stale reclaim work unchanged per socket.
120 - Windows (named-pipe transport exists; store-derived naming is deferred): the derived pipe
121 name is `\\.\pipe\codewhale-daemon-<boundary_id>`; follow-up work.
122
123 Consequences for today's refusal paths:
124
125 | Today's check | Becomes |
126 |---|---|
127 | `authenticated Runtime owner belongs to another selected store` | Unreachable: store and socket derive from the same tuple |
128 | `selected config profile differs from the captured owner scope` | Unreachable on the same socket: profile is part of the boundary; a different profile lands on a different socket (a deliberate second engine, not a refusal) |
129 | `selected worker setting differs from the held scheduler` | A typed control error (`owner_scheduler_mismatch`) carrying the owner's setting; the receipt advertises `workers`; clients retry with it. The scheduler is per-owner, first election wins |
130 | `stale owner receipt belongs to a different selected store` | Unreachable: a receipt at a given socket can only belong to that boundary |
131 | Version skew, owner-died-mid-attach, trust denial | Remain — these are genuine races/skew |
132
133 Scope cap: `MAX_RUNTIME_WORKSPACE_SCOPES = 64` stays, but scopes stop being
134 "retained until owner retirement" (today's wart: *restart the owner to retire
135 unused scopes*). See §4.
136
137 ## 4. Owner and frontend lifecycle
138
139 ### States
140
141 ```
142 absent → electing → ready ⇄ serving → draining → retired
143 ```
144
145 - **electing:** bind the boundary socket (kernel-atomic election; losers
146 probe, find the winner, and attach). Stale reclaim (dead socket, refused
147 connection) is existing behavior.
148 - **ready:** store opened under its process-owner lock, receipt published,
149 scheduler and task manager started, first workspace scope admitted.
150 - **serving:** frontends attach/detach; each attachment gets
151 `daemon/frontend_ready` with its endpoint (reused listener or a
152 guest-requested one carrying the guest's token).
153 - **draining:** stop admitting; let accepted turns finish (existing
154 `shutdown_and_wait` semantics); release the store lock; retire socket and
155 receipt.
156 - **retired:** nothing on disk claims ownership; the next client re-elects.
157
158 ### Election daemonizes
159
160 The client that wins election does not *stay* the owner as a child of the
161 client's process tree. The elected `serve` re-execs a detached supervisor
162 (single child, reparented to the OS, stdio closed) which opens the store and
163 publishes the receipt; the original child then attaches like any guest. Every
164 frontend is therefore killable by its own client with zero engine-wide
165 blast radius. The VS Code extension's "stop the engine started by this
166 window" keeps meaning exactly "stop *my* frontend".
167
168 ### Idle retirement
169
170 The owner retires when, for a configurable grace (default 60 s):
171
172 - zero live frontend connections,
173 - no accepted turns, running tasks, or due/running automations,
174 - no `linger` holder.
175
176 `linger` is an attach-mode property, not a flag only the desktop knows:
177 a desktop app attaches a pure control connection with linger for
178 app-lifetime; an account-owned remote-control session (mobile/web remote)
179 holds linger while active; automations due within the grace block retirement
180 on their own. Retirement is graceful drain, never SIGKILL.
181
182 ### Crash and recovery
183
184 An owner crash EOFs every guest's control connection. Guest children
185 re-run election (one winner), re-attach, and re-request their listeners.
186 Accepted turns in flight at crash are lost — that is the honest cost of one
187 owner; stores, events, and receipts are durable, so recovery is
188 re-elect → re-attach → reload thread state, all idempotent (scope admission
189 re-canonicalizes the workspace; listener admission is a fresh bind).
190 Guest children may print a **new** `Runtime API listening on …` line after
191 re-election; clients treat every matching line as the current endpoint, not
192 just the first (extension change, §5.3).
193
194 ### Upgrades
195
196 Version skew already refuses cross-version attach. Add one control
197 operation, `daemon/drain_restart`: the desktop (or CLI) tells the owner to
198 drain and exit, then starts the new binary and lets frontends re-attach.
199 No orphaned sockets: drain is the same path as retirement.
200
201 ### Scope retirement
202
203 Workspace scopes refcount live frontend attachments; on last detach the
204 scope's MCP/LSP pools close and the scope slot frees after the same grace.
205 Disk state (items, events) stays; re-admission is cheap. The 64-cap now
206 bounds *concurrent* workspaces, not lifetime workspaces.
207
208 ## 5. Client contracts
209
210 All clients speak the same three verbs: **find** (connect boundary socket),
211 **elect** (spawn detached owner if absent), **attach** (frontend scope +
212 listener selection). Nothing else.
213
214 ### 5.1 Desktop (canonical consumer)
215
216 Attaches over the control socket directly — JSON-RPC control transport, no
217 TCP hop, one connection per window, one linger connection for the app.
218 Orchestrates upgrades via `daemon/drain_restart`. Surfaces owner facts
219 (pid, version, boundary, scopes, frontends, uptime) in its status UI from
220 the receipt plus a `daemon/status` read.
221
222 ### 5.2 Web (`codewhale web`)
223
224 Finds/elects the default boundary, attaches a web frontend. Bootstrap-nonce
225 URLs are per-attachment (existing `web_bootstrap_url`). Multi-tab is N SSE
226 connections to one listener — never N engines.
227
228 ### 5.3 VS Code extension
229
230 Keeps its child-per-window shape — the compat line makes a guest child look
231 identical to a standalone engine — but the child attaches to the default
232 boundary instead of demanding a private store:
233
234 - stop setting `CODEWHALE_RUNTIME_DIR` **and** `DEEPSEEK_TASKS_DIR` on
235 engines ≥ 0.10 — the runtime-dir override was the isolation workaround,
236 and the tasks-dir env forks the resolved store root (hence the boundary);
237 tasks land in the user-level tasks dir, which is what `codewhale doctor`
238 and receipts already read;
239 - one-time version probe (`codewhale --version`) chooses the strategy:
240 ≥ 0.10 → attach; < 0.10 → legacy per-workspace store (current 0.8.3
241 behavior, which is correct for the old one-process-per-store model);
242 - accept repeated `Runtime API listening on` lines (re-election) and update
243 the base URL;
244 - surface typed attach failures verbatim instead of
245 `Engine exited before becoming ready`;
246 - add a "Codewhale: engine status" command (doctor owner panel: boundary,
247 socket, pid, scopes, frontends) and "Codewhale: restart engine"
248 (`daemon/drain_restart`).
249
250 Window close kills only the guest child; its listener drains in the owner;
251 other windows are untouched. Same-workspace-in-two-windows now works (same
252 scope, two listeners, two tokens).
253
254 ### 5.4 ACP (`serve --acp`)
255
256 An ACP base owner is immutable by design (`acp_only`); in this design it is
257 simply its own boundary (the acp-only bit is in the tuple), so Zed sessions
258 never collide with the interactive owner and never attach into it.
259
260 ### 5.5 Mobile / remote control
261
262 Account-owned remote control attaches to the default boundary with
263 watch/drive device-token intents (existing) and holds linger while a remote
264 session is live. Nothing new.
265
266 ### 5.6 Interactive TUI, `exec`, MCP stdio — explicit non-goals
267
268 The interactive TUI keeps its per-session store (`for_session`), `exec`
269 stays a one-shot worker, `serve --mcp` stays stdio-scoped. They are not
270 frontends of the owner and must not become so implicitly; the boundary model
271 governs the `app-server`/`serve` daemon family only. (A future where the
272 TUI attaches as a frontend is possible but is not this design.)
273
274 ## 6. Security
275
276 Kept unchanged: peer-uid checks, 0600/0700, per-connection receipts that are
277 never bearers, loopback-only default binds, per-listener guest tokens,
278 constant-time token comparison, canonical workspace verification
279 (`O_DIRECTORY|O_NOFOLLOW` + same-file identity), device-token intents.
280
281 Added or sharpened:
282
283 - **Boundary hashing uses canonical inputs only** — a symlinked config path
284 or non-canonical runtime dir must not fork a second owner silently.
285 - **Workspace admission is an engine-side trust decision**: scope admission
286 consults project trust (`[projects]` in config); an untrusted workspace's
287 first attach surfaces an approval (the engine already runs approvals; the
288 extension's VS Code-side trust is a client precondition, not the
289 engine's).
290 - **Audit events** for `owner_elected`, `scope_admitted`, `frontend_attached`,
291 `frontend_detached`, `owner_retired` land in the boundary store's event
292 log — the owner election stops being observable only through
293 `engine.log`.
294 - Derived sockets live under the same 0700 parent as the default socket; no
295 new world-writable surface. Hash collision on a derived socket shows up as
296 a receipt mismatch → refuse (the true-race class).
297
298 ## 7. Mechanism changes (touchpoints)
299
300 Phase 1 — engine, identity + typed errors (no client changes required):
301
302 - `daemon_socket.rs`: extend `SocketPathInputs` with the runtime-dir override
303 and config profile/source; derive non-default socket names from
304 `boundary_id`; keep the default path for the default boundary.
305 - `runtime_api.rs`: `validate_selected_owner` loses the store-compare (now
306 structurally guaranteed) and keeps pid/lease/principal checks; worker
307 mismatch becomes a typed control error; scheduler setting joins the
308 receipt.
309 - Election daemonization: a detached re-exec path in `serve` startup
310 (`--supervise-owner` internal flag); guest children always attach.
311 - Scope refcounting + grace retirement in `RuntimeWorkspaceScopes`; idle
312 retirement loop honoring turns/tasks/automations/linger.
313 - `doctor`: owner panel (boundary, socket, receipt, scopes, frontends).
314
315 Phase 2 — extension migration (version probe, drop per-workspace runtime
316 dir, repeated-line handling, status/restart commands, typed error surface).
317
318 Phase 3 — desktop/web speak control-protocol attach directly; linger;
319 `daemon/drain_restart`; `daemon/status`.
320
321 Phase 4 (optional, only if a real requirement appears) — per-scope worker
322 pools, or per-workspace store partitions inside a boundary.
323
324 ## 8. Rollout and compatibility
325
326 | Client | Engine 0.8.x | Engine ≥ 0.10 (phase 1) | After phase 2/3 |
327 |---|---|---|---|
328 | Extension ≤ 0.8.3 | works (old model) | **broken today** (the reported error) | works: version probe keeps per-workspace stores on old engines |
329 | Extension ≥ phase 2 | works via probe | attaches; multi-window works | same |
330 | `codewhale web` | standalone | unchanged behavior | attaches to default boundary |
331 | Desktop socket client | n/a | attach works when boundary matches | canonical; linger; upgrades |
332 | TUI / exec / MCP | unchanged | unchanged | unchanged |
333
334 No transport changes, no wire-format changes beyond additive typed errors and
335 control ops; the stdout readiness line contract is preserved for every
336 spawn-and-scan client.
337
338 ## 9. Rejected alternatives
339
340 - **Socket-per-store only (keep N independent engines).** Smallest diff, but
341 leaves N provider catalogs, N schedulers contending over the shared
342 automations/tasks locations (`AutomationManager::default_location`,
343 `default_tasks_dir` are per-user, not per-store), and N heavy processes.
344 The 0.10.1 owner model exists to end exactly this.
345 - **HTTP-first discovery (port files as the control plane).** Port files
346 already exist per workspace; HTTP cannot authenticate the local peer the
347 way the socket + receipt do. The socket stays the control plane.
348 - **OS supervision (launchd/systemd user units).** Installs state per
349 machine for a problem self-election + idle retirement solves with zero
350 install; desktop *may* supervise, but nothing requires it.
351 - **Owner stays inside the electing client, extensions learn "shared"
352 semantics.** Makes every client's stop path a protocol negotiation about
353 other clients' needs; fragile under SIGTERM. Daemonized election is
354 simpler and total.
355 - **Store-per-workspace partitions inside the owner.** Unnecessary today —
356 threads are workspace-filtered in one shared store, and the extension
357 already depends on shared saved sessions. Revisit only with a concrete
358 isolation requirement.
359
360 ## 10. Open questions
361
362 1. Grace default (60 s?) and whether linger is per-connection or
363 per-boundary with a count.
364 2. Should the automations scheduler run in the owner unconditionally, or
365 only when at least one frontend has ever attached (headless-schedule
366 mode)?
367 3. `daemon/drain_restart` authorization: any attached frontend, or only
368 linger holders / an explicit operator path?
369 4. Whether the desktop wants a *named* multi-boundary story (e.g., one
370 boundary per account profile) — the tuple supports it; the UX does not
371 have to yet.
372 5. Windows store-derived named-pipe naming timing (the existing transport is retained).
373
374 ---
375
376 ## 11. Workspace drive lease (single-writer per workspace)
377
378 **Status:** Partial implementation at Runtime API workspace scope admission.
379 Turn admission and standalone TUI/CLI ownership are not added in this PR.
380
381 ### The invariant
382
383 One process holds the workspace kernel lease across stores that use the same
384 private lease-state root. Scopes in that process share counted acquisitions.
385 This PR does not serialize distinct in-process engines or add leases to
386 standalone TUI/CLI drivers. Existing watchers of an admitted owner share its
387 held scope and retain their token-intent restrictions.
388
389 ### Why the lease unit is the workspace, not the store
390
391 Three engine facts make the workspace the real contended resource:
392
393 1. **The workspace is a shared write surface.** Two engines with different
394 stores editing the same working tree is *worse* than store double-writes:
395 it corrupts user code, not history.
396 2. **The snapshot side-repo is keyed by workspace, store-independent**
397 (`snapshot/paths.rs` — user-level state dir hashed by canonical workspace
398 path; the 500 MB cap warning in the wild lands there). Two engines on one
399 workspace write the same snapshot repo with no serialization today.
400 3. **The in-process git-write mutex only covers windows on the same server**
401 (`git_writes`, #6647). Cross-process it does not exist.
402
403 The existing exclusivity unit — the store process-owner lock — is scoped to
404 one store. Per-workspace stores (extension), per-session stores (TUI), and
405 the user-level default store never contend on it, yet may share a
406 workspace. The lease lifts the unit to where the actual conflict is.
407
408 ### Drive vs watch
409
410 Existing device tokens separate watch and drive intent. This PR takes the
411 lease when a Runtime API workspace scope is admitted; it does not add a
412 separate lease-free scope admission API. Existing observers attach to the
413 owner's held scope and do not acquire another operating-system lease.
414
415 ### Mechanism
416
417 - **Lease file**: one per workspace under the private `workspace-leases` state directory —
418 `<lease_state_base()>/<project_hash>/<worktree_hash>.lease` —
419 reusing the same canonical-path hashing as the snapshot side-repo, so worktrees
420 of one checkout share a project bucket and a worktree lease is exact.
421 - **Acquire**: open-create + a kernel `flock`/Windows byte-range lock. Write holder facts: pid,
422 `process_start` (the existing liveness token), client label, store root,
423 timestamp.
424 - **Liveness**: the kernel lock releases when its holder dies, so a crashed
425 holder does not prevent the next acquisition. The lease file keeps a stable
426 identity. Releasing the lock leaves diagnostic metadata on disk; a successor
427 overwrites it on acquisition. The record alone never establishes a live holder.
428 A contender never deletes or replaces it based on recorded pid or
429 creation-time metadata: those fields describe a holder but do not grant
430 takeover authority. An old record can remain between a successor's lock
431 acquisition and its metadata write. A live but wedged holder must release
432 the kernel lease or exit before another process can drive the workspace.
433 - **Refusal is legible**: on contention the engine reports the recorded
434 holder (pid, client label, store root, age). The holder must close or release
435 its scope before another process can drive; existing observers may attach
436 watch-only to that owner. This PR does not add a forced takeover command.
437 - **Where it lives**: one small module in the TUI crate beside the store
438 process-owner lock, taking only `&Path` (workspace) + holder facts.
439
440 ### Admission points
441
442 `RuntimeWorkspaceScopes::admit` is the implemented admission point. It retains
443 canonical directory identity checks, acquires the lease before coordination
444 registration, and holds the guard through asynchronous MCP/LSP cleanup.
445
446 Independent turn admission and standalone TUI/CLI resume/fork ownership are
447 follow-up work. They do not acquire this lease merely by opening a
448 `RuntimeThreadManager`. Existing watch requests continue to use the admitted
449 owner scope and existing token checks.
450
451 ### Costs and caveats (honest list)
452
453 - Refusal UX is a product surface: the second client must present holder
454 facts and a takeover path, or this becomes a support burden.
455 - fd-lock semantics weaken on NFS/network volumes; the lease degrades to
456 advisory there (same as every existing lock in the engine).
457 - pid namespaces in containers make `process_start` checks conservative:
458 refuse takeover rather than false-positive "dead".
459 - Test matrix cost: client-pair mutex behavior (VS Code × desktop, TUI ×
460 VS Code, …) is a durable maintenance cost.
461 - Rollout: engines older than the lease have no lease; the lease binds only
462 when both sides run the new engine (first-ready-wins, no migration).
463
464 ### Relationship to the phases
465
466 The lease is orthogonal to the topology phases: A/C decide *where history
467 lives*, the lease decides *who may write*, B's lifecycle machinery remains
468 optional. Combined semantics: anyone can watch; history converges by
469 domain; one driver per workspace at a time.
470
470 lines MARKDOWN