返回 CodeWhale
delegated-coordination.md
根目录 / docs / architecture / delegated-coordination.md
1 # Delegated coordination contract
2
3 Codewhale records the small amount of shared state that parallel work needs to
4 remain attributable. This is coordination metadata, not an approval system and
5 not a store for model reasoning or transcripts.
6
7 ## Launch and write ownership
8
9 Every write-capable child persists the same `ChildLaunchManifest` used by the
10 runtime. Its mutation claim contains normalized repo-relative directory roots,
11 exact files, and named contracts. Paths that are absolute or escape with `..`
12 fail validation.
13
14 A prompt-only general child starts read-only. Callers that want a writer must
15 declare at least one `write_roots`, `exact_files`, or
16 `coordination_contracts` value. Codewhale does not infer a repo-wide `.` claim.
17 An active shared-workspace claim blocks another active owner when either tree
18 contains the other, exact files collide, or a named contract matches. A real
19 isolated worktree may proceed concurrently. Scope expansion uses
20 `agent action=claim` (`write_roots`, `exact_files`,
21 `coordination_contracts`); a collision records a bounded contention receipt and
22 fails before mutation without opening a permission modal.
23
24 Fleet workers follow the same rule. Write-capable Fleet tasks declare
25 `workspace.writable_paths` or `metadata.coordination_contracts`, and the
26 resolved values are persisted in their launch manifest.
27
28 ### Embedding state boundary
29
30 By default, delegated control-plane state remains workspace-scoped at
31 `<workspace>/.codewhale/state`: the worker ledger, complete transcript
32 artifacts, and store locks share that root. An embedding host may set
33 `EngineConfig::subagent_state_root` to keep those files under a session-owned
34 root without changing child cwd, tool path authority, or the execution
35 workspace recorded in receipts.
36
37 Different state roots intentionally form different coordination domains. They
38 do not exchange write claims or contention receipts even when their execution
39 workspace is the same. A host choosing that layout must serialize conflicting
40 writes itself or give writers isolated worktrees; the state-root override is a
41 storage and lifecycle boundary, not cross-session write arbitration.
42
43 This record is a cooperative Codewhale coordination boundary, not an operating
44 system sandbox. Fleet carries a machine-readable outer cap into each worker,
45 rechecks structured mutation targets, rejects symlink aliases, and denies
46 unbounded shell, Git, code, plugin, and mutating MCP execution. Those checks
47 prevent one Codewhale worker from silently exceeding its declared claim; they
48 do not promise containment against a separate hostile process racing filesystem
49 paths. Use an OS sandbox or an isolated host when that adversarial boundary is
50 required.
51
52 Authority-bound Fleet subprocesses are explicit leaves in v0.9.1. Their MCP,
53 LSP, snapshot, custom-tool, plugin, shell, and nested-agent startup surfaces are
54 disabled so configured background executables cannot bypass the structured
55 mutation path. The persisted receipt reports `max_spawn_depth = 0`.
56
57 ## Decisions and projected context
58
59 Coordination schema version 1 persists decision records with a stable id,
60 subject, proposed/accepted/superseded status, one owner, applicability scope,
61 concise constraints, evidence handles, version, and sequence. Only the owner
62 may change a decision's status. A second accepted decision for the same subject
63 cannot silently replace the first.
64
65 At child launch, Codewhale projects only accepted decisions whose scope matches
66 the child's declared paths, contracts, role, or tool capabilities. The
67 projection is deduplicated, limited to eight decisions and 4096 UTF-8 bytes,
68 and receipted by child id and decision ids. The task prompt may separately
69 carry at most eight explicit dependency facts and eight observable acceptance
70 checks. Parent transcripts, secrets, and raw reasoning are never projected.
71
72 ## Neutral fan-in
73
74 Conflicting candidates remain preserved as branch, patch, or artifact handles.
75 The neutral owner is the nearest common Planner/manager/operator in the
76 persisted parent tree, falling back to the root release owner. Neither candidate
77 author may claim that role. Reconciliation records:
78
79 - both or all input decision ids and candidate handles;
80 - a retry count and a limit of at most three;
81 - distinct independent Reviewer and Verifier evidence handles;
82 - a verified, failed, or blocked verification outcome; and
83 - the neutral disposition and bounded evidence handles.
84
85 Retry exhaustion is a terminal, inspectable receipt, not permission to discard
86 either candidate. Restart/replay preserves the schema, decisions, claims,
87 contention, projections, and reconciliation sequence.
88
89 ## Inspection
90
91 `agent action=status` exposes concise per-child claims and accepted decisions.
92 The bounded decision, claim, contention, projection, and reconciliation
93 receipts, plus deterministic hottest-path counts, reach the TUI through
94 `CoordinationDetailProjection`; the `agents/coordinate action=inspect` tool that
95 used to serve them to the model is registered for transcript replay only and is
96 no longer advertised in the model catalog. Metrics without an authoritative
97 source, such as package growth or route cost, remain explicitly null instead of
98 being inferred.
99
100 ## One model-facing surface
101
102 `agent` is the only sub-agent tool in the model catalog. The six narrow
103 `agents/*` tools stay registered so a persisted transcript replays against the
104 same implementations, but they declare `model_visible() -> false`: they are not
105 sent in the initial catalog and no discovery call returns them. Everything
106 they did is reachable through an `agent` action — `status`/`peek` for `list`,
107 `message`, `followup`, `interrupt`, `wait`, and `claim` for the one capability
108 that had no equivalent, write-scope expansion.
109
110 ## Durable workspace transactions and writer ownership
111
112 The current ledger is `.codewhale/state/subagents.v3.json`: one format3
113 envelope around the existing agent, worker and coordination schemas. It records
114 writer provenance, publication sequences and a durable revision. It is the sole
115 current state authority. Transcripts remain their existing separate artifacts;
116 legacy recovery bytes are retained backups, not another writable ledger.
117
118 A short OS transaction lock serializes store initialization, migration and every
119 read-current/check/mutate/publish operation. Claim overlap, decisions and their
120 sequence/session/scope receipts are checked against that current state before
121 acknowledgement. Unrelated writers' records are preserved. A stale snapshot
122 cannot replace a newer publication from its writer, an older launch generation
123 cannot replace a newer one, and a terminal receipt cannot be resurrected as
124 Running by a checkpoint. An explicit terminal retry accepts only the same
125 winning outcome; authoritative newer accounting metadata is retained.
126
127 There is no workspace-wide session lock. Interactive, exec, Fleet, background
128 and Runtime managers in one folder are ordinary neighbours: each holds only its
129 own boot lease and takes the transaction lock per operation. The Runtime
130 constructor keeps one manager per state path inside its process. No manager
131 holds the transaction lock while a child executes or while it waits for a
132 provider or channel capacity. Conflicting lock contention returns a bounded
133 retry error. Unsupported locking or failed store admission refuses durable
134 writes rather than silently creating an empty writable ledger, and admission is
135 retried on the next delegated write instead of staying refused for the life of
136 the process.
137
138 A Runtime that admits a selected workspace other than its own state root keeps
139 that workspace's claims in its own store. Before it admits a shared-workspace
140 writer there, and each time it leases such a writer, it refuses while any
141 session holds a live boot lease in the selected workspace's own store, and it
142 refuses when that store's directory cannot be listed. Only sessions that hold
143 a boot lease are seen: a Codewhale 0.10.2 or older session holds none. A
144 session that opens in that workspace later does not see the Runtime's claims,
145 and its lease refuses the Runtime's next shared-workspace writer there; give
146 writers isolated worktrees when both are expected.
147
148 Each writer holds its own boot lease. Other managers preserve its live records
149 and use its active claims during admission. An existing unlocked lease can
150 establish that its writer ended; a missing, invalid or unreadable lease is
151 uncertain and fails closed. Local task handles do not establish that another
152 process's work stopped. Parked and headless
153 WaitingForUser claim rules retain their existing lifecycle meaning; they do not
154 transfer a still-live writer's record ownership to a different boot.
155
156 Shared coordination mutations run through the existing manager transaction.
157 Failed operations do not automatically publish partial state. A deliberately
158 persisted contention receipt remains inspectable even though admission returns
159 an error. Fleet compensation is fenced by the exact store revision and the
160 same writer's successful publication; a stale snapshot cannot undo another
161 writer's work. Worker retention removes its owned records durably before
162 removing their transcript artifacts or evicting handles.
163
164 Taking over a proven-dead writer refreshes its exact durable worker and agent
165 projection and records that recovery before the requested mutation. The newer
166 snapshot sequence fences any older captured checkpoint, including for preflight.
167 Failed admission restores ownership from the last committed recovery image.
168 Synthetic recovery interruption is recorded as uncertainty and can be resolved
169 by the exact authoritative terminal outcome; it cannot authorize replay of an
170 admitted attempt. Unresolved recovery records remain retained. Local heartbeat
171 cleanup and retention act only on owned
172 records; transcript deletion also checks the committed retained identities.
173
174 Fleet restart preparation records the next exact generation as an unstarted
175 reservation. Cold recovery preserves that reservation until the matching Fleet
176 lease consumes it. The executor durably admits the full registered launch spec
177 before starting a process; an admitted or settled attempt cannot launch again
178 under the same generation. Current ledger cancellation can settle an unstarted
179 reservation only after any previous attempt has a confirmed outcome; an old
180 ledger attempt cannot consume its prepared successor.
181 An explicit controller may prepare that exact next generation for a live
182 foreign headless worker under the existing Fleet lease comparison, preserving
183 the execution owner's writer identity and every unrelated receipt. The owner
184 refreshes its durable generation before its next mutation; old-generation
185 checkpoints cannot undo the preparation.
186 The existing Fleet ledger and executor move through the bounded blocking owner
187 with the same manager-lock file. Successful completion reconciles the worker
188 projection after processing the executor's terminal event.
189
190 The per-worker `launch_admission_version` distinguishes the current durable
191 pre-spawn protocol from legacy rows. A missing legacy start timestamp or a
192 legacy terminal projection does not prove process teardown. Preparation retains
193 `prepared_previous_attempt_unsettled` until the owning executor confirms the
194 exact prior run, task, generation and full launch spec, or an authoritative
195 attempt receipt supplies that proof. A cold owner without either proof refuses
196 the reserved launch and retains its uncertainty. It does not invent a Failed
197 outcome or release a live writer's claim. Busy coordination yields without
198 leasing; unrelated foreign workers remain untouched.
199
200 The existing Fleet executor retains observed terminal output, the prepared
201 receipt and stopped host until publication is acknowledged. Final stream tails,
202 including usage, and the terminal receipt form one `TaskAttemptFinalized` ledger
203 record. An exact retry synchronizes the same candidate instead of appending
204 usage again. A visible record after a failed sync is not an acknowledgment.
205 The ledger remembers successful durability only for the same owned file and
206 length; appends, replacement and compaction invalidate that receipt.
207
208 Terminal completion keeps the public Running gate and its ownership until the
209 exact terminal result is durably recorded and parent/mailbox/host fan-in is
210 queued. The admitted bounded blocking owner performs that complete sequence,
211 so dropping its waiter cannot discard an admitted commit. A filesystem or
212 publication failure produces uncertainty, retains the winning pending result
213 and claims, and sends no successful completion. A later retry uses that same
214 winner. Failed live delivery after a successful commit leaves the durable
215 terminal fact intact and reports the delivery failure. Explicit in-memory
216 managers remain in-memory; their results are not durable receipts.
217
218 Current store publication propagates file-write and Unix directory-sync errors.
219 Opening or observing a new store revision resolves its directory durability
220 before acknowledging idempotent state, and exact terminal retries repeat that
221 barrier. Unchanged preflight does not add a directory sync.
222 An error after rename can still mean the new image is visible, so recovery reads
223 the committed image and never announces success solely from a failed waiter.
224 Native filesystem and power-loss qualification remain separate evidence.
225 Canceling a Fleet waiter retains an admitted blocking batch and its lock until
226 the batch returns. Dropped executor ownership uses the existing parent-death
227 pipe or Windows Job containment; that fallback does not create a successful
228 terminal receipt or claim that a remote effect was undone.
229
230 ### Legacy cutover and recovery
231
232 The first current-format admission migrates under the short transaction lock.
233 It does not wait for older sessions that still hold the retired
234 `subagents.v1.lock`. It retains the original
235 legacy bytes and a validated recovery copy, then leaves
236 `subagents.v1.json` as a private directory containing that recovery material.
237 An older session still open in that folder can no longer save its delegated
238 state once the directory replaces its file; restart it. If it publishes its
239 file between the two cutover renames, the cutover stops at a retained-file
240 refusal until a person inspects both files; nothing is deleted.
241 The current format3 file is published under the same short transaction lock.
242 Interrupted cutover states are validated and resumed without replacing a later
243 current-format revision with the old backup. Future or malformed envelopes
244 cannot fall back to parsing as legacy state.
245
246 The retained directory prevents the inspected older atomic file publisher from
247 replacing that pathname with its stale snapshot. It does not prevent an old
248 binary from executing tools or changing a workspace. Concurrent arbitrary old
249 binaries are not a supported current coordination domain; close them before
250 cutover. Recovery data is not silently deleted, and migration qualification
251 uses isolated synthetic state rather than existing user sessions. Different
252 explicit state roots remain separate coordination domains as described above.
253
253 lines MARKDOWN