pi-goal-delegate 0.2.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,114 +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 that gates `delegate_complete` in the child and is independently re-run by the parent (see [Verification](#verification)). |
86
- | `resultSchema` | none | JSON Schema for the structured `result` returned through `delegate_complete`, suitable for codemode aggregation. A schema no value could satisfy (an unresolved `$ref`, a shape the validator cannot evaluate) is refused at start, because TypeBox fails closed and the child could never complete. |
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
+ |---|---|---|
87
138
  | `maxTurns` | 150 | Model turns. One turn is one assistant response plus its tool calls. |
88
- | `timeoutMinutes` | 60 | Wall-clock cap. The child enforces it too, so a workspace run is still bounded after Pi dies. |
89
- | `maxCostUsd` | `PI_DELEGATE_MAX_COST_USD` | Cumulative spend cap for this run, from provider usage cost. It bounds one run, not the delegation tree; a child may not exceed its own parent's cap. 0 disables it. |
90
- | `maxDepth` | 0 | Maximum absolute delegation-tree depth, 0-3. Zero disables nested delegation; children cannot raise depth, cost, or deadline limits. |
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. |
91
142
  | `model` | parent model | `provider/id`, passed to the child explicitly (see [Model](#model)). |
92
143
  | `tools` | inherited | Allowlist for the child. The protocol tools, and `codemode` when the parent has it, are always kept. |
93
- | `cwd` | session cwd | Working directory. |
144
+ | `cwd` | session cwd | Working directory for the child. |
94
145
  | `scope` | `session` | `session` dies with Pi and survives `/reload`; `workspace` outlives Pi and is re-adopted. |
95
146
  | `isolated` | `false` | Drop ambient extensions, skills, MCP servers, and context files. |
96
- | `worktree` | `false` | Give the child its own `git worktree` and branch. Requires git. |
97
147
  | `resumeFrom` | none | Continue a previous child: a run id, or a session file path. |
98
- | `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. |
99
149
 
100
- ### `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.
101
153
 
102
- Every run this session knows about, live or settled: status, turns, cost, how the
103
- completion was verified, and where a resume would point. Listing claims nothing,
104
- so unlike `delegate_await` it never consumes the completion message.
105
- `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;
106
162
 
107
- ### `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`
108
168
 
109
- `delegate_send(runId, text)` hands a running child one message. The parent
110
- appends it to `inbox.jsonl` in the run directory and the worker reads it at its
111
- next `turn_start`. The worker immediately queues it with Pi's `deliverAs: "steer"`,
112
- so Pi delivers it after the current turn's tool calls and before the next model
113
- call. It works across `/reload` and across processes, and it never interrupts a
114
- request already in flight. The child treats it as direction for existing work,
115
- not as a new goal; it is not deferred until `agent_settled`.
169
+ Inspects runs, and waits for them when asked.
116
170
 
117
- ### `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.
118
180
 
119
- Waits up to `waitMs` (default 30000, max 50000) for one or more delegations. It
120
- blocks this tool call and never cancels the work. `waitMs: 0` is a snapshot.
121
- `mode: "any"` returns on the first settle; `"all"` waits for every run.
181
+ ### `delegate_send`
122
182
 
123
- A settle reported by an await is claimed before the wait starts, so it is not
124
- also announced as a message. Claims are reference counted, and an aborted wait
125
- 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.
126
190
 
127
191
  ### `delegate_cancel`
128
192
 
129
- Graceful signal, grace period (default 3000ms), process-tree fence, then a check
130
- that the tree is actually gone. `containment` is a measurement, not a promise, and
131
- 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:
132
195
 
133
196
  | `containment` | Meaning |
134
197
  |---|---|
@@ -136,37 +199,22 @@ it has three values:
136
199
  | `leaked` | Some process survived; the pids are in `leakedPids`. |
137
200
  | `unproven` | This platform exposes no process table, so absence could not be proven. Report it as unproven, never as gone. |
138
201
 
139
- The three-state verdict exists because the old `verifiedGone: boolean` was `true`
140
- 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.
141
204
 
142
205
  ### Child-side protocol
143
206
 
144
207
  The child gets exactly two tools that end the loop:
145
208
 
146
- - `delegate_complete(summary, evidence, result?)` - completion-gated done. Evidence is commands, files, checks; `result` is validated when `resultSchema` is present.
147
- - `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.
148
213
 
149
214
  Foreign goal tools (`goal_complete`, `goal_blocked`, `goal_wait`, the old
150
215
  `goal_handoff_*`) are deactivated in the child. A delegated child has one goal
151
216
  protocol.
152
217
 
153
- ## Waiting: three rules
154
-
155
- 1. **Starting is not waiting.** `delegate_start` waits for admission plus a
156
- bounded inline window, and then returns. It never waits for the goal.
157
- 2. **A tool-call wait is bounded and narrow.** `delegate_await` blocks at most 50
158
- seconds, because a `codemode` script has a 60-second budget. Its expiry
159
- cancels nothing.
160
- 3. **The long wait is ending the turn.** The completion arrives as a
161
- `delegate-completion` message, coalesced over 150ms and steered in before the
162
- next model call. One message for twelve runs is one decision, not twelve.
163
-
164
- The rule exists because a goal takes minutes. Across 42 recorded runs, 100% ran
165
- longer than 60 seconds: minimum 222s, median 1102s (18 minutes), maximum 6270s
166
- (104 minutes). A start call that waits for the goal is a start call that times
167
- out, so the old tool forced every `codemode` caller to override `timeout_ms` into
168
- the hours and risk aborting a healthy child.
169
-
170
218
  ## Lifecycle
171
219
 
172
220
  | Status | Who decides | Meaning |
@@ -177,17 +225,17 @@ the hours and risk aborting a healthy child.
177
225
  | `unverified` | parent | The child said complete, and the parent ran `verify` and it failed. |
178
226
  | `blocked` | child | `delegate_blocked`. The outcome carries `needs`, not `evidence`. |
179
227
  | `no_progress` | child or parent | Circuit breaker: repeated identical call, consecutive failures, or two identical no-tool turns. |
180
- | `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. |
181
- | `timeout` | parent and child | Wall clock. Parent enforces with the ladder; child enforces on its own for `workspace` runs. |
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. |
182
230
  | `aborted` | parent | `delegate_cancel`. |
183
231
  | `error` | parent | Spawn failure, child crash, provider error, or no verdict at all. |
184
- | `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. |
185
233
 
186
- Only `complete` and `blocked` are delegations that delivered what they were
187
- given. Everything else is a failure, and `isFailure` in `contract.ts` is the one
188
- definition the tools, the command, and `isError` on a tool result all share: a
189
- `no_progress` or `limit` run used to be reported with `isError: false`, so an
190
- 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.
191
239
 
192
240
  ## Verification
193
241
 
@@ -197,19 +245,17 @@ both sides:
197
245
  ```js
198
246
  await tools.delegate_start({
199
247
  goal: "Make the parser stream instead of buffering",
200
- verify: "pnpm test --filter parser"
248
+ verify: "pnpm test --filter parser",
201
249
  });
202
250
  ```
203
251
 
204
- `delegate_complete` first runs the command in the child's directory. A failure
205
- is returned to the child as a tool error containing the command output, and the
206
- run continues so the child can repair the cause and retry. Only a passing claim
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
207
255
  terminates the child. The parent then independently runs the same command before
208
256
  accepting the outcome, using the same `PI_DELEGATE_ENV_DROP` policy so verification
209
257
  cannot regain credentials withheld from the child.
210
258
 
211
- The parent's recheck records `verified`:
212
-
213
259
  | `verified` | Meaning |
214
260
  |---|---|
215
261
  | `true` | The command exited 0. |
@@ -220,30 +266,26 @@ The child's summary and evidence survive a contradiction: the parent records tha
220
266
  its own check failed, not that the child never spoke. `childVerification` preserves
221
267
  the successful child-side gate separately from the parent's `verification` record.
222
268
 
223
- ## Budgets, and why the defaults are these numbers
269
+ ## Budgets
224
270
 
225
- `maxTurns` counts model turns. Real delegations, measured from the child session
226
- files of 42 runs: minimum 25, median 110, p90 217, maximum 296. The default is 150
227
- and the hard maximum is 500. The old default of 20 counted user messages, so it
228
- 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.
229
273
 
230
- `timeoutMinutes` defaults to 60. A 30-minute cap would have cut 14 of those 42
231
- 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.
232
276
 
233
- Circuit breakers run in both the child and the parent's compact event observer:
234
- the third identical tool call is blocked in the child, the sixth ends the run,
235
- eight consecutive tool errors end the run, and two consecutive turns with the
236
- same answer and no tool calls end the run. They live in
237
- `contract.ts` as pure functions over one state record, because the parent reads
238
- the same rules from the child's event stream and two copies of a threshold is two
239
- 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".
240
283
 
241
284
  ### Admission: how many children at once
242
285
 
243
286
  One session may keep `PI_DELEGATE_MAX_LIVE` delegations live, four by default,
244
- thirty-two at most. A `Promise.all` over fifty goals used to start fifty children,
245
- each with its own process, model stream, and budget; the fifty-first is now
246
- 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:
247
289
 
248
290
  ```text
249
291
  Too many live delegations: 4 of 4 already running.
@@ -252,9 +294,9 @@ Wait for one to settle, cancel one with delegate_cancel, or raise
252
294
  PI_DELEGATE_MAX_LIVE (currently 4, maximum 32).
253
295
  ```
254
296
 
255
- The gate counts live runs plus starts synchronously reserved during admission,
256
- not lifetime runs: concurrent starts cannot pass before their handles register,
257
- and cancelling frees a slot 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
258
300
  "unlimited".
259
301
 
260
302
  ### Cost
@@ -265,54 +307,50 @@ ends as `limit` with the amount in the summary. It is off by default
265
307
  (`PI_DELEGATE_MAX_COST_USD=0`): a cap that kills a healthy run by default is worse
266
308
  than no cap.
267
309
 
268
- The cap is per run. A nested child may not choose a cap larger than its own
269
- parent's, but nothing sums a tree: four grandchildren with a $2 cap each can spend
270
- $8 between them, and the parent's own cap is unaffected. Treat `maxDepth` and
271
- `maxTurns` as the tree-wide bound and `maxCostUsd` as the per-run ceiling.
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.
272
314
 
273
315
  ## Parallel children and worktrees
274
316
 
275
- Two children editing one working tree fight over every file: a build in one
276
- rewrites what the other is reading, and `git status` in either reports the
277
- 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:
278
319
 
279
320
  ```js
280
321
  await tools.delegate_start({ goal: "...", worktree: true });
281
322
  ```
282
323
 
283
324
  The parent runs `git worktree add --no-track -b delegate/<runId>
284
- <agentDir>/delegate/worktrees/<runId> HEAD` in the session directory and starts
285
- the child there. The outcome records `worktree: { path, branch, repo, base }` and
286
- `integration`: HEAD, dirty status, diff statistics, `changes.patch`, and the
287
- result of `git apply --check` against the original repository. The patch includes
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
288
329
  committed, tracked-uncommitted, and untracked work. Nothing is automatically
289
330
  committed or merged; `integration.applyCommand` is the explicit integration path.
290
331
 
291
332
  The checkout is **kept by default**: it holds the only copy of the child's work.
292
- `PI_DELEGATE_KEEP_WORKTREES=0` opts into cleanup, and even then only a clean tree
293
- is removed. A worktree inside the record root is removed with its record by
294
- retention, but only when clean and no other run record references it. A dirty
295
- worktree and its pointer record are both preserved. A directory that is not a git
296
- repository, or a repository with no commit, fails the start with git's own message
297
- rather than silently falling back 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.
298
337
 
299
338
  ## Resuming a run
300
339
 
301
- `outcome.sessionFile` is the child's own Pi session. `delegate_start({ resumeFrom:
302
- runId })` resolves it and passes `--session <path>` to the new child, so a second
303
- delegation continues the first one's context instead of starting cold. When the
304
- previous run used a worktree, the resumed run automatically keeps that checkout
305
- as its cwd instead of moving back to the shared tree. `resumedFrom` records the
306
- lineage. A session file path or a session id is accepted as-is; an unknown value
307
- is passed through rather than guessed at. A resume is a new run with a new budget,
308
- not a reopening of the sealed run record.
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.
309
347
 
310
348
  ## Model
311
349
 
312
- The parent passes its model to the child explicitly with `--model` and its
313
- thinking level with `--thinking`. Inheritance by omission does not work: a child
314
- started without `--model` falls back to `settings.json` `defaultModel`, which is
315
- 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:
316
354
  `explicit`, `inherited`, or `default`.
317
355
 
318
356
  ## Accounting
@@ -320,77 +358,62 @@ not the parent session model. `modelSource` in the outcome records which one ran
320
358
  Every outcome carries `turns`, `toolCalls`, and `usage` (`input`, `output`,
321
359
  `cacheRead`, `cacheWrite`, `totalTokens`, `cost`). The numbers are folded from the
322
360
  child's own JSON event stream, and the child writes the same numbers into
323
- `result.json`, so a killed run still reports what was spent up to the kill. Across
324
- 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.
325
362
 
326
363
  ## Supervision
327
364
 
328
365
  `delegate_start` spawns `supervisor.mjs`, a detached Node process in its own
329
- session. The supervisor owns the child stdout and stderr and writes
330
- `child.jsonl`, `child.log`, and the compact accounting stream `control.jsonl`. Pi holds no pipe to the child, which is what makes
331
- the rest possible:
332
-
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.
333
375
  - **`/reload` transfers ownership.** The live registry is published to a
334
- process-global slot keyed by `(pid, sessionId, cwd)`; the next activation claims
335
- it and rebinds its UI callbacks. Nothing restarts, no byte is lost. A slot that
336
- nobody claims within 30 seconds expires into cancellation, so a handle is never
337
- 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.
338
379
  - **`session_shutdown` reaps session runs.** The supervisor watches fd 3. EOF means
339
380
  the owning Pi died, so the tree is torn down. Bytes on fd 3 are not a protocol;
340
381
  `/reload` transfers the in-process registry without changing supervisor ownership.
341
382
  - **`scope: "workspace"` survives Pi.** No fd 3, no owner watch. On the next
342
383
  `session_start` in the same directory, a run whose owner identity is dead is
343
- re-adopted: the event log is folded, the tail resumes, and the settle is
344
- delivered here. A run whose owner is alive is read-only. A record with no exit
345
- 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`.
346
387
  - **Logs drain past the cap.** 32 MiB per stream by default. Past the cap the
347
- supervisor stops appending the raw payload and keeps reading, because a reader
348
- that stops reading turns a logging policy into a hung child. It still writes
349
- compact turn, usage, cost, and breaker records to `control.jsonl`, so a capped
350
- payload log cannot blind the parent's budgets or no-progress enforcement.
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.
351
392
  - **The fence is the containment guarantee, where a process table exists.**
352
393
  Cancellation unions three views: processes tagged `PI_DELEGATE_RUN=<id>`, live
353
- descendants of the captured `(boot_id, pid, start)` identity, and live members
354
- of the owned process group. Each pid start time is re-read before signalling, so
355
- a reused pid is never killed. A process group alone is not containment:
356
- `setsid(2)` escapes it. Off Linux the group is what is left, and it is enough to
357
- kill: `spawn(detached: true)` makes the supervisor a session leader, so its pid
358
- *is* the process group id and `kill(-pgid)` reaches the whole tree without asking
359
- the kernel anything.
360
- - **The group handle is not a guess.** `pgidFor()` returns the detached
361
- supervisor's own pid on POSIX. It used to be read from `/proc/<pid>/stat`, which
362
- meant every non-Linux platform had an empty group list, so `killGroup` had
363
- 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.
364
399
 
365
400
  ## Permission asks
366
401
 
367
- The child is started with `PI_SUBAGENT_PARENT_SESSION=<session id>`, the
368
- convention `@gotgenes/pi-permission-system` documents for out-of-process
369
- subagents. A gated tool call in the child is forwarded to the delegating session,
370
- so authority stays with the human instead of failing closed with "no interactive
371
- UI is available". Without a human to answer, the child reports `blocked`. The
372
- marker is never overwritten when one is already present, so a chain of
373
- 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.
374
409
 
375
410
  This is a declared dependency on another package's environment convention, not on
376
- its code. It is why a delegated child is not a security boundary of its own:
377
-
378
- - **Nothing here reads or writes that extension.** This package sets one
379
- environment variable and `@gotgenes/pi-permission-system` reads it. If that
380
- package is not installed, the variable is inert and nothing changes.
381
- - **The convention can move.** If that package changes the variable name, gated
382
- calls in the child fall back to whatever that extension does by default
383
- (usually "deny, no interactive UI"), and the child reports `blocked`. It does
384
- not become silently permissive.
385
- - **A different permission extension sees nothing.** Another implementation of
386
- permission gating will not honour this marker, so an approval ask from a child
387
- fails closed there. `isolated: true` is the other answer for a host that cannot
388
- answer asks at all: built-in tools only, no ambient extension, skill, MCP
389
- server, or AGENTS.md.
390
-
391
- `isolated: true` is the other answer for a host that cannot answer asks: the child
392
- runs with built-in tools only, no ambient extension, skill, MCP server, or
393
- 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`.
394
417
 
395
418
  ## Command
396
419
 
@@ -400,23 +423,58 @@ AGENTS.md.
400
423
  /delegate list delegations in this session
401
424
  /delegate read <id|prefix> one run in full
402
425
  /delegate log <id|prefix> tail the child stderr
426
+ /delegate send <id> <text> steer a running child
403
427
  /delegate cancel <id|prefix|all> cancel with the ladder
428
+ /delegate doctor check this installation
404
429
  ```
405
430
 
406
431
  Options may appear anywhere, as `--name value` or `--name=value`: `--model`,
407
- `--turns`, `--minutes`, `--cost`, `--done`, `--context`, `--verify`,
408
- `--tools`, `--scope`, `--isolated`, `--worktree`, `--resume`, `--cwd`, `--depth`,
409
- `--schema`. `--verify` is the same completion gate the tool takes: it runs inside
410
- the child at `delegate_complete`, and the parent re-runs it with the child's
411
- dropped-environment policy before the claim is accepted.
412
- `/delegate send <id> <text>` is the steering path, the same as `delegate_send`.
413
- The command accepts what the tool schema accepts:
414
- `--turns` is 1-500, `--minutes` is 1-240, and a relative `--cwd` resolves
415
- against the session directory rather than the process working directory. A bare
416
- `--` ends option parsing, so a goal may contain its own `--words`.
417
-
418
- Outside the TUI the command waits for the outcome and prints it, because nothing
419
- else keeps a print-mode process alive for a session-scoped child.
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:
447
+
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".
420
478
 
421
479
  ## Artifacts
422
480
 
@@ -437,33 +495,29 @@ else keeps a print-mode process alive for a session-scoped child.
437
495
  | `owner.lock` | parent | The adoption claim, created with `O_EXCL`. One owner at a time. |
438
496
 
439
497
  Each file has exactly one writer. `state.json` replaced `pid.json`, `exit.json` and
440
- `log-cap.json`, which described the same process in three files that a reader had
441
- to merge: two writers of one fact is how they disagree. Records written by a
442
- 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.
443
500
 
444
- Each run directory is created `0700` and every record inside it is written
445
- `0600`. The record holds the goal, the context note, and the child's full output
446
- on a possibly shared machine, so it is private to the user who started it.
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.
447
504
 
448
- Nothing reads a directory after its outcome is sealed, and records are reclaimed
449
- automatically. Retention is bounded three times: a record older than
505
+ ### Retention
506
+
507
+ Records are reclaimed automatically, bounded three times: a record older than
450
508
  `PI_DELEGATE_RETENTION_DAYS` (default 7) is removed, once the count passes
451
509
  `PI_DELEGATE_MAX_RUNS` (default 100) the oldest surplus is removed, and once the
452
- total passes `PI_DELEGATE_MAX_BYTES` (default 512 MiB) the oldest records are
453
- removed until it fits. The byte cap is the one that bounds the worst case:
454
- 32 MiB of stdout and 32 MiB of stderr per run times a hundred kept runs is 6.4 GB
455
- that no count or age limit ever reached.
456
-
457
- A record is never removed while it can still produce a verdict: a run this
458
- process follows, a record whose supervisor is alive, or one younger than ten
459
- minutes. Deleting a record removes a worktree inside the record root only through
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
460
518
  `git worktree remove`, only when it is clean, and only when no other run references
461
- it. A dirty checkout and its record stay in place. Delete old runs whenever you
462
- like; the next session prunes the rest.
463
-
464
- Runs recorded before this rename stay in `~/.pi/agent/goal-handoff/`. Nothing
465
- reads them, and the old extension is retired to
466
- `~/.pi/agent/retired-extensions/goal-handoff/`.
519
+ it. `/delegate doctor` reports the plan before the next prune runs it, so retention
520
+ is predictable rather than a surprise.
467
521
 
468
522
  ### Environment
469
523
 
@@ -483,6 +537,29 @@ reads them, and the old extension is retired to
483
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. |
484
538
  | `PI_SUBAGENT_PARENT_SESSION` | Set for the child unless one is already present. Names the session that answers forwarded permission asks. |
485
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
+
486
563
  ## Tests
487
564
 
488
565
  From the repository root:
@@ -497,68 +574,86 @@ pnpm run test:coverage
497
574
  | Suite | Covers |
498
575
  |---|---|
499
576
  | `tests/delegate.test.mjs` | lifecycle, event folding, containment, claims, the cancellation grace period, the status footer, reload |
500
- | `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 |
501
580
  | `tests/worker.test.mjs` | the child's circuit breakers and terminal states, in a real subprocess |
502
581
  | `tests/events.test.mjs` | the event stream: unknown records, error carriers, the incremental tailer |
503
582
  | `tests/isolation.test.mjs` | directory-scoped workspace adoption, per-session registries |
504
583
  | `tests/adoption.test.mjs` | re-adoption against a supervisor that is actually running |
505
584
  | `tests/failure.test.mjs` | wall-clock deadlines, a supervisor killed from outside, an exit with no verdict |
506
- | `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 |
507
586
  | `tests/supervisor.test.mjs` | sealed exit records, controlled exit, log cap, the owner watch |
508
- | `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` |
509
588
  | `tests/guard.test.mjs` | the child-side recursion guard, parameter validation, declared bounds |
510
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. |
511
590
  | `tests/gates.test.mjs` | the live-admission gate, the spend cap, verified completion, the adoption claim, steering, worktrees, and typed record reads |
512
591
  | `tests/result-schema.test.mjs` | the `resultSchema` admission audit and the instance path a rejected value is told |
513
592
 
514
- `tests/support.mjs` holds what every suite needs: temporary directories removed
515
- when the test ends, the `PI_DELEGATE_*` environment restored after each test, and
516
- `waitFor` in place of fixed sleeps. 188 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.
517
599
 
518
600
  CI runs the whole suite on Linux against Node 22, 24 and 26, and runs
519
- `tests/containment.test.mjs` plus `tests/gates.test.mjs` on `macos-latest`: those
520
- are the suites that exercise cancellation and adoption where `/proc` does not
521
- 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.
522
604
 
523
605
  No suite needs a model or a network. The lifecycle suites spawn the fake child in
524
- `tests/fixtures/fake-pi.mjs`, which emits a real JSON event stream and seals a
525
- real verdict, and which can also refuse SIGTERM so a grace period is observable; the worker suite drives the real `worker.ts` through
526
- `tests/fixtures/worker-host.mjs`. The e2e suite loads the extension through Pi's
527
- own loader and resolves Pi's host packages from an explicit `PI_HOST_MODULES`
528
- override first, then from the project's own `node_modules`, then from the newest
529
- `~/.pi/agent/managed-runtime/releases` entry, so a clean clone with
530
- `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.
531
613
 
532
614
  ## Limits
533
615
 
534
- - **Containment is platform-dependent, and the verdict says which one ran.**
535
- Linux gets full observation: procfs identity, the tag scan, the descendant walk,
536
- and the owned process group. macOS and other POSIX platforms get the process
537
- group, which the detached supervisor leads, probed with signal 0: cancellation
538
- works, and the verdict is `gone` or `leaked` on real evidence. Windows gets
539
- `taskkill /T` and no observation, so its verdict is `unproven` — the tree is
540
- asked to die and the parent says so instead of claiming proof. A `setsid(2)`
541
- child that also clears its environment and loses its parent is out of reach on
542
- any platform.
543
- - **A delegation is not a sandbox.** The child runs with the parent's authority,
544
- 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
545
625
  `PI_DELEGATE_ENV_DROP`). `tools` and `isolated` bound the surface, not the
546
- permission.`
547
- - **A session-scoped run cannot outlive the session.** Use `workspace` for that.
548
- In print mode a session run is cancelled when the process exits, so a print
549
- caller should await it.
550
- - **`isolated: true` also drops provider extensions.** A custom provider that
551
- lives in an extension is unavailable to an isolated child.
552
- - **A delegated child inherits the parent filesystem and network permissions.**
553
- Tool allowlists bound the surface, not the sandbox.
554
- - **`delegate_await` blocks the tool call.** A tool call cannot be suspended here.
555
- Waits measured in minutes belong to the completion message.
556
- - **The workspace adoption scan reads the global run root.** A record is adopted
557
- only when it was started by this session's directory (its recorded session
558
- directory, or the child `cwd` for a record written before that field existed;
559
- both are compared through `realpath`), and its owner is gone. Two sessions in
560
- 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
561
635
  directory is never adopted.
562
- - **The no-progress rule is a heuristic.** Two identical answers with no tool call
563
- end the run in either observer; a child that varies its wording while doing
564
- nothing can 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.