pi-goal-delegate 0.1.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,11 +1,14 @@
1
1
  # delegate
2
2
 
3
- One self-contained goal, handed to a fresh child agent, under a contract that
4
- says when it is done and what proves it. The parent starts the delegation, gets a
5
- handle in about a second, and is woken by a completion message.
3
+ A delegation hands one goal to a fresh Pi child process with its own context
4
+ window, budget, and completion contract. `delegate_start` **waits for the
5
+ verified outcome by default**, so a `codemode` script collects results the way
6
+ it collects any other tool result: inline, in order, with no cross-turn
7
+ bookkeeping. `wait: false` returns a live handle in about a second and lets a
8
+ completion message wake the session later.
6
9
 
7
- This extension replaces `goal-handoff`. The primitive did not change. The
8
- lifecycle around it did, and the names now say what the thing is.
10
+ This package replaces `goal-handoff`. The primitive is the same: one goal, one
11
+ child, one verifiable ending.
9
12
 
10
13
  ## Install
11
14
 
@@ -21,110 +24,174 @@ package. To work on it directly, add the checkout instead:
21
24
  pi -e /path/to/pi-goal-delegate/src/index.ts
22
25
  ```
23
26
 
24
- Nothing else is required. The extension has no runtime dependency of its own: it
25
- starts another `pi` process with the same binary that is running it.
27
+ The extension has no runtime dependency of its own: it starts another `pi`
28
+ process with the same binary that is running it.
26
29
 
27
- ## Where this sits
30
+ ## When to delegate
28
31
 
29
- | Layer | Owns | Does not own |
32
+ Delegate when at least one of these is true before any work starts. Each one is
33
+ decidable from the request itself, in seconds:
34
+
35
+ 1. **The task splits into two or more independent workstreams.** Rewriting
36
+ several documents or modules, auditing separate subsystems, fixing unrelated
37
+ test suites. Two or more workstreams means a fan-out, and a fan-out is one
38
+ script with `Promise.all`.
39
+ 2. **The work is a long loop you do not want in this context.** Exploration,
40
+ reverse engineering, build-and-fix iteration, or verification that will take
41
+ more than about fifteen tool calls. The child absorbs the search noise and
42
+ returns the verdict.
43
+ 3. **A mechanical job can run on a cheaper or different model under a command
44
+ gate.** Renames, migrations, doc rewrites, test backfills: pass `model` and
45
+ `verify` and let the gate decide whether the work counts.
46
+
47
+ Work inline when the change is a direct edit of one to five calls, when it needs
48
+ back-and-forth with the user, or when it shares tight uncommitted state with this
49
+ session. A single delegation of one small task is slower than doing it, so one
50
+ workstream is not a reason to delegate.
51
+
52
+ ## Two ways to wait, and which is the default
53
+
54
+ | Mode | How | When |
30
55
  |---|---|---|
31
- | `codemode` | Control flow over tools: `Promise.all`, loops, filtering, scripting | Processes, budgets, child agents |
32
- | `pi-async-shell` | OS process supervision for commands: scope, binding, containment, durable logs | Anything about a goal or an agent |
33
- | `delegate` | The contract with a fresh child agent: goal, done criteria, budget, evidence, lifecycle | Orchestration, fan-out policy, generic shell supervision |
56
+ | **Inline** (default, `wait: true`) | `delegate_start` holds the call open until the child settles and returns the outcome. | Inside `codemode`, in a fan-out, or in an active `/goal`. |
57
+ | **Handle** (`wait: false`) | The call returns a live handle as soon as the run is admitted; the settle later arrives as a `delegate-completion` message. | When the parent has other work to do, or the session should go idle while the child runs. |
58
+
59
+ The inline wait is bounded by the run's own budget, so no call can outlive the
60
+ delegation it waits for. Two things can still end the wait early, and neither one
61
+ touches the child:
62
+
63
+ - The caller aborts the tool call, for example when a `codemode` script reaches
64
+ its `timeout_ms` deadline.
65
+ - The run's own `timeoutMinutes` expires and the parent stops the child.
66
+
67
+ In both cases `delegate_start` returns the live handle, the claim on the settle is
68
+ released, and the completion is delivered as a message when the child ends.
34
69
 
35
- A delegation happens to be a process, so this extension supervises one, using the
36
- model `pi-async-shell` established: a detached owner for the output, a scope that
37
- says who must reap, an event for completion instead of a poll, and a cancellation
38
- ladder that proves absence. It borrows the model, not the code.
70
+ ### Raising the script deadline
39
71
 
40
- Fan-out belongs to `codemode`, not here:
72
+ A `codemode` script has no deadline unless its header sets one, and a host that
73
+ sets a short default (60 seconds, say) will cut an inline wait long before a
74
+ typical delegation ends. Set the deadline for the whole script whenever the work
75
+ is longer than a minute:
41
76
 
42
77
  ```js
43
- const handles = await Promise.all(goals.map((g) => tools.delegate_start(g)));
44
- return handles.map((h) => h.runId);
45
- // end the turn; the completion message wakes you when they settle
78
+ // @options: {"timeout_ms": 1800000}
79
+ // goal: fan out three verified delegations and return their outcomes
80
+ const goals = [
81
+ { goal: "Make pnpm test pass in packages/api", verify: "pnpm --dir packages/api test", worktree: true },
82
+ { goal: "Make pnpm test pass in packages/web", verify: "pnpm --dir packages/web test", worktree: true },
83
+ ];
84
+ const outcomes = await Promise.all(goals.map((g) => tools.delegate_start(g)));
85
+ return outcomes.map(({ runId, status, verified, summary, integration }) => ({
86
+ runId, status, verified, summary, patch: integration?.patchPath,
87
+ }));
46
88
  ```
47
89
 
48
- ## Layout
90
+ ### Yielding the turn instead
49
91
 
50
- ```text
51
- src/
52
- index.ts tool and command registration (the file Pi discovers)
53
- command.ts /delegate, the human front end for the same registry
54
- registry.ts handles, claims, admission gate, coalesced completion, /reload handoff
55
- run.ts admission, live tail, cancellation ladder, sealed outcome
56
- spawn.ts run directory layout, child argv, detached supervisor spawn, typed reads
57
- supervisor.mjs detached owner of the child output and of state.json
58
- identity.ts procfs identity, process-tree fence, containment verdict
59
- events.ts the child JSON event stream: turns, usage, last text
60
- worker.ts child-side goal loop (loaded into the child with -e)
61
- contract.ts statuses, budgets, breakers, prompt text shared by both sides
62
- verify.ts the parent's own check on a completion claim
63
- worktree.ts a checkout of its own for a child that asks for one
64
- retention.ts reclaim run records by age, count and bytes
65
- skills/
66
- delegate/ the skill that teaches the workflow to an agent
67
- tests/ node --test suites, plus the fake child and worker host
68
- ```
92
+ With `wait: false`, the completion arrives as a `delegate-completion` message: one
93
+ coalesced message for a whole wave of runs, steered in before the next model call.
94
+ In an ordinary session, end the turn and let it wake you.
95
+
96
+ Under `/goal` (`@narumitw/pi-goal`), ending a turn without `goal_wait` triggers
97
+ immediate automatic continuation while the child is still running. Do one of these
98
+ instead:
99
+
100
+ - keep `wait: true` (the default), so the child is done before the turn can end;
101
+ - or call `goal_wait({ goal_id, reason })` alone, which pauses Goal mode until the
102
+ `delegate-completion` message wakes it.
103
+
104
+ `delegate_start` reads the active goal id from the session and prints the exact
105
+ `goal_wait` call when it returns a live handle under Goal mode.
106
+
107
+ ## Where this sits
69
108
 
70
- `package.json` declares `pi.extensions` and `pi.skills`, so installing the
71
- package gives Pi both the extension and the skill.
109
+ | Layer | Owns | Does not own |
110
+ |---|---|---|
111
+ | `codemode` | Control flow over tools: `Promise.all`, loops, filtering, scripting | Processes, budgets, child agents |
112
+ | `pi-async-shell` | OS process supervision for commands: scope, binding, containment, durable logs | Anything about a goal or an agent |
113
+ | `delegate` | The contract with a fresh child agent: goal, done criteria, budget, evidence, lifecycle | Orchestration, fan-out policy, generic shell supervision |
114
+
115
+ A delegation is a process, so this extension supervises one with the model
116
+ `pi-async-shell` established: a detached owner for the output, a scope that says
117
+ who must reap, an event for completion instead of a poll, and a cancellation ladder
118
+ that proves absence. It borrows the model, not the code.
72
119
 
73
120
  ## Tools
74
121
 
75
- ### `delegate_start`
122
+ Four tools, one seam: start a run, inspect or wait for runs, steer a run, stop a run.
76
123
 
77
- Admits the child and returns its handle. The child keeps running after the call
78
- returns.
124
+ ### `delegate_start`
79
125
 
80
126
  | Parameter | Default | Meaning |
81
127
  |---|---|---|
82
- | `goal` | required | The objective, self-contained. |
83
- | `doneWhen` | child decides | Verifiable completion criteria. Prefer "a command exits 0", not "it works". |
84
- | `context` | none | Only facts the child cannot discover: decisions, paths, constraints. Capped at 4000 characters. |
85
- | `verify` | none | A command the parent runs after the child reports `complete`. Exit 0 is the proof; anything else reports `unverified` (see [Verification](#verification)). |
128
+ | `goal` | required | The objective, stated so it stands without this conversation. |
129
+ | `doneWhen` | child decides | Verifiable completion criteria. Prefer "a command exits 0" over "it works". |
130
+ | `verify` | none | A shell command that gates `delegate_complete` in the child and is re-run by the parent (see [Verification](#verification)). |
131
+ | `context` | none | Facts the child cannot discover: decisions, paths, constraints. Capped at 4000 characters. |
132
+ | `wait` | `true` | Hold the call until the child settles and return its outcome. `false` returns a live handle as soon as the run is admitted. |
133
+ | `worktree` | `false` | Give the child its own `git worktree` and branch. Requires git. |
134
+ | `options` | none | Everything else, below. |
135
+
136
+ | `options` field | Default | Meaning |
137
+ |---|---|---|
86
138
  | `maxTurns` | 150 | Model turns. One turn is one assistant response plus its tool calls. |
87
- | `timeoutMinutes` | 60 | Wall-clock cap. The child enforces it too, so a workspace run is still bounded after Pi dies. |
88
- | `maxCostUsd` | `PI_DELEGATE_MAX_COST_USD` | Cumulative spend cap, from provider usage cost. 0 disables it. |
139
+ | `timeoutMinutes` | 60 | Wall-clock cap, and therefore the ceiling on an inline wait. The child enforces it too. |
140
+ | `maxCostUsd` | `PI_DELEGATE_MAX_COST_USD` | Cumulative spend cap for this run, from provider usage cost. 0 disables it. |
141
+ | `maxDepth` | 0 | Maximum absolute delegation-tree depth, 0-3. Zero disables nested delegation. |
89
142
  | `model` | parent model | `provider/id`, passed to the child explicitly (see [Model](#model)). |
90
143
  | `tools` | inherited | Allowlist for the child. The protocol tools, and `codemode` when the parent has it, are always kept. |
91
- | `cwd` | session cwd | Working directory. |
144
+ | `cwd` | session cwd | Working directory for the child. |
92
145
  | `scope` | `session` | `session` dies with Pi and survives `/reload`; `workspace` outlives Pi and is re-adopted. |
93
146
  | `isolated` | `false` | Drop ambient extensions, skills, MCP servers, and context files. |
94
- | `worktree` | `false` | Give the child its own `git worktree` and branch. Requires git. |
95
147
  | `resumeFrom` | none | Continue a previous child: a run id, or a session file path. |
96
- | `inlineSettleMs` | 1000 | Hold this call open for an immediate settle, so a broken start fails here. Expiry cancels nothing. |
148
+ | `resultSchema` | none | JSON Schema for the structured `result` returned through `delegate_complete`. A schema no value could satisfy is refused at start, because the child could then never complete. |
97
149
 
98
- ### `delegate_list`
150
+ A known option name written at the top level instead of inside `options` is lifted
151
+ into `options` before validation, so a near-miss argument starts the run the caller
152
+ meant instead of failing the schema.
99
153
 
100
- Every run this session knows about, live or settled: status, turns, cost, how the
101
- completion was verified, and where a resume would point. Listing claims nothing,
102
- so unlike `delegate_await` it never consumes the completion message.
103
- `includeSettled: false` shows only what is running.
154
+ ```js
155
+ // Default: wait for the verified outcome.
156
+ const outcome = await tools.delegate_start({
157
+ goal: "Make the parser stream instead of buffering",
158
+ verify: "pnpm test --filter parser",
159
+ context: "parse() is used by cli/scan.ts; keep its signature",
160
+ });
161
+ if (outcome.verified === true) return outcome.summary;
104
162
 
105
- ### `delegate_send`
163
+ // Background: a handle now, a message later.
164
+ const handle = await tools.delegate_start({ goal: "...", wait: false });
165
+ ```
166
+
167
+ ### `delegate_status`
106
168
 
107
- `delegate_send(runId, text)` hands a running child one message. The parent
108
- appends it to `inbox.jsonl` in the run directory and the worker reads it at its
109
- next `turn_start`, so it works across `/reload` and across processes, and it
110
- never interrupts a request that is already in flight. The child treats it as
111
- direction for the work it is already doing, not as a new goal.
169
+ Inspects runs, and waits for them when asked.
112
170
 
113
- ### `delegate_await`
171
+ | Parameter | Default | Meaning |
172
+ |---|---|---|
173
+ | `runIds` | every run in this session | One run id, an array of run ids, or `"all"`. |
174
+ | `waitMs` | 0 | `0` is a snapshot. Above 0, the call waits up to this many milliseconds for the runs to settle. |
175
+ | `mode` | `all` | `all` waits for every named run; `any` returns when the first one settles. |
176
+
177
+ A call that names run ids claims the settles it reports, so the same settle is not
178
+ also announced as a message. A call with no `runIds` is a read: it lists what
179
+ exists and claims nothing.
114
180
 
115
- Waits up to `waitMs` (default 30000, max 50000) for one or more delegations. It
116
- blocks this tool call and never cancels the work. `waitMs: 0` is a snapshot.
117
- `mode: "any"` returns on the first settle; `"all"` waits for every run.
181
+ ### `delegate_send`
118
182
 
119
- A settle reported by an await is claimed before the wait starts, so it is not
120
- also announced as a message. Claims are reference counted, and an aborted wait
121
- hands its settle back to the completion channel.
183
+ `delegate_send(runId, text)` hands a running child one message. The parent appends
184
+ it to `inbox.jsonl` in the run directory and the worker reads it at its next
185
+ `turn_start`, immediately queuing it with Pi's `deliverAs: "steer"` so it lands
186
+ after the current turn's tool calls and before the next model call. It works across
187
+ `/reload` and across processes and never interrupts a request in flight. Use it to
188
+ correct course; that costs one call, where a restart costs the whole budget and the
189
+ context.
122
190
 
123
191
  ### `delegate_cancel`
124
192
 
125
- Graceful signal, grace period (default 3000ms), process-tree fence, then a check
126
- that the tree is actually gone. `containment` is a measurement, not a promise, and
127
- it has three values:
193
+ Graceful signal, grace period (default 3000 ms), process-tree fence, then a check
194
+ that the tree is actually gone. `containment` is a measurement:
128
195
 
129
196
  | `containment` | Meaning |
130
197
  |---|---|
@@ -132,37 +199,22 @@ it has three values:
132
199
  | `leaked` | Some process survived; the pids are in `leakedPids`. |
133
200
  | `unproven` | This platform exposes no process table, so absence could not be proven. Report it as unproven, never as gone. |
134
201
 
135
- The three-state verdict exists because the old `verifiedGone: boolean` was `true`
136
- when nothing was observable: an absence of observation read as proof of absence.
202
+ The three-state verdict exists because a two-state `verifiedGone` was `true` when
203
+ nothing was observable: an absence of observation read as proof of absence.
137
204
 
138
205
  ### Child-side protocol
139
206
 
140
207
  The child gets exactly two tools that end the loop:
141
208
 
142
- - `delegate_complete(summary, evidence)` - verified done. Evidence is commands, files, checks.
143
- - `delegate_blocked(reason, needs)` - a decision, credential, or fact the child cannot obtain.
209
+ - `delegate_complete(summary, evidence, result?)` — completion-gated done. Evidence
210
+ is commands, files, checks; `result` is validated when `resultSchema` is present.
211
+ - `delegate_blocked(reason, needs)` — a decision, credential, or fact the child
212
+ cannot obtain.
144
213
 
145
214
  Foreign goal tools (`goal_complete`, `goal_blocked`, `goal_wait`, the old
146
215
  `goal_handoff_*`) are deactivated in the child. A delegated child has one goal
147
216
  protocol.
148
217
 
149
- ## Waiting: three rules
150
-
151
- 1. **Starting is not waiting.** `delegate_start` waits for admission plus a
152
- bounded inline window, and then returns. It never waits for the goal.
153
- 2. **A tool-call wait is bounded and narrow.** `delegate_await` blocks at most 50
154
- seconds, because a `codemode` script has a 60-second budget. Its expiry
155
- cancels nothing.
156
- 3. **The long wait is ending the turn.** The completion arrives as a
157
- `delegate-completion` message, coalesced over 150ms and steered in before the
158
- next model call. One message for twelve runs is one decision, not twelve.
159
-
160
- The rule exists because a goal takes minutes. Across 42 recorded runs, 100% ran
161
- longer than 60 seconds: minimum 222s, median 1102s (18 minutes), maximum 6270s
162
- (104 minutes). A start call that waits for the goal is a start call that times
163
- out, so the old tool forced every `codemode` caller to override `timeout_ms` into
164
- the hours and risk aborting a healthy child.
165
-
166
218
  ## Lifecycle
167
219
 
168
220
  | Status | Who decides | Meaning |
@@ -172,32 +224,37 @@ the hours and risk aborting a healthy child.
172
224
  | `complete` | child | `delegate_complete`, and the `verify` command, if any, exited 0. |
173
225
  | `unverified` | parent | The child said complete, and the parent ran `verify` and it failed. |
174
226
  | `blocked` | child | `delegate_blocked`. The outcome carries `needs`, not `evidence`. |
175
- | `no_progress` | child | Circuit breaker: repeated identical call, consecutive failures, or two identical no-tool turns. |
176
- | `limit` | child or parent | Turn budget or spend cap reached. The child fences itself before the next request, not at the idle boundary; the parent's copy of the same rule is a runaway net with a two-turn grace. |
177
- | `timeout` | parent and child | Wall clock. Parent enforces with the ladder; child enforces on its own for `workspace` runs. |
227
+ | `no_progress` | child or parent | Circuit breaker: repeated identical call, consecutive failures, or two identical no-tool turns. |
228
+ | `limit` | child or parent | Turn budget or spend cap reached. The child fences itself before the next request; the parent's copy of the rule is a runaway net with a two-turn grace. |
229
+ | `timeout` | parent and child | Wall clock. The parent enforces it with the ladder; the child enforces it on its own for `workspace` runs. |
178
230
  | `aborted` | parent | `delegate_cancel`. |
179
231
  | `error` | parent | Spawn failure, child crash, provider error, or no verdict at all. |
180
- | `lost` | parent | Adopted workspace record with no exit and no provable liveness. Never reported as complete. |
232
+ | `lost` | parent | An adopted workspace record with no exit and no provable liveness. Never reported as complete. |
181
233
 
182
- Only `complete` and `blocked` are delegations that delivered what they were
183
- given. Everything else is a failure, and `isFailure` in `contract.ts` is the one
184
- definition the tools, the command, and `isError` on a tool result all share: a
185
- `no_progress` or `limit` run used to be reported with `isError: false`, so an
186
- orchestrator branching on `isError` read a stalled child as a finished one.
234
+ Only `complete` and `blocked` delivered what they were given. Everything else is a
235
+ failure, and `isFailure` in `contract.ts` is the one definition the tools, the
236
+ command, and `isError` on a tool result all share: a `no_progress` or `limit` run
237
+ reported with `isError: false` is a stalled child an orchestrator reads as a
238
+ finished one.
187
239
 
188
240
  ## Verification
189
241
 
190
- `doneWhen` is prose for the child. `verify` is a command for the parent:
242
+ `doneWhen` is prose for the child. `verify` is an executable completion gate for
243
+ both sides:
191
244
 
192
245
  ```js
193
246
  await tools.delegate_start({
194
247
  goal: "Make the parser stream instead of buffering",
195
- verify: "pnpm test --filter parser"
248
+ verify: "pnpm test --filter parser",
196
249
  });
197
250
  ```
198
251
 
199
- After the child reports `complete`, the parent runs that command in the child's
200
- own directory and records `verified`:
252
+ `delegate_complete` first runs the command in the child's directory. A failure is
253
+ returned to the child as a tool error containing the command output, and the run
254
+ continues so the child can repair the cause and retry. Only a passing claim
255
+ terminates the child. The parent then independently runs the same command before
256
+ accepting the outcome, using the same `PI_DELEGATE_ENV_DROP` policy so verification
257
+ cannot regain credentials withheld from the child.
201
258
 
202
259
  | `verified` | Meaning |
203
260
  |---|---|
@@ -206,32 +263,29 @@ own directory and records `verified`:
206
263
  | `"not-run"` | The run carried no verify command, so the evidence is the child's own account and nothing more. |
207
264
 
208
265
  The child's summary and evidence survive a contradiction: the parent records that
209
- its own check failed, not that the child never spoke. Before this existed,
210
- "evidence" was a string the child wrote about itself and nothing executed it.
266
+ its own check failed, not that the child never spoke. `childVerification` preserves
267
+ the successful child-side gate separately from the parent's `verification` record.
211
268
 
212
- ## Budgets, and why the defaults are these numbers
269
+ ## Budgets
213
270
 
214
- `maxTurns` counts model turns. Real delegations, measured from the child session
215
- files of 42 runs: minimum 25, median 110, p90 217, maximum 296. The default is 150
216
- and the hard maximum is 500. The old default of 20 counted user messages, so it
217
- recorded `turns: 1` for a 265-turn session and bounded nothing.
271
+ `maxTurns` counts model turns. Recorded delegations measure from 25 to 296 turns,
272
+ with a median of 110, so the default is 150 and the hard maximum is 500.
218
273
 
219
- `timeoutMinutes` defaults to 60. A 30-minute cap would have cut 14 of those 42
220
- runs; 60 minutes keeps 90% of them.
274
+ `timeoutMinutes` defaults to 60, which keeps about 90% of recorded runs inside the
275
+ cap. It bounds the inline wait as well, so one number answers both questions.
221
276
 
222
- Circuit breakers, all in the child: the third identical tool call is blocked, the
223
- sixth ends the run, eight consecutive tool errors end the run, and two
224
- consecutive turns with the same answer and no tool calls end the run. They live in
225
- `contract.ts` as pure functions over one state record, because the parent reads
226
- the same rules from the child's event stream and two copies of a threshold is two
227
- answers to "was this run stuck".
277
+ Circuit breakers run in the child and in the parent's compact event observer: the
278
+ third identical tool call is blocked in the child, the sixth ends the run, eight
279
+ consecutive tool errors end the run, and two consecutive turns with the same answer
280
+ and no tool calls end the run. They live in `contract.ts` as pure functions over
281
+ one state record, because the parent reads the same rules from the child's event
282
+ stream and two copies of a threshold is two answers to "was this run stuck".
228
283
 
229
284
  ### Admission: how many children at once
230
285
 
231
286
  One session may keep `PI_DELEGATE_MAX_LIVE` delegations live, four by default,
232
- thirty-two at most. A `Promise.all` over fifty goals used to start fifty children,
233
- each with its own process, model stream, and budget; the fifty-first is now
234
- refused with the live runs named:
287
+ thirty-two at most. A `Promise.all` over fifty goals is refused at the fifth with
288
+ the live runs named:
235
289
 
236
290
  ```text
237
291
  Too many live delegations: 4 of 4 already running.
@@ -240,8 +294,9 @@ Wait for one to settle, cancel one with delegate_cancel, or raise
240
294
  PI_DELEGATE_MAX_LIVE (currently 4, maximum 32).
241
295
  ```
242
296
 
243
- The gate counts live runs, not lifetime runs: cancelling frees a slot
244
- immediately. A malformed value falls back to the default rather than to
297
+ The gate counts live runs plus starts reserved during admission, not lifetime runs:
298
+ concurrent starts cannot pass before their handles register, and cancelling frees a
299
+ slot immediately. A malformed value falls back to the default rather than to
245
300
  "unlimited".
246
301
 
247
302
  ### Cost
@@ -252,42 +307,50 @@ ends as `limit` with the amount in the summary. It is off by default
252
307
  (`PI_DELEGATE_MAX_COST_USD=0`): a cap that kills a healthy run by default is worse
253
308
  than no cap.
254
309
 
310
+ The cap is per run. A nested child may not choose a cap larger than its parent's,
311
+ but nothing sums a tree: four grandchildren with a $2 cap each can spend $8 between
312
+ them. Treat `maxDepth` and `maxTurns` as the tree-wide bound and `maxCostUsd` as the
313
+ per-run ceiling.
314
+
255
315
  ## Parallel children and worktrees
256
316
 
257
- Two children editing one working tree fight over every file: a build in one
258
- rewrites what the other is reading, and `git status` in either reports the
259
- other's work. `worktree: true` gives the child its own checkout:
317
+ Two children editing one working tree fight over every file. `worktree: true` gives
318
+ the child its own checkout:
260
319
 
261
320
  ```js
262
321
  await tools.delegate_start({ goal: "...", worktree: true });
263
322
  ```
264
323
 
265
324
  The parent runs `git worktree add --no-track -b delegate/<runId>
266
- <agentDir>/delegate/worktrees/<runId> HEAD` in the session directory and starts
267
- the child there. The outcome records `worktree: { path, branch, repo }`, so the
268
- parent can merge from it or open it.
325
+ <agentDir>/delegate/worktrees/<runId> HEAD` in the session directory and starts the
326
+ child there. The outcome records `worktree: { path, branch, repo, base }` and
327
+ `integration`: HEAD, dirty status, diff statistics, `changes.patch`, and the result
328
+ of `git apply --check` against the original repository. The patch includes
329
+ committed, tracked-uncommitted, and untracked work. Nothing is automatically
330
+ committed or merged; `integration.applyCommand` is the explicit integration path.
269
331
 
270
332
  The checkout is **kept by default**: it holds the only copy of the child's work.
271
- `PI_DELEGATE_KEEP_WORKTREES=0` opts into cleanup, and even then only a clean tree
272
- is removed. A worktree inside the record root is removed with its record by
273
- retention. A directory that is not a git repository, or a repository with no
274
- commit, fails the start with git's own message rather than silently falling back
275
- to the shared tree.
333
+ `PI_DELEGATE_KEEP_WORKTREES=0` opts into cleanup, and even then only a clean tree is
334
+ removed. A directory that is not a git repository, or a repository with no commit,
335
+ fails the start with git's own message rather than silently falling back to the
336
+ shared tree.
276
337
 
277
338
  ## Resuming a run
278
339
 
279
- `outcome.sessionFile` is the child's own Pi session. `delegate_start({ resumeFrom:
280
- runId })` resolves it and passes `--session <path>` to the new child, so a second
281
- delegation continues the first one's context instead of starting cold. A session
282
- file path or a session id is accepted as-is; an unknown value is passed through
283
- rather than guessed at.
340
+ `outcome.sessionFile` is the child's own Pi session. `options.resumeFrom: runId`
341
+ resolves it and passes `--session <path>` to the new child, so a second delegation
342
+ continues the first one's context instead of starting cold. When the previous run
343
+ used a worktree, the resumed run keeps that checkout as its cwd. `resumedFrom`
344
+ records the lineage. A session file path or a session id is accepted as-is; an
345
+ unknown value is passed through rather than guessed at. A resume is a new run with a
346
+ new budget, not a reopening of the sealed record.
284
347
 
285
348
  ## Model
286
349
 
287
- The parent passes its model to the child explicitly with `--model` and its
288
- thinking level with `--thinking`. Inheritance by omission does not work: a child
289
- started without `--model` falls back to `settings.json` `defaultModel`, which is
290
- not the parent session model. `modelSource` in the outcome records which one ran:
350
+ The parent passes its model to the child explicitly with `--model` and its thinking
351
+ level with `--thinking`. Inheritance by omission does not work: a child started
352
+ without `--model` falls back to `settings.json` `defaultModel`, which is not the
353
+ parent session model. `modelSource` in the outcome records which one ran:
291
354
  `explicit`, `inherited`, or `default`.
292
355
 
293
356
  ## Accounting
@@ -295,75 +358,62 @@ not the parent session model. `modelSource` in the outcome records which one ran
295
358
  Every outcome carries `turns`, `toolCalls`, and `usage` (`input`, `output`,
296
359
  `cacheRead`, `cacheWrite`, `totalTokens`, `cost`). The numbers are folded from the
297
360
  child's own JSON event stream, and the child writes the same numbers into
298
- `result.json`, so a killed run still reports what was spent up to the kill. Across
299
- the recorded runs the cost was $0.08 to $2.42 per delegation.
361
+ `result.json`, so a killed run still reports what was spent up to the kill.
300
362
 
301
363
  ## Supervision
302
364
 
303
365
  `delegate_start` spawns `supervisor.mjs`, a detached Node process in its own
304
- session. The supervisor owns the child stdout and stderr and writes
305
- `child.jsonl` and `child.log`. Pi holds no pipe to the child, which is what makes
306
- the rest possible:
307
-
366
+ session. The supervisor owns the child stdout and stderr and writes `child.jsonl`,
367
+ `child.log`, and the compact accounting stream `control.jsonl`. Pi holds no pipe to
368
+ the child, which is what makes the rest possible:
369
+
370
+ - **An interrupted wait does not interrupt the child.** A tool call that is aborted
371
+ or times out ends only the wait. The supervisor is detached, the run keeps going,
372
+ the claim on its settle is released, and the completion is delivered as a message.
373
+ Synchronous orchestration and background orchestration are therefore one mechanism
374
+ with a different amount of patience.
308
375
  - **`/reload` transfers ownership.** The live registry is published to a
309
- process-global slot keyed by `(pid, sessionId, cwd)`; the next activation claims
310
- it and rebinds its UI callbacks. Nothing restarts, no byte is lost. A slot that
311
- nobody claims within 30 seconds expires into cancellation, so a handle is never
312
- left unowned.
376
+ process-global slot keyed by `(pid, sessionId, cwd)`; the next activation claims it
377
+ and rebinds its UI callbacks. Nothing restarts, no byte is lost. A slot nobody
378
+ claims within 30 seconds expires into cancellation.
313
379
  - **`session_shutdown` reaps session runs.** The supervisor watches fd 3. EOF means
314
- the owning Pi died, so the tree is torn down; the single line `release` means
315
- ownership moved, so it keeps running.
380
+ the owning Pi died, so the tree is torn down. Bytes on fd 3 are not a protocol;
381
+ `/reload` transfers the in-process registry without changing supervisor ownership.
316
382
  - **`scope: "workspace"` survives Pi.** No fd 3, no owner watch. On the next
317
383
  `session_start` in the same directory, a run whose owner identity is dead is
318
- re-adopted: the event log is folded, the tail resumes, and the settle is
319
- delivered here. A run whose owner is alive is read-only. A record with no exit
320
- and no provable liveness becomes `lost`.
384
+ re-adopted: the event log is folded, the tail resumes, and the settle is delivered
385
+ here. A run whose owner is alive is read-only. A record with no exit and no
386
+ provable liveness becomes `lost`.
321
387
  - **Logs drain past the cap.** 32 MiB per stream by default. Past the cap the
322
- supervisor stops appending and keeps reading, because a reader that stops
323
- reading turns a logging policy into a hung child.
388
+ supervisor stops appending the raw payload and keeps reading, because a reader that
389
+ stops reading turns a logging policy into a hung child. It still writes compact
390
+ turn, usage, cost, and breaker records to `control.jsonl`, so a capped payload log
391
+ cannot blind the parent's budgets or no-progress enforcement.
324
392
  - **The fence is the containment guarantee, where a process table exists.**
325
393
  Cancellation unions three views: processes tagged `PI_DELEGATE_RUN=<id>`, live
326
- descendants of the captured `(boot_id, pid, start)` identity, and live members
327
- of the owned process group. Each pid start time is re-read before signalling, so
328
- a reused pid is never killed. A process group alone is not containment:
329
- `setsid(2)` escapes it. Off Linux the group is what is left, and it is enough to
330
- kill: `spawn(detached: true)` makes the supervisor a session leader, so its pid
331
- *is* the process group id and `kill(-pgid)` reaches the whole tree without asking
332
- the kernel anything.
333
- - **The group handle is not a guess.** `pgidFor()` returns the detached
334
- supervisor's own pid on POSIX. It used to be read from `/proc/<pid>/stat`, which
335
- meant every non-Linux platform had an empty group list, so `killGroup` had
336
- nothing to signal and the cancel still reported success.
394
+ descendants of the captured `(boot_id, pid, start)` identity, and live members of
395
+ the owned process group. Each pid start time is re-read before signalling, so a
396
+ reused pid is never killed. Off Linux the group is what is left, and it is enough
397
+ to kill: `spawn(detached: true)` makes the supervisor a session leader, so its pid
398
+ *is* the process group id and `kill(-pgid)` reaches the whole tree.
337
399
 
338
400
  ## Permission asks
339
401
 
340
- The child is started with `PI_SUBAGENT_PARENT_SESSION=<session id>`, the
341
- convention `@gotgenes/pi-permission-system` documents for out-of-process
342
- subagents. A gated tool call in the child is forwarded to the delegating session,
343
- so authority stays with the human instead of failing closed with "no interactive
344
- UI is available". Without a human to answer, the child reports `blocked`. The
345
- marker is never overwritten when one is already present, so a chain of
346
- delegations relays through the middle hop.
402
+ The child is started with `PI_SUBAGENT_PARENT_SESSION=<session id>`, the convention
403
+ `@gotgenes/pi-permission-system` documents for out-of-process subagents. A gated
404
+ tool call in the child is forwarded to the delegating session, so authority stays
405
+ with the human instead of failing closed with "no interactive UI is available".
406
+ Without a human to answer, the child reports `blocked`. The marker is never
407
+ overwritten when one is already present, so a chain of delegations relays through
408
+ the middle hop.
347
409
 
348
410
  This is a declared dependency on another package's environment convention, not on
349
- its code. It is why a delegated child is not a security boundary of its own:
350
-
351
- - **Nothing here reads or writes that extension.** This package sets one
352
- environment variable and `@gotgenes/pi-permission-system` reads it. If that
353
- package is not installed, the variable is inert and nothing changes.
354
- - **The convention can move.** If that package changes the variable name, gated
355
- calls in the child fall back to whatever that extension does by default
356
- (usually "deny, no interactive UI"), and the child reports `blocked`. It does
357
- not become silently permissive.
358
- - **A different permission extension sees nothing.** Another implementation of
359
- permission gating will not honour this marker, so an approval ask from a child
360
- fails closed there. `isolated: true` is the other answer for a host that cannot
361
- answer asks at all: built-in tools only, no ambient extension, skill, MCP
362
- server, or AGENTS.md.
363
-
364
- `isolated: true` is the other answer for a host that cannot answer asks: the child
365
- runs with built-in tools only, no ambient extension, skill, MCP server, or
366
- AGENTS.md.
411
+ its code: if that package is not installed, the variable is inert. If it changes the
412
+ variable name, gated calls in the child fall back to that extension's default
413
+ (usually "deny, no interactive UI") and the child reports `blocked`; it does not
414
+ become silently permissive. `isolated: true` is the answer for a host that cannot
415
+ answer asks at all: built-in tools only, no ambient extension, skill, MCP server, or
416
+ `AGENTS.md`.
367
417
 
368
418
  ## Command
369
419
 
@@ -373,20 +423,58 @@ AGENTS.md.
373
423
  /delegate list delegations in this session
374
424
  /delegate read <id|prefix> one run in full
375
425
  /delegate log <id|prefix> tail the child stderr
426
+ /delegate send <id> <text> steer a running child
376
427
  /delegate cancel <id|prefix|all> cancel with the ladder
428
+ /delegate doctor check this installation
377
429
  ```
378
430
 
379
431
  Options may appear anywhere, as `--name value` or `--name=value`: `--model`,
380
- `--turns`, `--minutes`, `--cost`, `--done`, `--context`, `--verify`,
381
- `--tools`, `--scope`, `--isolated`, `--worktree`, `--resume`, `--cwd`.
382
- `/delegate send <id> <text>` is the steering path, the same as `delegate_send`.
383
- The command accepts what the tool schema accepts:
384
- `--turns` is 1-500, `--minutes` is 1-240, and a relative `--cwd` resolves
385
- against the session directory rather than the process working directory. A bare
386
- `--` ends option parsing, so a goal may contain its own `--words`.
432
+ `--turns`, `--minutes`, `--cost`, `--done`, `--context`, `--verify`, `--tools`,
433
+ `--scope`, `--isolated`, `--worktree`, `--resume`, `--cwd`, `--depth`, `--schema`,
434
+ `--wait`, `--background`. The command accepts what the tool schema accepts:
435
+ `--turns` is 1-500, `--minutes` is 1-240, and a relative `--cwd` resolves against the
436
+ session directory rather than the process working directory. A bare `--` ends option
437
+ parsing, so a goal may contain its own `--words`.
438
+
439
+ In the TUI the command returns as soon as the run is admitted and the settle arrives
440
+ as a completion message; `--wait` holds it open instead. In print mode it waits for
441
+ the outcome and prints it, because nothing else keeps a print-mode process alive for
442
+ a session-scoped child; `--background` returns immediately.
443
+
444
+ ## Doctor
445
+
446
+ `/delegate doctor` checks the parts that fail silently:
387
447
 
388
- Outside the TUI the command waits for the outcome and prints it, because nothing
389
- else keeps a print-mode process alive for a session-scoped child.
448
+ ```text
449
+ delegate doctor
450
+ manifest ok pi-goal-delegate 0.3.0 · 1 extension, 1 skill path
451
+ run root ok ~/.pi/agent/delegate · 12 records · 41.2 MiB
452
+ git ok available · worktree: true usable
453
+ launcher ok /usr/bin/node /usr/lib/pi/cli.js · child runs in --mode json
454
+ live ok 1 live of 4 · dl_mx38p4q3_e48a8e01
455
+ retention warn 3 of 14 records would be removed by the next prune: dl_1, dl_2, dl_3
456
+ PI_DELEGATE_MAX_RUNS, PI_DELEGATE_RETENTION_DAYS and PI_DELEGATE_MAX_BYTES set the policy
457
+ limits ok max live 4 of 32 · spend cap off · verify timeout 120s · run cap 240 minutes
458
+ session ok s_abc123 in /repo · top-level session
459
+ containment ok linux: procfs identity, tag scan, group fence
460
+ ```
461
+
462
+ Each line is `ok`, `warn`, or `fail`, and a check that cannot answer says so instead of
463
+ throwing. A `fail` is an installation that will not work, and the reason is on the
464
+ line: a run root that cannot be written, a launcher that does not exist, a manifest
465
+ entry that no longer resolves. A `warn` is a working installation with
466
+ something to know.
467
+
468
+ The same checks run at `session_start` for the one failure that used to be
469
+ invisible: an unwritable record root. A missing root is checked through its
470
+ nearest existing ancestor, and a symlink to a writable directory is accepted.
471
+ The probe uses a unique exclusive file and reports create, write, close or
472
+ unlink failures, so it neither clobbers an existing file nor passes a read-only
473
+ root. It produces a warning in the session instead of a delegation that fails
474
+ six days later.
475
+
476
+ `delegate_status` with no runs reports the run root and the record count as well, so
477
+ an agent can tell "nothing has run" from "the record root moved".
390
478
 
391
479
  ## Artifacts
392
480
 
@@ -397,40 +485,39 @@ else keeps a print-mode process alive for a session-scoped child.
397
485
  | `spec.json` | parent | The exact contract the child received, including the child command line. Written once, at admission. |
398
486
  | `meta.json` | parent | Scope, status, session directory, supervisor identity, owner identity, containment mode. |
399
487
  | `state.json` | supervisor | Pid, process group, cap, exit, sealed-at. The one record of the child process, sealed atomically. |
400
- | `child.jsonl` | supervisor | The child JSON event stream. Turns, usage, and progress are folded from this. |
488
+ | `child.jsonl` | supervisor | The raw child JSON event stream, capped at 32 MiB. |
489
+ | `control.jsonl` | supervisor | Compact turn, usage, cost, text, and breaker events. Written even after the raw cap; this is the parent's accounting source. |
401
490
  | `child.log` | supervisor | The child stderr. |
402
491
  | `result.json` | child | The verdict: status, summary, evidence or needs, turns, usage, session file. |
403
- | `outcome.json` | parent | The sealed outcome, readable after the parent is gone. |
492
+ | `outcome.json` | parent | The sealed outcome, including structured result and integration metadata, readable after the parent is gone. |
493
+ | `changes.patch` | parent | For worktree runs with changes: committed, tracked, and untracked work exported without an automatic commit. |
404
494
  | `inbox.jsonl` | parent | Steering messages, one JSON line each. The child reads the file at `turn_start`. |
405
495
  | `owner.lock` | parent | The adoption claim, created with `O_EXCL`. One owner at a time. |
406
496
 
407
497
  Each file has exactly one writer. `state.json` replaced `pid.json`, `exit.json` and
408
- `log-cap.json`, which described the same process in three files that a reader had
409
- to merge: two writers of one fact is how they disagree. Records written by a
410
- previous version are still read.
498
+ `log-cap.json`, which described the same process in three files a reader had to merge.
499
+ Records written by a previous version are still read.
500
+
501
+ Each run directory is created `0700` and every record inside it is written `0600`.
502
+ The record holds the goal, the context note, and the child's full output on a
503
+ possibly shared machine, so it is private to the user who started it.
411
504
 
412
- Each run directory is created `0700` and every record inside it is written
413
- `0600`. The record holds the goal, the context note, and the child's full output
414
- on a possibly shared machine, so it is private to the user who started it.
505
+ ### Retention
415
506
 
416
- Nothing reads a directory after its outcome is sealed, and records are reclaimed
417
- automatically. Retention is bounded three times: a record older than
507
+ Records are reclaimed automatically, bounded three times: a record older than
418
508
  `PI_DELEGATE_RETENTION_DAYS` (default 7) is removed, once the count passes
419
509
  `PI_DELEGATE_MAX_RUNS` (default 100) the oldest surplus is removed, and once the
420
- total passes `PI_DELEGATE_MAX_BYTES` (default 512 MiB) the oldest records are
421
- removed until it fits. The byte cap is the one that bounds the worst case:
422
- 32 MiB of stdout and 32 MiB of stderr per run times a hundred kept runs is 6.4 GB
423
- that no count or age limit ever reached.
424
-
425
- A record is never removed while it can still produce a verdict: a run this
426
- process follows, a record whose supervisor is alive, or one younger than ten
427
- minutes. Deleting a record also removes a worktree inside the record root, so no
428
- orphan checkout survives it. Delete old runs whenever you like; the next session
429
- prunes the rest.
430
-
431
- Runs recorded before this rename stay in `~/.pi/agent/goal-handoff/`. Nothing
432
- reads them, and the old extension is retired to
433
- `~/.pi/agent/retired-extensions/goal-handoff/`.
510
+ total passes `PI_DELEGATE_MAX_BYTES` (default 512 MiB) the oldest records are removed
511
+ until it fits. The byte cap bounds the worst case: 32 MiB of stdout and 32 MiB of
512
+ stderr per run times a hundred kept runs is 6.4 GB that no count or age limit ever
513
+ reached.
514
+
515
+ A record is never removed while it can still produce a verdict: a run this process
516
+ follows, a record whose supervisor is alive, or one younger than ten minutes.
517
+ Deleting a record removes a worktree inside the record root only through
518
+ `git worktree remove`, only when it is clean, and only when no other run references
519
+ it. `/delegate doctor` reports the plan before the next prune runs it, so retention
520
+ is predictable rather than a surprise.
434
521
 
435
522
  ### Environment
436
523
 
@@ -450,6 +537,29 @@ reads them, and the old extension is retired to
450
537
  | `PI_DELEGATE_RUN` / `PI_DELEGATE_DIR` / `PI_DELEGATE_SPEC` | Set by the parent on the supervisor and inherited by the child: the containment tag, the run directory, and the contract path. |
451
538
  | `PI_SUBAGENT_PARENT_SESSION` | Set for the child unless one is already present. Names the session that answers forwarded permission asks. |
452
539
 
540
+ ## Layout
541
+
542
+ ```text
543
+ src/
544
+ index.ts tool and command registration (the file Pi discovers)
545
+ command.ts /delegate, the human front end for the same registry
546
+ doctor.ts the installation and health self-check
547
+ registry.ts handles, claims, admission gate, coalesced completion, /reload handoff
548
+ run.ts admission, live tail, cancellation ladder, sealed outcome
549
+ spawn.ts run directory layout, child argv, detached supervisor spawn, typed reads
550
+ supervisor.mjs detached owner of the child output and of state.json
551
+ identity.ts procfs identity, process-tree fence, containment verdict
552
+ events.ts the child JSON event stream: turns, usage, last text
553
+ worker.ts child-side goal loop (loaded into the child with -e)
554
+ contract.ts statuses, budgets, breakers, prompt text shared by both sides
555
+ verify.ts the parent's own check on a completion claim
556
+ worktree.ts a checkout of its own for a child that asks for one
557
+ retention.ts reclaim run records by age, count and bytes, and report the plan
558
+ skills/
559
+ delegate/ the skill that teaches the workflow to an agent
560
+ tests/ node --test suites, plus the fake child and worker host
561
+ ```
562
+
453
563
  ## Tests
454
564
 
455
565
  From the repository root:
@@ -464,67 +574,86 @@ pnpm run test:coverage
464
574
  | Suite | Covers |
465
575
  |---|---|
466
576
  | `tests/delegate.test.mjs` | lifecycle, event folding, containment, claims, the cancellation grace period, the status footer, reload |
467
- | `tests/command.test.mjs` | `/delegate` parsing, quoting, prefix resolution, every cancel form, the TUI and print paths |
577
+ | `tests/command.test.mjs` | `/delegate` parsing, quoting, prefix resolution, every cancel form, doctor, the TUI and print paths |
578
+ | `tests/surface.test.mjs` | the four-tool surface, the lean schema budget, option hoisting, the inline default, the `goal_wait` guidance, and the `onProgress` contract |
579
+ | `tests/doctor.test.mjs` | real run-root probes: missing ancestors, read-only directories, exclusive cleanup, and symlinked roots |
468
580
  | `tests/worker.test.mjs` | the child's circuit breakers and terminal states, in a real subprocess |
469
581
  | `tests/events.test.mjs` | the event stream: unknown records, error carriers, the incremental tailer |
470
582
  | `tests/isolation.test.mjs` | directory-scoped workspace adoption, per-session registries |
471
583
  | `tests/adoption.test.mjs` | re-adoption against a supervisor that is actually running |
472
584
  | `tests/failure.test.mjs` | wall-clock deadlines, a supervisor killed from outside, an exit with no verdict |
473
- | `tests/retention.test.mjs` | age and count pruning, live-run protection |
585
+ | `tests/retention.test.mjs` | age and count pruning, the reported plan, live-run protection |
474
586
  | `tests/supervisor.test.mjs` | sealed exit records, controlled exit, log cap, the owner watch |
475
- | `tests/tool-e2e.test.mjs` | the real loader, tool schemas, every `delegate_await` and `delegate_cancel` mode, `/reload` |
587
+ | `tests/tool-e2e.test.mjs` | the real loader, tool schemas, inline and background starts, every `delegate_status` and `delegate_cancel` mode, `/reload` |
476
588
  | `tests/guard.test.mjs` | the child-side recursion guard, parameter validation, declared bounds |
477
589
  | `tests/containment.test.mjs` | the containment verdict model, signal-0 probing, a real cancel that must prove the tree gone, `isFailure`. Portable: this is the suite the macOS CI job runs. |
478
590
  | `tests/gates.test.mjs` | the live-admission gate, the spend cap, verified completion, the adoption claim, steering, worktrees, and typed record reads |
591
+ | `tests/result-schema.test.mjs` | the `resultSchema` admission audit and the instance path a rejected value is told |
479
592
 
480
- `tests/support.mjs` holds what every suite needs: temporary directories removed
481
- when the test ends, the `PI_DELEGATE_*` environment restored after each test, and
482
- `waitFor` in place of fixed sleeps. 156 tests, no model and no network.
593
+ `tests/support.mjs` holds what every suite needs: temporary directories removed when
594
+ the test ends, the `PI_DELEGATE_*` environment restored after each test, and
595
+ `waitFor` in place of fixed sleeps. No suite replaces `process.stdout`: the
596
+ command takes its output sink as a dependency, because a test that swaps the
597
+ process stream also swaps the channel the test runner reports on, and the results
598
+ it swallows are the ones nobody notices are missing.
483
599
 
484
600
  CI runs the whole suite on Linux against Node 22, 24 and 26, and runs
485
- `tests/containment.test.mjs` plus `tests/gates.test.mjs` on `macos-latest`: those
486
- are the suites that exercise cancellation and adoption where `/proc` does not
487
- exist, which is exactly the platform where absence used to be reported as proof.
601
+ `tests/containment.test.mjs` plus `tests/gates.test.mjs` on `macos-latest`: those are
602
+ the suites that exercise cancellation and adoption where `/proc` does not exist,
603
+ which is exactly the platform where absence used to be reported as proof.
488
604
 
489
605
  No suite needs a model or a network. The lifecycle suites spawn the fake child in
490
- `tests/fixtures/fake-pi.mjs`, which emits a real JSON event stream and seals a
491
- real verdict, and which can also refuse SIGTERM so a grace period is observable; the worker suite drives the real `worker.ts` through
492
- `tests/fixtures/worker-host.mjs`. The e2e suite loads the extension through Pi's
493
- own loader and resolves Pi's host packages from an explicit `PI_HOST_MODULES`
494
- override first, then from the project's own `node_modules`, then from the newest
495
- `~/.pi/agent/managed-runtime/releases` entry, so a clean clone with
496
- `pnpm install` runs it with no configuration.
606
+ `tests/fixtures/fake-pi.mjs`, which emits a real JSON event stream and seals a real
607
+ verdict, and which can also refuse SIGTERM so a grace period is observable. The
608
+ worker suite drives the real `worker.ts` through `tests/fixtures/worker-host.mjs`.
609
+ The e2e suite loads the extension through Pi's own loader and resolves Pi's host
610
+ packages from an explicit `PI_HOST_MODULES` override first, then from the project's
611
+ own `node_modules`, then from the newest `~/.pi/agent/managed-runtime/releases`
612
+ entry.
497
613
 
498
614
  ## Limits
499
615
 
500
- - **Containment is platform-dependent, and the verdict says which one ran.**
501
- Linux gets full observation: procfs identity, the tag scan, the descendant walk,
502
- and the owned process group. macOS and other POSIX platforms get the process
503
- group, which the detached supervisor leads, probed with signal 0: cancellation
504
- works, and the verdict is `gone` or `leaked` on real evidence. Windows gets
505
- `taskkill /T` and no observation, so its verdict is `unproven` — the tree is
506
- asked to die and the parent says so instead of claiming proof. A `setsid(2)`
507
- child that also clears its environment and loses its parent is out of reach on
508
- any platform.
509
- - **A delegation is not a sandbox.** The child runs with the parent's authority,
510
- in the parent's filesystem, with the parent's environment (minus
616
+ - **Containment is platform-dependent, and the verdict says which one ran.** Linux
617
+ gets procfs identity, the tag scan, the descendant walk, and the owned process
618
+ group. macOS and other POSIX platforms get the process group, probed with signal 0:
619
+ cancellation works, and the verdict is `gone` or `leaked` on real evidence. Windows
620
+ gets `taskkill /T` and no observation, so its verdict is `unproven`. A `setsid(2)`
621
+ child that also clears its environment and loses its parent is out of reach on any
622
+ platform.
623
+ - **A delegation is not a sandbox.** The child runs with the parent's authority, in
624
+ the parent's filesystem, with the parent's environment (minus
511
625
  `PI_DELEGATE_ENV_DROP`). `tools` and `isolated` bound the surface, not the
512
- permission.`
513
- - **A session-scoped run cannot outlive the session.** Use `workspace` for that.
514
- In print mode a session run is cancelled when the process exits, so a print
515
- caller should await it.
516
- - **`isolated: true` also drops provider extensions.** A custom provider that
517
- lives in an extension is unavailable to an isolated child.
518
- - **A delegated child inherits the parent filesystem and network permissions.**
519
- Tool allowlists bound the surface, not the sandbox.
520
- - **`delegate_await` blocks the tool call.** A tool call cannot be suspended here.
521
- Waits measured in minutes belong to the completion message.
522
- - **The workspace adoption scan reads the global run root.** A record is adopted
523
- only when it was started by this session's directory (its recorded session
524
- directory, or the child `cwd` for a record written before that field existed;
525
- both are compared through `realpath`), and its owner is gone. Two sessions in
526
- different directories never adopt each other's runs, and a record from a deleted
626
+ permission.
627
+ - **A session-scoped run cannot outlive the session.** Use `workspace` for that. In
628
+ print mode a session run is cancelled when the process exits, so a print caller
629
+ should use the default inline wait.
630
+ - **`isolated: true` also drops provider extensions.** A custom provider that lives in
631
+ an extension is unavailable to an isolated child.
632
+ - **The workspace adoption scan reads the global run root.** A record is adopted only
633
+ when it was started by this session's directory and its owner is gone. Two sessions
634
+ in different directories never adopt each other's runs, and a record from a deleted
527
635
  directory is never adopted.
528
- - **The child's no-progress rule is a heuristic.** Two identical answers with no
529
- tool call end the run; a child that varies its wording while doing nothing can
530
- still consume its turn budget.
636
+ - **The no-progress rule is a heuristic.** Two identical answers with no tool call end
637
+ the run in either observer; a child that varies its wording while doing nothing can
638
+ still consume its turn budget.
639
+
640
+ ## Design notes
641
+
642
+ Three decisions are load-bearing, and each one replaced a rule that measured wrong in
643
+ practice.
644
+
645
+ **The wait is inline, and its ceiling is the run's own budget.** Every recorded
646
+ delegation ran longer than 60 seconds (minimum 222 s, median 1102 s, maximum 6270 s),
647
+ so a tool-call wait capped in tens of seconds could never report a result. A capped
648
+ wait pushed callers into cross-turn bookkeeping, and under `/goal` that bookkeeping
649
+ was a live loop: end the turn, get continuation, poll, repeat. Waiting for the
650
+ outcome the run already promises costs nothing extra and removes the loop.
651
+
652
+ **The tool surface is four calls with one required argument.** A delegation is decided
653
+ in the second before the first call. Seventeen flat optional parameters and a tutorial
654
+ in the description answer questions the caller has not asked yet; a required `goal`,
655
+ six sparse inputs, and a nested `options` bag answer the one that matters.
656
+
657
+ **The completion is an event, never a poll.** A settle that nothing awaited is
658
+ delivered as one coalesced message. A settle an await reported is claimed and never
659
+ announced twice.