pi-goal-delegate 0.1.0 → 0.2.0

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/CHANGELOG.md CHANGED
@@ -4,6 +4,63 @@ All notable changes to this package are recorded here. The format follows
4
4
  [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
5
5
  [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [0.2.0] - 2026-12-01
8
+
9
+ ### Added
10
+
11
+ - **Structured results.** `delegate_start({ resultSchema })` and a third
12
+ `delegate_complete(summary, evidence, result)` argument give a codemode
13
+ orchestrator a validated JSON value instead of prose it has to parse. The value
14
+ is capped at 64,000 characters, and a rejection names the failing instance path
15
+ and the reason, so the repair is one call rather than a guess.
16
+ - **An admission audit for that schema.** A `resultSchema` that no value could
17
+ satisfy - an unresolved local `$ref`, a reference into a document this package
18
+ cannot reach, a shape TypeBox cannot evaluate - is refused at `delegate_start`,
19
+ where the caller can still fix the contract, instead of failing every completion
20
+ claim the child has no way to repair.
21
+ - **Nested delegation.** `maxDepth` (0-3) and `/delegate --depth` let a child
22
+ decompose its own goal. Depth, spend and deadline attenuate down the tree: one
23
+ `attenuationRefusal` in `contract.ts` answers for every entry point, and a
24
+ child's goal prompt reports the minutes the run actually has rather than the
25
+ minutes its parent asked for.
26
+ - **Worktree integration.** A worktree run's outcome carries `integration`: HEAD,
27
+ dirty status with git's positional columns intact, diff statistics, an
28
+ applicable `changes.patch` covering committed, tracked-uncommitted and untracked
29
+ work, and the result of `git apply --check` against the original repository.
30
+ `applyCommand` is the explicit integration path; nothing is committed or merged
31
+ automatically.
32
+ - **`control.jsonl`.** Compact turn, usage, cost, text and breaker records beside
33
+ the capped raw log, so a 32 MiB payload cap can no longer blind the parent's
34
+ budgets or its no-progress enforcement. The stream decodes statefully: a chunk
35
+ that splits a multi-byte character no longer corrupts the last text or a call
36
+ signature, and a final line without a newline is still folded.
37
+ - `/delegate` adds `--depth` and `--schema`.
38
+
39
+ ### Changed
40
+
41
+ - **`verify` gates the completion claim instead of auditing it afterwards.** It
42
+ runs inside the live child at `delegate_complete`: a failure returns the command
43
+ output to the child for repair, and only a passing claim terminates the run. A
44
+ cancelled or expired run does not start the check at all. The parent then
45
+ independently re-runs the same command under the same `PI_DELEGATE_ENV_DROP`
46
+ policy, and `childVerification` keeps the two records apart.
47
+ - **Steering is delivered as `steer` at `turn_start`** instead of being held
48
+ until `agent_settled`, where a child that was already done could miss it.
49
+ - **A resume continues the checkout.** Resuming a worktree-backed run reuses that
50
+ worktree instead of moving back to the shared tree, and records `resumedFrom`.
51
+ Retention removes a clean checkout through `git worktree remove` and preserves a
52
+ dirty or shared one, including the checkout of a run that never sealed.
53
+ - **An ordinary completion carries the whole outcome** within a 24,000-character
54
+ budget, so the parent does not spend a second call on what it already has. The
55
+ compact form keeps `summary`, `evidence` and `needs` as the distinct fields
56
+ they are.
57
+
58
+ ### Fixed
59
+
60
+ - The parent observes the shared circuit breakers from the child's stream, and
61
+ admission slots are reserved synchronously, so a concurrent `Promise.all` cannot
62
+ start more children than the live limit allows.
63
+
7
64
  ## [0.1.0] - 2026-12-01
8
65
 
9
66
  First published release under the package name `pi-goal-delegate`. It replaces
@@ -151,4 +208,5 @@ so there is no `[Unreleased]` section to merge forward.
151
208
  environment is still inherited by default, because a provider key in it is how
152
209
  the child authenticates.
153
210
 
211
+ [0.2.0]: https://github.com/Zhuocheng-Lang/pi-goal-delegate/compare/v0.1.0...v0.2.0
154
212
  [0.1.0]: https://github.com/Zhuocheng-Lang/pi-goal-delegate/releases/tag/v0.1.0
package/README.md CHANGED
@@ -82,10 +82,12 @@ returns.
82
82
  | `goal` | required | The objective, self-contained. |
83
83
  | `doneWhen` | child decides | Verifiable completion criteria. Prefer "a command exits 0", not "it works". |
84
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)). |
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. |
86
87
  | `maxTurns` | 150 | Model turns. One turn is one assistant response plus its tool calls. |
87
88
  | `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. |
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. |
89
91
  | `model` | parent model | `provider/id`, passed to the child explicitly (see [Model](#model)). |
90
92
  | `tools` | inherited | Allowlist for the child. The protocol tools, and `codemode` when the parent has it, are always kept. |
91
93
  | `cwd` | session cwd | Working directory. |
@@ -106,9 +108,11 @@ so unlike `delegate_await` it never consumes the completion message.
106
108
 
107
109
  `delegate_send(runId, text)` hands a running child one message. The parent
108
110
  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.
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`.
112
116
 
113
117
  ### `delegate_await`
114
118
 
@@ -139,7 +143,7 @@ when nothing was observable: an absence of observation read as proof of absence.
139
143
 
140
144
  The child gets exactly two tools that end the loop:
141
145
 
142
- - `delegate_complete(summary, evidence)` - verified done. Evidence is commands, files, checks.
146
+ - `delegate_complete(summary, evidence, result?)` - completion-gated done. Evidence is commands, files, checks; `result` is validated when `resultSchema` is present.
143
147
  - `delegate_blocked(reason, needs)` - a decision, credential, or fact the child cannot obtain.
144
148
 
145
149
  Foreign goal tools (`goal_complete`, `goal_blocked`, `goal_wait`, the old
@@ -172,7 +176,7 @@ the hours and risk aborting a healthy child.
172
176
  | `complete` | child | `delegate_complete`, and the `verify` command, if any, exited 0. |
173
177
  | `unverified` | parent | The child said complete, and the parent ran `verify` and it failed. |
174
178
  | `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. |
179
+ | `no_progress` | child or parent | Circuit breaker: repeated identical call, consecutive failures, or two identical no-tool turns. |
176
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. |
177
181
  | `timeout` | parent and child | Wall clock. Parent enforces with the ladder; child enforces on its own for `workspace` runs. |
178
182
  | `aborted` | parent | `delegate_cancel`. |
@@ -187,7 +191,8 @@ orchestrator branching on `isError` read a stalled child as a finished one.
187
191
 
188
192
  ## Verification
189
193
 
190
- `doneWhen` is prose for the child. `verify` is a command for the parent:
194
+ `doneWhen` is prose for the child. `verify` is an executable completion gate for
195
+ both sides:
191
196
 
192
197
  ```js
193
198
  await tools.delegate_start({
@@ -196,8 +201,14 @@ await tools.delegate_start({
196
201
  });
197
202
  ```
198
203
 
199
- After the child reports `complete`, the parent runs that command in the child's
200
- own directory and records `verified`:
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
207
+ terminates the child. The parent then independently runs the same command before
208
+ accepting the outcome, using the same `PI_DELEGATE_ENV_DROP` policy so verification
209
+ cannot regain credentials withheld from the child.
210
+
211
+ The parent's recheck records `verified`:
201
212
 
202
213
  | `verified` | Meaning |
203
214
  |---|---|
@@ -206,8 +217,8 @@ own directory and records `verified`:
206
217
  | `"not-run"` | The run carried no verify command, so the evidence is the child's own account and nothing more. |
207
218
 
208
219
  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.
220
+ its own check failed, not that the child never spoke. `childVerification` preserves
221
+ the successful child-side gate separately from the parent's `verification` record.
211
222
 
212
223
  ## Budgets, and why the defaults are these numbers
213
224
 
@@ -219,9 +230,10 @@ recorded `turns: 1` for a 265-turn session and bounded nothing.
219
230
  `timeoutMinutes` defaults to 60. A 30-minute cap would have cut 14 of those 42
220
231
  runs; 60 minutes keeps 90% of them.
221
232
 
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
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
225
237
  `contract.ts` as pure functions over one state record, because the parent reads
226
238
  the same rules from the child's event stream and two copies of a threshold is two
227
239
  answers to "was this run stuck".
@@ -240,8 +252,9 @@ Wait for one to settle, cancel one with delegate_cancel, or raise
240
252
  PI_DELEGATE_MAX_LIVE (currently 4, maximum 32).
241
253
  ```
242
254
 
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
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
245
258
  "unlimited".
246
259
 
247
260
  ### Cost
@@ -252,6 +265,11 @@ ends as `limit` with the amount in the summary. It is off by default
252
265
  (`PI_DELEGATE_MAX_COST_USD=0`): a cap that kills a healthy run by default is worse
253
266
  than no cap.
254
267
 
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.
272
+
255
273
  ## Parallel children and worktrees
256
274
 
257
275
  Two children editing one working tree fight over every file: a build in one
@@ -264,23 +282,30 @@ await tools.delegate_start({ goal: "...", worktree: true });
264
282
 
265
283
  The parent runs `git worktree add --no-track -b delegate/<runId>
266
284
  <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.
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
288
+ committed, tracked-uncommitted, and untracked work. Nothing is automatically
289
+ committed or merged; `integration.applyCommand` is the explicit integration path.
269
290
 
270
291
  The checkout is **kept by default**: it holds the only copy of the child's work.
271
292
  `PI_DELEGATE_KEEP_WORKTREES=0` opts into cleanup, and even then only a clean tree
272
293
  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.
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.
276
298
 
277
299
  ## Resuming a run
278
300
 
279
301
  `outcome.sessionFile` is the child's own Pi session. `delegate_start({ resumeFrom:
280
302
  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.
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.
284
309
 
285
310
  ## Model
286
311
 
@@ -302,7 +327,7 @@ the recorded runs the cost was $0.08 to $2.42 per delegation.
302
327
 
303
328
  `delegate_start` spawns `supervisor.mjs`, a detached Node process in its own
304
329
  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
330
+ `child.jsonl`, `child.log`, and the compact accounting stream `control.jsonl`. Pi holds no pipe to the child, which is what makes
306
331
  the rest possible:
307
332
 
308
333
  - **`/reload` transfers ownership.** The live registry is published to a
@@ -311,16 +336,18 @@ the rest possible:
311
336
  nobody claims within 30 seconds expires into cancellation, so a handle is never
312
337
  left unowned.
313
338
  - **`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.
339
+ the owning Pi died, so the tree is torn down. Bytes on fd 3 are not a protocol;
340
+ `/reload` transfers the in-process registry without changing supervisor ownership.
316
341
  - **`scope: "workspace"` survives Pi.** No fd 3, no owner watch. On the next
317
342
  `session_start` in the same directory, a run whose owner identity is dead is
318
343
  re-adopted: the event log is folded, the tail resumes, and the settle is
319
344
  delivered here. A run whose owner is alive is read-only. A record with no exit
320
345
  and no provable liveness becomes `lost`.
321
346
  - **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.
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.
324
351
  - **The fence is the containment guarantee, where a process table exists.**
325
352
  Cancellation unions three views: processes tagged `PI_DELEGATE_RUN=<id>`, live
326
353
  descendants of the captured `(boot_id, pid, start)` identity, and live members
@@ -378,7 +405,10 @@ AGENTS.md.
378
405
 
379
406
  Options may appear anywhere, as `--name value` or `--name=value`: `--model`,
380
407
  `--turns`, `--minutes`, `--cost`, `--done`, `--context`, `--verify`,
381
- `--tools`, `--scope`, `--isolated`, `--worktree`, `--resume`, `--cwd`.
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.
382
412
  `/delegate send <id> <text>` is the steering path, the same as `delegate_send`.
383
413
  The command accepts what the tool schema accepts:
384
414
  `--turns` is 1-500, `--minutes` is 1-240, and a relative `--cwd` resolves
@@ -397,10 +427,12 @@ else keeps a print-mode process alive for a session-scoped child.
397
427
  | `spec.json` | parent | The exact contract the child received, including the child command line. Written once, at admission. |
398
428
  | `meta.json` | parent | Scope, status, session directory, supervisor identity, owner identity, containment mode. |
399
429
  | `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. |
430
+ | `child.jsonl` | supervisor | The raw child JSON event stream, capped at 32 MiB. |
431
+ | `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
432
  | `child.log` | supervisor | The child stderr. |
402
433
  | `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. |
434
+ | `outcome.json` | parent | The sealed outcome, including structured result and integration metadata, readable after the parent is gone. |
435
+ | `changes.patch` | parent | For worktree runs with changes: committed, tracked, and untracked work exported without an automatic commit. |
404
436
  | `inbox.jsonl` | parent | Steering messages, one JSON line each. The child reads the file at `turn_start`. |
405
437
  | `owner.lock` | parent | The adoption claim, created with `O_EXCL`. One owner at a time. |
406
438
 
@@ -424,9 +456,10 @@ that no count or age limit ever reached.
424
456
 
425
457
  A record is never removed while it can still produce a verdict: a run this
426
458
  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.
459
+ minutes. Deleting a record removes a worktree inside the record root only through
460
+ `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.
430
463
 
431
464
  Runs recorded before this rename stay in `~/.pi/agent/goal-handoff/`. Nothing
432
465
  reads them, and the old extension is retired to
@@ -476,10 +509,11 @@ pnpm run test:coverage
476
509
  | `tests/guard.test.mjs` | the child-side recursion guard, parameter validation, declared bounds |
477
510
  | `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
511
  | `tests/gates.test.mjs` | the live-admission gate, the spend cap, verified completion, the adoption claim, steering, worktrees, and typed record reads |
512
+ | `tests/result-schema.test.mjs` | the `resultSchema` admission audit and the instance path a rejected value is told |
479
513
 
480
514
  `tests/support.mjs` holds what every suite needs: temporary directories removed
481
515
  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.
516
+ `waitFor` in place of fixed sleeps. 188 tests, no model and no network.
483
517
 
484
518
  CI runs the whole suite on Linux against Node 22, 24 and 26, and runs
485
519
  `tests/containment.test.mjs` plus `tests/gates.test.mjs` on `macos-latest`: those
@@ -525,6 +559,6 @@ override first, then from the project's own `node_modules`, then from the newest
525
559
  both are compared through `realpath`), and its owner is gone. Two sessions in
526
560
  different directories never adopt each other's runs, and a record from a deleted
527
561
  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.
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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-goal-delegate",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Bounded delegation for Pi: one self-contained goal, a fresh child agent, and a contract that says when it is done and what proves it.",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: delegate
3
- description: Hand a self-contained goal to a fresh child agent under a verification contract, then let its completion wake the session. Use for work worth many turns in a clean context, for parallel fan-out through codemode, for a goal that outlives one Pi session, and whenever a task needs evidence rather than a claim.
3
+ description: Hand a self-contained goal to a fresh child agent under a verification contract, then let its completion wake the session. Use when the work needs many turns in a clean context, when you fan out parallel goals through codemode, when a goal outlives one Pi session, or when a task needs evidence rather than a claim.
4
4
  ---
5
5
 
6
6
  # Delegation
@@ -19,11 +19,12 @@ When a task takes one tool call, needs user input at each step, or requires this
19
19
 
20
20
  ## Write the contract
21
21
 
22
- Each parameter has a schema in `delegate_start`. Shape the three contract fields and overrides as follows:
22
+ Each parameter has a schema in `delegate_start`. Shape the contract fields and overrides as follows:
23
23
 
24
24
  - **goal**: Name the target artifact in one imperative objective: `"Make pnpm test pass in packages/app"` instead of `"look at the tests"`.
25
25
  - **doneWhen**: State a falsifiable condition: a command exits 0, a test passes, or a file has specific content.
26
- - **verify**: When a single command proves the goal, pass it here. The parent runs it after the child claims completion, and a non-zero exit turns the run into `unverified`. `doneWhen` is prose for the child; `verify` is the check the parent actually runs.
26
+ - **verify**: Pass the single command that proves the goal. It gates `delegate_complete`. A failure returns the output to the live child for repair. After a passing claim, the parent independently re-runs the command with the same dropped-environment policy. A parent failure turns the run into `unverified`.
27
+ - **resultSchema**: Pass a JSON Schema so codemode gets deterministic structured output. `delegate_start` refuses an unusable schema (an unresolved `$ref`) up front instead of letting it fail every completion. The child must then supply `delegate_complete({ summary, evidence, result })`. `delegate_complete` rejects an invalid result shape and keeps the run alive.
27
28
  - **context**: Include only non-discoverable facts: prior decisions, exact paths, constraints, and files to leave unchanged. Omit conversation transcripts.
28
29
  - **Overrides**:
29
30
  - When the work is read-only or restricted, pass `tools` (for example `"read,grep"`).
@@ -31,22 +32,18 @@ Each parameter has a schema in `delegate_start`. Shape the three contract fields
31
32
  - When a refactor exceeds the 90th-percentile budget (150 turns, 60 minutes), raise `maxTurns`. Split a slow goal instead of raising `timeoutMinutes`.
32
33
  - When the run must survive closing Pi, pass `scope: "workspace"`. Only a later session in the same directory re-adopts it.
33
34
  - When the host cannot answer permission asks or must exclude ambient extensions, skills, MCP servers, and context files, pass `isolated: true`.
34
- - When two children would edit the same tree, pass `worktree: true`. Each gets its own checkout and branch, recorded in `outcome.worktree`.
35
- - When the goal continues earlier work, pass `resumeFrom` with the previous run id instead of repeating its context.
36
- - When spend must be bounded, pass `maxCostUsd`. A run that crosses it ends as `limit`.
35
+ - When two children would edit the same tree, pass `worktree: true`. Each gets its own checkout and branch. Read `outcome.integration` for status, diff stat, `changes.patch`, and `applyCheck`. Nothing is auto-committed or merged.
36
+ - When the child must decompose its goal, pass `maxDepth` (0-3). Default 0 disables nested delegation. A child stays within the parent's depth, spend, and deadline limits.
37
+ - When the goal continues earlier work, pass `resumeFrom` with the previous run id instead of repeating its context. A worktree-backed run resumes in the same checkout. `resumedFrom` records the lineage. The new run gets a fresh budget.
38
+ - When a run needs a spend cap, pass `maxCostUsd`. A run that crosses the cap ends as `limit`. The cap applies to one run only. A child's cap stays at or below its parent's cap. The platform sums no caps across the tree.
37
39
 
38
40
  ## Steer instead of restarting
39
41
 
40
- `delegate_send(runId, text)` hands a running child one message. It is read at the
41
- child's next turn start, so it redirects work already in progress. Correcting
42
- course costs one call; cancelling and starting again costs the whole budget and
43
- the context.
42
+ `delegate_send(runId, text)` hands a running child one message. The child reads it at its next turn start. Pi queues it with `deliverAs: "steer"`, so it lands before the next model call instead of waiting for settle. Correcting course costs one call. Restarting costs the whole budget and the context.
44
43
 
45
44
  ## At most a few at once
46
45
 
47
- One session keeps `PI_DELEGATE_MAX_LIVE` delegations live, four by default. A
48
- larger fan-out is refused with the live runs named. Fan out in waves, or raise the
49
- limit deliberately.
46
+ One session keeps `PI_DELEGATE_MAX_LIVE` delegations live, four by default. `delegate_start` refuses a larger fan-out and names the live runs. Fan out in waves, or raise the limit deliberately.
50
47
 
51
48
  ## Fan out in codemode, wait outside it
52
49
 
@@ -66,8 +63,8 @@ Keep each codemode script to at most one `delegate_await` call within the 60-sec
66
63
 
67
64
  | Status | Meaning | Next action |
68
65
  |---|---|---|
69
- | `complete` | The child called `delegate_complete`. `verified: true` means the parent's own check passed; `"not-run"` means there was no check to run. | With `verified: true`, report success. With `"not-run"`, verify the `evidence` (run the command or read the diff) yourself first. |
70
- | `unverified` | The child claimed completion and the parent's `verify` command failed. | Read `verification.output`; the work is not done, whatever the child said. |
66
+ | `complete` | The child passed its completion gate. `verified: true` means the parent's independent `verify` run also passed. `"not-run"` means the parent supplied no `verify` command. Structured output is in `result`. | With `verified: true`, report success and consume `result` directly. With `"not-run"`, verify the `evidence` or `result` yourself first. |
67
+ | `unverified` | The child claimed completion and the parent's `verify` command failed. | Read `verification.output`. The work is not done, whatever the child said. |
71
68
  | `blocked` | The child needs a decision, credential, or fact. It is in `needs`, not `evidence`. | Start a new delegation with the answer in `context`, or ask the user. |
72
69
  | `no_progress` | A circuit breaker fired: repeated call, repeated failure, or two identical idle turns. | Narrow the goal or change the approach instead of restarting the same goal. |
73
70
  | `limit` | The turn budget or the spend cap ran out before a verdict. | Raise `maxTurns`/`maxCostUsd` or split the goal. |
package/src/command.ts CHANGED
@@ -15,8 +15,9 @@
15
15
 
16
16
  import { join, resolve } from "node:path";
17
17
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
18
- import { MAX_MAX_TURNS, MAX_TIMEOUT_MINUTES, shortGoal } from "./contract.ts";
18
+ import { MAX_MAX_DEPTH, MAX_MAX_TURNS, MAX_TIMEOUT_MINUTES, shortGoal } from "./contract.ts";
19
19
  import { readTail } from "./events.ts";
20
+ import { auditResultSchema } from "./result-schema.ts";
20
21
  import type { RunRegistry } from "./registry.ts";
21
22
  import { formatOutcome, type RunHandle } from "./run.ts";
22
23
 
@@ -28,7 +29,7 @@ const LOG_TAIL_BYTES = 64 * 1024;
28
29
  export interface DelegateCommandOptions {
29
30
  /** The registry of the session this command runs in. */
30
31
  registryFor: (ctx: ExtensionCommandContext) => RunRegistry;
31
- defaults: { maxTurns: number; timeoutMinutes: number; maxCostUsd?: number };
32
+ defaults: { maxTurns: number; timeoutMinutes: number; maxCostUsd?: number; maxDepth?: number };
32
33
  }
33
34
 
34
35
  const USAGE = [
@@ -41,8 +42,10 @@ const USAGE = [
41
42
  " --done <criteria> explicit completion criteria",
42
43
  " --context <facts> only what the child cannot discover itself",
43
44
  " --tools <list> child tool allowlist, e.g. read,grep",
44
- " --verify <command> command the parent runs to prove a complete verdict",
45
- " --cost <usd> cumulative spend cap, 0 disables it",
45
+ " --verify <command> gates delegate_complete, then the parent re-runs it",
46
+ " --cost <usd> per-run spend cap in USD, 0 disables it",
47
+ " --depth <n> maximum delegation-tree depth, 0-3 (default 0)",
48
+ " --schema <json> JSON Schema for the child's structured result",
46
49
  " --scope <session|workspace> workspace survives Pi exiting",
47
50
  " --isolated no ambient extensions, skills, MCP servers, or context files",
48
51
  " --worktree give the child its own git worktree and branch",
@@ -59,6 +62,8 @@ const KNOWN_FLAGS = new Set([
59
62
  "turns",
60
63
  "minutes",
61
64
  "cost",
65
+ "depth",
66
+ "schema",
62
67
  "done",
63
68
  "context",
64
69
  "verify",
@@ -341,6 +346,8 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
341
346
  let maxTurns: number;
342
347
  let timeoutMinutes: number;
343
348
  let maxCostUsd: number;
349
+ let maxDepth: number;
350
+ let resultSchema: Record<string, unknown> | undefined;
344
351
  let scope: "session" | "workspace";
345
352
  let isolated: boolean;
346
353
  let worktree: boolean;
@@ -348,6 +355,28 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
348
355
  maxCostUsd = parsed.flags.cost === undefined
349
356
  ? (options.defaults.maxCostUsd ?? 0)
350
357
  : boundedNumber(parsed.flags.cost, 0, "cost", { min: 0, max: 10_000 });
358
+ maxDepth = boundedNumber(parsed.flags.depth, options.defaults.maxDepth ?? 0, "depth", {
359
+ min: 0,
360
+ max: MAX_MAX_DEPTH,
361
+ integer: true,
362
+ });
363
+ if (parsed.flags.schema === undefined) {
364
+ resultSchema = undefined;
365
+ } else {
366
+ let decoded: unknown;
367
+ try {
368
+ decoded = JSON.parse(parsed.flags.schema);
369
+ } catch (error) {
370
+ throw new Error(`--schema must be valid JSON: ${String(error)}`);
371
+ }
372
+ if (typeof decoded !== "object" || decoded === null || Array.isArray(decoded)) {
373
+ throw new Error("--schema must be a JSON Schema object.");
374
+ }
375
+ const schema = decoded as Record<string, unknown>;
376
+ const problem = auditResultSchema(schema);
377
+ if (problem) throw new Error(problem.startsWith("resultSchema") ? problem.replace("resultSchema", "--schema") : problem);
378
+ resultSchema = schema;
379
+ }
351
380
  worktree = booleanFlag(parsed.flags.worktree, false, "worktree");
352
381
  maxTurns = boundedNumber(parsed.flags.turns, options.defaults.maxTurns, "turns", {
353
382
  min: 1,
@@ -381,6 +410,8 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
381
410
  maxTurns,
382
411
  timeoutMinutes,
383
412
  maxCostUsd,
413
+ maxDepth,
414
+ resultSchema,
384
415
  model: parsed.flags.model,
385
416
  tools: parsed.flags.tools,
386
417
  cwd: runCwd,
@@ -396,7 +427,7 @@ export function registerDelegateCommand(pi: ExtensionAPI, options: DelegateComma
396
427
  [
397
428
  `delegate started · ${handle.runId}`,
398
429
  `Goal: ${shortGoal(parsed.goal, 90)}`,
399
- `Budget: ${maxTurns} turns, ${timeoutMinutes} minutes, scope ${scope}${isolated ? ", isolated" : ""}${worktree ? ", own worktree" : ""}${maxCostUsd > 0 ? `, \$${maxCostUsd} cap` : ""}`,
430
+ `Budget: ${maxTurns} turns, ${timeoutMinutes} minutes, depth ${maxDepth}, scope ${scope}${isolated ? ", isolated" : ""}${worktree ? ", own worktree" : ""}${maxCostUsd > 0 ? `, \$${maxCostUsd} cap` : ""}`,
400
431
  "The result is posted into this session when the child settles.",
401
432
  ].join("\n"),
402
433
  );