@xzzpig/pi-subagents 0.15.1 → 0.18.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.
Files changed (135) hide show
  1. package/CHANGELOG.md +178 -1
  2. package/README.md +5 -3
  3. package/agents/claude-code-writer.md +1 -0
  4. package/agents/codex-exec-writer.md +1 -0
  5. package/agents/cursor-agent-writer.md +1 -0
  6. package/agents/reviewer.md +3 -2
  7. package/agents/worker.md +3 -2
  8. package/docs/agents.md +19 -12
  9. package/docs/configuration.md +21 -3
  10. package/docs/extension-api.md +70 -4
  11. package/docs/fork-extensions.md +23 -15
  12. package/docs/models.md +5 -3
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +4 -4
  15. package/docs/tool-reference.md +40 -19
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +57 -3
  18. package/inspector-runner.mjs +1 -1
  19. package/package.json +14 -8
  20. package/prompts/council.md +6 -3
  21. package/runner-peer-loader.mjs +4 -7
  22. package/runner-peer-preload.mjs +5 -7
  23. package/skills/pi-subagents/SKILL.md +1 -0
  24. package/skills/pi-subagents/references/constraints-and-recipes.md +5 -2
  25. package/skills/pi-subagents/references/execution-controls.md +6 -4
  26. package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
  27. package/skills/pi-subagents/references/multi-lane-orchestration.md +8 -0
  28. package/skills/pi-subagents/references/prompting-and-roles.md +16 -15
  29. package/src/agents/agent-eject.ts +3 -3
  30. package/src/agents/agent-management.ts +61 -52
  31. package/src/agents/agent-memory.ts +90 -3
  32. package/src/agents/agent-serializer.ts +4 -4
  33. package/src/agents/agents.ts +125 -51
  34. package/src/agents/global-npm-root.ts +58 -0
  35. package/src/agents/proactive-skills.ts +4 -1
  36. package/src/agents/runtime-agent-registry.ts +14 -11
  37. package/src/agents/skills.ts +42 -9
  38. package/src/api/delegation.ts +15 -0
  39. package/src/api/inspectors.ts +27 -0
  40. package/src/api/preflight.ts +60 -60
  41. package/src/extension/doctor.ts +9 -4
  42. package/src/extension/fanout-child.ts +8 -0
  43. package/src/extension/index.ts +101 -48
  44. package/src/extension/rpc.ts +10 -1
  45. package/src/extension/schemas.ts +12 -6
  46. package/src/extension/subagent-guide.ts +12 -4
  47. package/src/extension/tool-activation.ts +197 -0
  48. package/src/extension/tool-description.ts +1 -1
  49. package/src/inspectors/ghostty/plugin.ts +13 -1
  50. package/src/inspectors/plugins.ts +70 -3
  51. package/src/intercom/intercom-bridge.ts +2 -0
  52. package/src/intercom/native-supervisor-channel.ts +22 -15
  53. package/src/intercom/result-intercom.ts +4 -0
  54. package/src/runs/background/active-async-capacity.ts +3 -25
  55. package/src/runs/background/async-execution.ts +100 -140
  56. package/src/runs/background/async-job-tracker.ts +28 -34
  57. package/src/runs/background/async-resume.ts +16 -8
  58. package/src/runs/background/async-status.ts +2 -0
  59. package/src/runs/background/binary-bootstrap.ts +34 -6
  60. package/src/runs/background/fleet-view.ts +51 -7
  61. package/src/runs/background/notify.ts +93 -7
  62. package/src/runs/background/pid-namespace.ts +18 -0
  63. package/src/runs/background/process-terminal-candidate.ts +98 -0
  64. package/src/runs/background/process-terminal.ts +17 -96
  65. package/src/runs/background/result-watcher.ts +1 -1
  66. package/src/runs/background/retained-children.ts +3 -2
  67. package/src/runs/background/run-child-session.ts +16 -5
  68. package/src/runs/background/run-id-resolver.ts +10 -5
  69. package/src/runs/background/run-status.ts +10 -4
  70. package/src/runs/background/runner-aliases.ts +25 -15
  71. package/src/runs/background/runner-child-launch.ts +1 -2
  72. package/src/runs/background/runner-startup-failure.ts +56 -0
  73. package/src/runs/background/stale-run-reconciler.ts +19 -3
  74. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  75. package/src/runs/background/subagent-runner.ts +96 -287
  76. package/src/runs/background/wait-tool.ts +2 -0
  77. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  78. package/src/runs/foreground/execution.ts +217 -250
  79. package/src/runs/foreground/prompt-audit.ts +3 -9
  80. package/src/runs/foreground/subagent-executor.ts +377 -119
  81. package/src/runs/shared/acceptance.ts +167 -68
  82. package/src/runs/shared/capability-ceiling.ts +4 -1
  83. package/src/runs/shared/child-hooks.ts +1 -16
  84. package/src/runs/shared/child-launch.ts +22 -14
  85. package/src/runs/shared/child-runtime-config.ts +3 -0
  86. package/src/runs/shared/child-session.ts +52 -2
  87. package/src/runs/shared/child-tool-plan.ts +23 -113
  88. package/src/runs/shared/dynamic-fanout.ts +1 -1
  89. package/src/runs/shared/external-cli-runner.ts +3 -1
  90. package/src/runs/shared/external-job-bridge.ts +54 -0
  91. package/src/runs/shared/git-environment.ts +29 -0
  92. package/src/runs/shared/mcp-config-sources.ts +3 -0
  93. package/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -1
  94. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  95. package/src/runs/shared/model-resolution.ts +6 -1
  96. package/src/runs/shared/nested-events.ts +67 -55
  97. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  98. package/src/runs/shared/parallel-utils.ts +2 -1
  99. package/src/runs/shared/pi-spawn.ts +92 -6
  100. package/src/runs/shared/profile-launch-env.ts +10 -2
  101. package/src/runs/shared/single-output.ts +11 -2
  102. package/src/runs/shared/structured-output.ts +227 -7
  103. package/src/runs/shared/subagent-control.ts +2 -16
  104. package/src/runs/shared/subagent-prompt-runtime.ts +27 -5
  105. package/src/runs/shared/tool-availability.ts +2 -2
  106. package/src/runs/shared/tool-budget.ts +21 -0
  107. package/src/runs/shared/usage-reconciliation.ts +73 -0
  108. package/src/runs/shared/worktree.ts +35 -8
  109. package/src/shared/child-session-name.ts +4 -2
  110. package/src/shared/fork-context.ts +11 -4
  111. package/src/shared/launch-contract.ts +1 -1
  112. package/src/shared/pruned-fork.ts +69 -56
  113. package/src/shared/types.ts +52 -16
  114. package/src/slash/delegation-adapters.ts +25 -1
  115. package/src/slash/prompt-template-bridge.ts +16 -1
  116. package/src/slash/prompt-workflows.ts +12 -1
  117. package/src/slash/slash-commands.ts +7 -241
  118. package/src/slash/subagent-cost.ts +313 -0
  119. package/src/slash/subagents-admin.ts +28 -29
  120. package/src/tui/fleet-status.ts +24 -2
  121. package/src/tui/fleet.ts +7 -4
  122. package/src/tui/render.ts +53 -19
  123. package/src/watchdog/diff-tool.ts +24 -3
  124. package/src/watchdog/permission-arbiter.ts +13 -15
  125. package/src/watchdog/register-child.ts +10 -2
  126. package/src/watchdog/review.ts +14 -14
  127. package/src/watchdog/runtime.ts +2 -1
  128. package/src/watchdog/turn-delta.ts +11 -5
  129. package/src/workflows/scripted-workflow.ts +109 -23
  130. package/src/workflows/workflow-child-summary.ts +4 -2
  131. package/src/workflows/workflow-settlement.ts +4 -1
  132. package/src/runs/shared/completion-evidence.ts +0 -89
  133. package/src/runs/shared/completion-guard.ts +0 -255
  134. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  135. package/src/runs/shared/task-intent.ts +0 -244
package/docs/workflows.md CHANGED
@@ -10,7 +10,7 @@ Use orchestration as parent-agent guidance, not as a runtime workflow mode. For
10
10
  clarify → scout → worker → fresh reviewers → worker
11
11
  ```
12
12
 
13
- Packaged `worker`, `oracle`, and `advisor` default to forked context when a launch omits `context`. If the parent has no persisted session file or current leaf yet, that implicit default falls back to `fresh`. Pass `context: "fresh"` when you intentionally want a fresh child run, or `context: "fork"` when fork must remain strict.
13
+ Packaged `worker` defaults to fresh context so implementation starts from its assigned brief instead of the parent's unfinished conversation. Packaged `oracle` and `advisor` default to forked context; if the parent has no persisted session file or current leaf yet, that implicit default falls back to `fresh`. Explicit `context`, `context: "profile"`, and global `defaultSubagentContext` still override these profile defaults.
14
14
 
15
15
  Child-safety boundaries are enforced at runtime:
16
16
 
@@ -51,6 +51,10 @@ Workflow-level child controls default onto each `runs.run`/`runs.all` launch; ex
51
51
 
52
52
  Child results cross into the script as plain JSON data. Non-JSON host metadata is omitted, so use returned fields such as `runId`, `ok`, `output`, and `structuredOutput` for workflow control.
53
53
 
54
+ Omitting a child's `async` preserves awaited final-result semantics, even if the child runs in the background. Explicit child `async: true` intentionally returns after launch: its receipt has `state: "running"`, `ok: false`, an empty `output`, and no completion error or final `outputReference`. `ok` confirms successful child completion, not successful dispatch. Use `runId` and `asyncDir` to inspect the running child; `artifactPaths` may include runtime directories and is not a list of final reports. Reusing the same workflow key returns the same receipt, not a refreshed result.
55
+
56
+ A workflow can finish dispatch while these children remain running. Its summary and child rows identify that distinction, and launch receipts do not generate child-completion notices. Consume the later child result before treating its work or report as complete.
57
+
54
58
  Validate a script without launching children:
55
59
 
56
60
  ```js
@@ -114,6 +118,8 @@ subagent({
114
118
 
115
119
  These controls are opt-in. Avoid tight hard budgets for mutation-capable workers unless the workflow has an explicit checkpoint and handoff path.
116
120
 
121
+ The optional `preflight` lane hints apply only to raw `workflowScript` or `workflowScriptPath` requests, not named workflows or direct child calls. They are display-only: mismatched coverage warns but never changes execution authority.
122
+
117
123
  The result is `{ ok, errors }`. Invalid scripts return a tool error and include line and column data when available. Validation checks syntax, portable nested-async rules, literal `runs.run` and `runs.all` keys and child `baseRef` values, duplicate literal keys in one `runs.all` group, direct keyed access to a known `runs.all` result, and statically clear non-JSON boundary values. Dynamic keys and other runtime-only values are accepted without a warning. Validation does not discover agents, launch children, or create run artifacts.
118
124
 
119
125
  ```js
@@ -194,6 +200,54 @@ The helper validates the complete plain-JSON lane inventory before launching any
194
200
 
195
201
  The board is bounded and contains only lane/stage keys, state, success, retained run ids, explicit output references, bounded errors, and an optional structured verdict. It does not return child transcripts or create a lane registry or cleanup authority. Use raw `runs.run(...)`/`runs.all(...)` when a workflow needs conditional or rolling orchestration beyond this helper.
196
202
 
203
+ ### Typed post-run checks and typed steps
204
+
205
+ Two ways to put a small classifier (a script, a lookup, a fast evaluation model) into a workflow without spending an LLM turn on it.
206
+
207
+ **A typed gate** runs a command after a child finishes and turns its JSON stdout into that child's `structuredOutput`:
208
+
209
+ ```js
210
+ subagent({ workflowScript: `
211
+ const review = await runs.run("review", {
212
+ agent: "reviewer", task: packet,
213
+ output: "reports/review.md", outputMode: "file-only",
214
+ gate: { command: "classify --report reports/review.md", output: "json" }
215
+ });
216
+ if (review.structuredOutput.verdict === "blocked") {
217
+ return runs.run("fix", { agent: "worker", task: "Fix the findings in reports/review.md" });
218
+ }
219
+ return { verdict: review.structuredOutput.verdict, report: "reports/review.md" };
220
+ ` });
221
+ ```
222
+
223
+ The parent receives a pointer plus a verdict instead of the review text. See [typed gates](tool-reference.md#typed-gates) for the contract and failure rules.
224
+
225
+ **A typed step** is an agent whose runner is a command rather than a Pi session. The prompt arrives on stdin, stdout is the child's output, and the workflow uses it like any other child:
226
+
227
+ ```yaml
228
+ ---
229
+ name: classifier
230
+ description: Typed classification of the task text
231
+ runner:
232
+ type: external-cli
233
+ command: /path/to/classify
234
+ args: [--stdin, --json]
235
+ promptDelivery: stdin
236
+ async: true
237
+ systemPromptMode: replace
238
+ inheritProjectContext: false
239
+ inheritGlobalContext: false
240
+ inheritSkills: false
241
+ ---
242
+ ```
243
+
244
+ ```js
245
+ const results = await runs.all(items.map((item) => ({ key: item.key, agent: "classifier", task: item.text })));
246
+ const routed = results.map((r, i) => ({ key: items[i].key, ...JSON.parse(r.output) }));
247
+ ```
248
+
249
+ Command-runner agents are async-only; workflows launch children async by default, but a direct `async: false` call is refused. The runner gets only the assembled prompt, never a forked transcript, so keep `inheritProjectContext` and `inheritGlobalContext` off unless the command wants that text. See [examples/typed-gate](https://github.com/nicobailon/pi-subagents/tree/main/examples/typed-gate) for a runnable version of both shapes.
250
+
197
251
  ### Host command steps
198
252
 
199
253
  Use the named `run-ci` resource when a permission/policy extension needs to admit one supported non-interactive command as workflow evidence instead of a child-agent run:
@@ -244,7 +298,7 @@ subagent({ workflowScript: `
244
298
  ` });
245
299
  ```
246
300
 
247
- The workflow trace records the run completions and steering receipt. Scripts still never see raw async directories, inbox paths, or session files. If the keyed child is terminal, stale, or has no live route when `runs.steer` runs, the receipt reports `missed` or `failed` and the script can decide whether to continue.
301
+ The workflow trace records the run completions and steering receipt. Scripts cannot access the filesystem or control inboxes; returned run and artifact references are data only. If the keyed child is terminal, stale, or has no live route when `runs.steer` runs, the receipt reports `missed` or `failed` and the script can decide whether to continue.
248
302
 
249
303
  Use named outputs when later workflow steps need structured data or durable references:
250
304
 
@@ -473,7 +527,7 @@ If messages do not show up, run `/subagents-doctor`. Advanced users can tune the
473
527
 
474
528
  Subagents can call `subagent` only when their resolved builtin tools explicitly include `subagent`. That is meant for delegated fanout agents, not ordinary worker/reviewer children. A depth guard prevents unbounded nesting.
475
529
 
476
- By default, nesting is limited to two levels: main session → subagent → sub-subagent. Deeper calls are blocked with guidance to complete the current task directly. Nested runs appear in the parent status widget and `status` output as a tree, and `status`, `interrupt`, and `resume` can target a nested run by its id.
530
+ By default, nesting is limited to two levels: main session → subagent → sub-subagent. Deeper calls are blocked with guidance to complete the current task directly. Nested runs appear in the parent status widget and `status` output as a tree, and `status`, `interrupt`, and `resume` can target a nested run by its id. Coordinator completion and widget cleanup retain descendant lookup authority in the owning parent session; they do not grant access to another session or outside a child's authorized subtree.
477
531
 
478
532
  Configure the limit with:
479
533
 
@@ -1,7 +1,7 @@
1
1
  import { createJiti } from "jiti";
2
2
 
3
3
  const jiti = createJiti(import.meta.url);
4
- const { runInspector } = await jiti.import("./src/inspectors/inspector-runner.ts");
4
+ const { runInspector } = await jiti.import("./src/inspectors/inspector-runner.js");
5
5
 
6
6
  try {
7
7
  runInspector();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xzzpig/pi-subagents",
3
- "version": "0.15.1",
3
+ "version": "0.18.0",
4
4
  "description": "Pi extension for single-agent delegation and scripted multi-agent workflows",
5
5
  "author": "Nico Bailon",
6
6
  "license": "MIT",
@@ -11,6 +11,7 @@
11
11
  "./external-job-provider": "./src/api/external-job-provider.ts",
12
12
  "./external-runs": "./src/api/external-runs.ts",
13
13
  "./agents": "./src/api/agents.ts",
14
+ "./inspectors": "./src/api/inspectors.ts",
14
15
  "./delegation": "./src/api/delegation.ts",
15
16
  "./capability-ceiling": "./src/api/capability-ceiling.ts",
16
17
  "./workflow-resources": "./src/api/workflow-resources.ts",
@@ -67,9 +68,10 @@
67
68
  },
68
69
  "peerDependencies": {
69
70
  "@earendil-works/pi-agent-core": "*",
70
- "@earendil-works/pi-ai": ">=0.80.0",
71
+ "@earendil-works/pi-ai": ">=0.86.1",
71
72
  "@earendil-works/pi-coding-agent": "*",
72
- "@earendil-works/pi-tui": "*"
73
+ "@earendil-works/pi-tui": "*",
74
+ "typebox": "*"
73
75
  },
74
76
  "peerDependenciesMeta": {
75
77
  "@earendil-works/pi-agent-core": {
@@ -83,25 +85,28 @@
83
85
  },
84
86
  "@earendil-works/pi-tui": {
85
87
  "optional": true
88
+ },
89
+ "typebox": {
90
+ "optional": true
86
91
  }
87
92
  },
88
93
  "dependencies": {
89
94
  "@xzzpig/pi-components": "0.4.0",
90
95
  "acorn": "8.18.0",
91
96
  "jiti": "2.7.0",
92
- "typebox": "1.1.38",
93
97
  "undici": "8.10.0",
94
98
  "yaml": "2.8.3"
95
99
  },
96
100
  "devDependencies": {
97
- "@earendil-works/pi-agent-core": "0.85.1",
98
- "@earendil-works/pi-ai": "0.85.1",
99
- "@earendil-works/pi-tui": "0.85.1",
101
+ "@earendil-works/pi-agent-core": "0.87.0",
102
+ "@earendil-works/pi-ai": "0.87.0",
103
+ "@earendil-works/pi-tui": "0.87.0",
100
104
  "@oxlint/plugins": "1.80.0",
101
105
  "@types/node": "24.13.3",
102
106
  "oxlint": "1.80.0",
103
107
  "typescript": "5.9.3",
104
- "@earendil-works/pi-coding-agent": "file:./test/fixtures/pi-coding-agent-shim"
108
+ "@earendil-works/pi-coding-agent": "file:./test/fixtures/pi-coding-agent-shim",
109
+ "typebox": "1.3.27"
105
110
  },
106
111
  "publishConfig": {
107
112
  "access": "public"
@@ -116,6 +121,7 @@
116
121
  "test": "npm run test:unit",
117
122
  "test:unit": "env -u PI_SUBAGENT_PARENT_SESSION -u PI_SESSION_ID -u PI_SESSION_FILE -u PI_CODING_AGENT -u PI_PROVIDER -u PI_MODEL -u PI_REASONING_LEVEL -u PI_SUBAGENT_EXTRA_AGENT_DIRS node --experimental-strip-types --import ./test/support/isolated-temp-root.mjs --test test/unit/*.test.ts",
118
123
  "test:integration": "env -u PI_SUBAGENT_PARENT_SESSION -u PI_SESSION_ID -u PI_SESSION_FILE -u PI_CODING_AGENT -u PI_PROVIDER -u PI_MODEL -u PI_REASONING_LEVEL -u PI_SUBAGENT_EXTRA_AGENT_DIRS node --experimental-strip-types --import ./test/support/register-loader.mjs --test test/integration/*.test.ts",
124
+ "test:smoke:tool-activation": "env -u PI_SUBAGENT_PARENT_SESSION -u PI_SESSION_ID -u PI_SESSION_FILE -u PI_CODING_AGENT -u PI_PROVIDER -u PI_MODEL -u PI_REASONING_LEVEL -u PI_SUBAGENT_EXTRA_AGENT_DIRS node --experimental-strip-types --test test/smoke/tool-activation.test.ts",
119
125
  "test:all": "npm run test:unit && npm run test:integration"
120
126
  }
121
127
  }
@@ -8,8 +8,11 @@ session, are the supervisor. You select the roster, curate cross-advisor packets
8
8
  decide which feedback is valid, and write the final memo. Advisors do not talk
9
9
  directly or see peer transcripts by default. This is not free-form agent chat.
10
10
 
11
- Before you orchestrate, read `skills/council-mode/SKILL.md` and
12
- `skills/pi-subagents/references/execution-controls.md`.
11
+ Before you orchestrate, load the council protocol with
12
+ `subagent({ action: "guide", topic: "council" })`. If only `subagents_enable`
13
+ is available, call it first; `subagent` is available on the next request. The
14
+ guide returns the packaged council-mode skill and the references it asks you to
15
+ read, so it also works when Pi runs with `--no-skills`.
13
16
 
14
17
  Parse the invocation yourself. The flags below are conventions, not runtime
15
18
  options. Record a brief with the question, scope, non-goals, evidence targets,
@@ -48,7 +51,7 @@ path if the run is not resumable.
48
51
  ## Run the protocol
49
52
 
50
53
  Use the canonical workflow, structured advisor contracts, aggregate pass receipts,
51
- and memo requirements in `skills/council-mode/SKILL.md`. Keep the parent as the
54
+ and memo requirements from the council guide. Keep the parent as the
52
55
  only synthesizer and decision maker. Do not introduce a chair advisor, peer chat,
53
56
  or transcript sharing.
54
57
 
@@ -2,8 +2,6 @@ import { pathToFileURL } from "node:url";
2
2
 
3
3
  let aliases = {};
4
4
  let nativeRunner = false;
5
- let compiledRunner = false;
6
- let packageRootUrl;
7
5
  const redirected = new Set([
8
6
  "@earendil-works/pi-tui",
9
7
  ]);
@@ -11,14 +9,13 @@ const redirected = new Set([
11
9
  export function initialize(data) {
12
10
  aliases = data?.aliases ?? {};
13
11
  nativeRunner = data?.nativeRunner === true;
14
- compiledRunner = data?.compiledRunner === true;
15
- packageRootUrl = data?.packageRootUrl;
16
12
  }
17
13
 
18
14
  export function resolve(specifier, context, nextResolve) {
19
- const packageImport = typeof packageRootUrl === "string" && context.parentURL?.startsWith(packageRootUrl) === true;
20
- if (nativeRunner && (!compiledRunner || packageImport) ? aliases[specifier] : redirected.has(specifier) && aliases[specifier]) {
21
- return nextResolve(pathToFileURL(aliases[specifier]).href, context);
15
+ const alias = nativeRunner ? aliases[specifier] : redirected.has(specifier) && aliases[specifier];
16
+ if (alias) {
17
+ const target = pathToFileURL(alias).href;
18
+ return nativeRunner ? { url: target, shortCircuit: true } : nextResolve(target, context);
22
19
  }
23
20
  return nextResolve(specifier, context);
24
21
  }
@@ -5,9 +5,6 @@ import { pathToFileURL } from "node:url";
5
5
  // pi-lens-ignore: unchecked-throwing-call-js
6
6
  const aliases = JSON.parse(process.env.JITI_ALIAS ?? "{}");
7
7
  const nativeRunner = process.env.PI_ASYNC_NATIVE_RUNNER === "1";
8
- const compiledRunner = process.env.PI_ASYNC_COMPILED_RUNNER === "1";
9
- // Pi's jiti loader owns aliases for external extensions; these hooks only supply peers to our compiled package.
10
- const packageRootUrl = new URL("./", import.meta.url).href;
11
8
  const redirected = new Set([
12
9
  "@earendil-works/pi-tui",
13
10
  ]);
@@ -17,9 +14,10 @@ const redirected = new Set([
17
14
  if (typeof nodeModule.registerHooks === "function") {
18
15
  nodeModule.registerHooks({
19
16
  resolve(specifier, context, nextResolve) {
20
- const packageImport = context.parentURL?.startsWith(packageRootUrl) === true;
21
- if ((nativeRunner && (!compiledRunner || packageImport) ? aliases[specifier] : redirected.has(specifier) && aliases[specifier])) {
22
- return nextResolve(pathToFileURL(aliases[specifier]).href, context);
17
+ const alias = nativeRunner ? aliases[specifier] : redirected.has(specifier) && aliases[specifier];
18
+ if (alias) {
19
+ const target = pathToFileURL(alias).href;
20
+ return nativeRunner ? { url: target, shortCircuit: true } : nextResolve(target, context);
23
21
  }
24
22
  try {
25
23
  return nextResolve(specifier, context);
@@ -31,6 +29,6 @@ if (typeof nodeModule.registerHooks === "function") {
31
29
  });
32
30
  } else {
33
31
  nodeModule.register(new URL("./runner-peer-loader.mjs", import.meta.url), {
34
- data: { aliases, nativeRunner, compiledRunner, packageRootUrl },
32
+ data: { aliases, nativeRunner },
35
33
  });
36
34
  }
@@ -101,6 +101,7 @@ For an authorized complex delegated workflow, read `prompting-and-roles.md` and
101
101
  - Keep the parent on the ordinary strong default model. Route workers/scouts to a fast capable tier, serious reviews to a strong tier, and top reasoning to bounded read-only critique.
102
102
  - Exact model names are deployment policy. Put them in user/project settings or profiles, not package guidance.
103
103
  - Give every child a compact meta-prompt checklist: objective; repo/cwd/ref; authority/edit boundary; relevant files/contracts and constraints; success/acceptance criteria; validation; expected output/report; and stop/ask conditions. See `references/prompting-and-roles.md`.
104
+ - Before launching a writer for substantial mutation work, classify it as single-seam or multi-seam and partition multi-seam work across exclusive component owners, gates, and durable handoffs before an integration-only owner. See `references/multi-lane-orchestration.md`.
104
105
  - For mutation work, use an isolated lane/worktree when isolation, overlap, or concurrent juggling matters; keep one writer per cwd/worktree. See `references/multi-lane-orchestration.md` for lane mechanics.
105
106
  - Keep long/high-output validation out of chat: prefer `interactive_shell` dispatch/background monitors, bounded logs, or subagent-owned reports; return a concise summary plus report path unless same-turn output is required. Do not use `interactive_shell` as an implicit fallback for a failed `subagent` lane; see `references/execution-controls.md`.
106
107
  - Treat subagent workflow, child launch, prompt runtime, extension load, and child tooling setup failures as lane infrastructure blockers. Stop, report the exact failure and run/worktree state, verify a clean worktree or capture a partial diff, and use only a clear same-protocol retry or an owner-approved execution-mode fallback.
@@ -6,10 +6,13 @@ This file is a detailed reference loaded from `skills/pi-subagents/SKILL.md`.
6
6
 
7
7
  - **Explicit forking requires a persisted parent session.** If the current session
8
8
  does not have a persisted session file or current leaf, explicit `context: "fork"`
9
- fails. An agent-level `defaultContext: fork` is a preference: packaged `worker`,
10
- `oracle`, and `advisor` fall back to `fresh` when those fork preconditions are not
9
+ fails. An agent-level `defaultContext: fork` is a preference: packaged `oracle`
10
+ and `advisor` fall back to `fresh` when those fork preconditions are not
11
11
  met yet. Use `context: "fresh"` when you do not want a fork even after the parent
12
12
  session exists.
13
+ - **Packaged workers start fresh.** `worker` defaults to fresh context so its brief,
14
+ not the parent's unfinished agenda, controls the implementation. Pass explicit
15
+ `context: "fork"` when inherited conversation history is required.
13
16
  - **Forked runs inherit parent history.** They are branched threads, not fresh
14
17
  filtered contexts. Use fresh context for adversarial reviewers unless the user explicitly asks for forked context.
15
18
  - **Default subagent nesting depth is 2.** Deeper recursive delegation is blocked
@@ -24,7 +24,7 @@ Project settings resolve from the nearest parent directory containing `.pi` or `
24
24
 
25
25
  An agent may set `runner.type: external-cli` with a non-empty `command`, optional string `args`, and `promptDelivery: stdin` (the default). The command runs with `shell: false`, inherits the resolved cwd and environment, and receives the combined agent instructions and task through stdin. It must already be installed; pi-subagents adds no CLI dependency.
26
26
 
27
- External CLI profiles are async-only and one-shot. They support lifecycle artifacts, stdout/stderr logs, timeout, and stop. Full stdout and stderr are retained in their log files, while the final stdout response and stderr error kept in memory are each limited to their last 64 KiB. They do not support native Pi child options such as model override, structured output, acceptance/agent contract, tool budgets, fast mode, fork context, skills, or native Pi tools unless the runner explicitly implements them. Foreground/clarify, steer/resume/interrupt-as-pause, nested subagents, and sessions are also unsupported.
27
+ A command-runner agent with a plain `command` (no adapter) is also how a classifier or scoring script becomes a typed workflow step: the prompt arrives on stdin, stdout is the child's `output`, and the script parses it. Keep `inheritProjectContext`, `inheritGlobalContext`, and `inheritSkills` off unless the command wants that text. External CLI profiles are async-only and one-shot. They support lifecycle artifacts, stdout/stderr logs, timeout, and stop. Full stdout and stderr are retained in their log files, while the final stdout response and stderr error kept in memory are each limited to their last 64 KiB. They do not support native Pi child options such as model override, structured output, acceptance/agent contract, tool budgets, fast mode, fork context, skills, or native Pi tools unless the runner explicitly implements them. Foreground/clarify, steer/resume/interrupt-as-pause, nested subagents, and sessions are also unsupported.
28
28
 
29
29
  ### External job profiles
30
30
 
@@ -32,7 +32,7 @@ An agent may set `runner.type: external-job` with a non-empty `provider` and opt
32
32
 
33
33
  External job profiles are async-only. The provider owns the remote job and Pi owns the async run record. Status persists provider name, provider job id, prompt digest, provider options, handle/conversation URLs when supplied, result artifact path, last known state, and provider failure code/message. Recovery uses existing provider job metadata to call `reattach` and `result`; it refuses to redispatch a prompt when the persisted provider job does not match the prompt digest.
34
34
 
35
- External job profiles do not support foreground/clarify, steer/resume, Pi models/tools/extensions/skills, tool budgets, structured output, native child permissions, or Pi child sessions. Capacity conflicts fail closed and include the blocking provider job id when the provider supplies it.
35
+ External job profiles do not support foreground/clarify, live steer or native session resume, Pi models/tools/extensions/skills, tool budgets, structured output, native child permissions, or Pi child sessions. Completed external-job runs can use `action: "resume"` for provider follow-up when the registered provider exposes `followUp(input)`; running jobs must finish first, and providers without follow-up support fail closed with an update/reload message. Capacity conflicts fail closed and include the blocking provider job id when the provider supplies it.
36
36
 
37
37
  ### Single agent
38
38
 
@@ -99,9 +99,11 @@ If `runs.all` is missing in a running session, reload or update `pi-subagents` b
99
99
 
100
100
  For one host-run verification command, pass `gate: "npm test"` on a `runs.run`/`runs.all` item (or at the top level as a workflow default). It is shorthand for verified acceptance with that single command: the runtime executes it on the host, records the result as evidence, and memoizes it per tracked workspace state and effective environment. `gate` cannot be combined with `acceptance`; use explicit `acceptance.verify` for multiple commands or custom criteria.
101
101
 
102
+ For a typed post-run check, pass the object form `gate: { command, output: "json", schema?, timeoutMs? }`. A passing command must print one JSON document (under 12,000 characters); the parsed value, validated against `schema` when given, becomes the child's `structuredOutput`, so a script can branch on `result.structuredOutput` and `runs.lanes` blocks on `verdict === "blocked"` without the parent reading the child's output. Pair it with `output` + `outputMode: "file-only"` so the command reads the saved file. Empty, non-JSON, or schema-invalid stdout fails the gate and rejects the run. Typed gates are never memoized. A typed gate cannot be combined with an `outputSchema` from the launch or the agent; the launch is rejected before any child starts. See the `tool-reference` guide, "Typed gates".
103
+
102
104
  If omitted, acceptance is inferred from role, mode, and risk. Use `level: "checked"` for ordinary writer evidence and `level: "verified"` when the runtime should run explicit validation commands. Independent review is orthogonal: use `review: { required: true, agent: "reviewer" }`; reviewer/read-only calls omit `acceptance`. `review-required` means evidence passed but review is pending; `reviewed` means an independent review found no blockers. Never request `level: "reviewed"`; it is recognized only so preflight can return an actionable correction. Disable gates with `{ level: "none", reason: "..." }`; bare `"none"` is rejected and `false` is only a deprecated shorthand. Child-reported command success is evidence, not runtime verification.
103
105
 
104
- Completed workflow children from this parent session stay addressable as retained children. `subagent({ action: "children.list" })` lists up to the last 10 with run ids and reports each row as `resumable` or `not resumable` with a reason. Resume only rows reported `resumable`. For a retained-child challenge, use `resume` instead of `steer` when the child is complete. If no retained child is resumable, launch a same-role fallback challenge and label it as fallback. A later workflow continues a resumable child with `runs.run(key, { resume: "<run-id>", task: "follow-up" })`. Inside `workflowScript`, awaiting that call waits for the revived child to finish and returns its completed output and new `runId`; top-level `{ action: "resume" }` remains detached. Pass explicit follow-up task text. Assign each returned child result back to the loop variable because every resume can return a new retained `runId`; always resume the latest returned id. `resume` and `agent` are mutually exclusive, the revived child keeps its stored agent/model/tool contract, and `gate` is rejected on retained resume items.
106
+ Completed workflow children from this parent session stay addressable as retained children. `subagent({ action: "children.list" })` lists up to the last 10 with run ids and reports each row as `resumable` or `not resumable` with a reason. This workflow-only roster is not an exhaustive list of direct native children. Resume only rows reported `resumable`. When the exact run id of an intended direct child is known, inspect it with `subagent({ action: "status", id: "<run-id>" })`; if status identifies the candidate, attempt `subagent({ action: "resume", id: "<run-id>", message: "..." })`. Resume performs the authoritative eligibility check and may reject the attempt. For a retained-child challenge, use `resume` instead of `steer` when the child is complete. Launch a same-role fallback challenge, labeled as fallback, only when no known candidate exists or resume rejects eligibility. A later workflow continues a resumable child with `runs.run(key, { resume: "<run-id>", task: "follow-up" })`. Inside `workflowScript`, awaiting that call waits for the revived child to finish and returns its completed output and new `runId`; top-level `{ action: "resume" }` remains detached. Pass explicit follow-up task text. Assign each returned child result back to the loop variable because every resume can return a new retained `runId`; always resume the latest returned id. `resume` and `agent` are mutually exclusive, the revived child keeps its stored agent/model/tool contract, and `gate` is rejected on retained resume items.
105
107
 
106
108
  Each workflow key identifies one result lane: use a new stable workflow key for every distinct retained resume pass; same-key calls are reused only when launch parameters are identical, and incompatible parameters are rejected.
107
109
 
@@ -491,7 +493,7 @@ subagent({
491
493
  workflowScript: `return runs.run("oracle-check", { agent: "oracle", task: "Review my current direction, challenge assumptions, and propose the best next move." })`
492
494
  })
493
495
 
494
- // Implementation only after explicit approval. Worker defaults to forked context.
496
+ // Implementation only after explicit approval. Worker defaults to fresh context.
495
497
  subagent({
496
498
  workflowScript: `return runs.run("implementation", { agent: "worker", task: "Implement the approved approach: ..." })`
497
499
  })
@@ -18,7 +18,7 @@ subagent({ action: "list" })
18
18
  subagent({ action: "children.list" })
19
19
  ```
20
20
 
21
- Lists up to the last 10 retained workflow children from this parent session with explicit `resumable` or `not resumable` rows. Resume only rows reported `resumable`. Send a simple follow-up or implementation challenge with `subagent({ action: "resume", id: "<run-id>", message: "..." })`. Continue one inside a workflow with `runs.run(key, { resume: "<run-id>", task: "follow-up" })`; each workflow key identifies one result lane, so use a new stable workflow key for every distinct retained resume pass. Same-key calls are reused only when launch parameters are identical, and incompatible parameters are rejected. The revived child keeps its stored agent, model, and tool contract. If no resumable child is listed, start a same-role fallback challenge and label it as fallback. `steer` with `mode: "follow_up"` only queues text for the next `resume` when the child has already completed.
21
+ Lists up to the last 10 retained workflow children from this parent session with explicit `resumable` or `not resumable` rows. This workflow-only roster is not an exhaustive list of direct native children. Resume only rows reported `resumable`. When the exact run id of an intended direct child is known, inspect it with `subagent({ action: "status", id: "<run-id>" })`; if status identifies the candidate, attempt `subagent({ action: "resume", id: "<run-id>", message: "..." })`. Resume performs the authoritative eligibility check and may reject the attempt. Continue one inside a workflow with `runs.run(key, { resume: "<run-id>", task: "follow-up" })`; each workflow key identifies one result lane, so use a new stable workflow key for every distinct retained resume pass. Same-key calls are reused only when launch parameters are identical, and incompatible parameters are rejected. The revived child keeps its stored agent, model, and tool contract. Start a same-role fallback challenge, labeled as fallback, only when no known candidate exists or resume rejects eligibility. `steer` with `mode: "follow_up"` only queues text for the next `resume` when the child has already completed.
22
22
 
23
23
  ### Refinement overlays
24
24
 
@@ -131,7 +131,7 @@ That is only a starting point. Omit `package` for the traditional unqualified ru
131
131
 
132
132
  `acceptance` is a single-agent launch default. Use a scalar level such as `checked` or an inline/block YAML map such as `{ level: "none", reason: "lightweight lookup" }`. An explicit tool-call value wins; scripted workflow child acceptance remains configured on the `runs.run` or `runs.all` item. Management create/update accepts the same policy object, and `acceptance: ""` clears the frontmatter default (`false` remains the deprecated disabled-policy shorthand).
133
133
 
134
- `acceptanceRole` is `read-only` or `writer` and controls automatic acceptance inference only. Explicit task mutation or no-edit intent wins; otherwise the role replaces agent-name guessing. Omission preserves the current name heuristics. The field does not grant or revoke tools. Management accepts `false` or an empty string to clear it.
134
+ `acceptanceRole` is `read-only` or `writer` and controls automatic acceptance inference only. The structured role is authoritative; task wording and agent names do not escalate acceptance. Omission uses lightweight attestation. The field does not grant or revoke tools. Management accepts `false` or an empty string to clear it.
135
135
 
136
136
  `tools` is a strict child allowlist, not an extension loader. For a named extension tool, keep its registered name in `tools` and load its provider through normal Pi discovery, `extensions`, a path-like `tools` entry, or `subagentOnlyExtensions`. For example, pair `tools: read, fixture_search` with `subagentOnlyExtensions: ./tools/fixture-search.ts` when the provider should exist only in that agent's child sessions. The child now fails with the unavailable names and provider-loading guidance instead of silently continuing when a requested tool is absent; internal `structured_output` is allowed automatically when an output schema requires it.
137
137
 
@@ -158,4 +158,4 @@ Additional user prompt templates can delegate into `pi-subagents` through the na
158
158
 
159
159
  Other Pi extensions can call `pi-subagents` through the in-process event bus. The RPC channels are `subagents:rpc:v1:ready`, `subagents:rpc:v1:request`, and per-request replies at `subagents:rpc:v1:reply:<requestId>`. Envelopes use `{ version: 1, requestId, method, params }`, and replies use `{ version: 1, requestId, success, data | error }`. `ping` advertises the exact process-local async completion event as `events.asyncComplete` for RPC-spawn consumers.
160
160
 
161
- Methods: `ping`, `status`, `spawn`, `steer`, `interrupt`, `resume`, and `stop`. `ping` capability metadata advertises optional projections: `capabilities.fleetStatus: { version: 1 }` adds bounded current-session `data.fleet` records (opaque reconciliation `key`, resolved `agent`, optional `role`, `model`, `effort`, caller-facing `goal`, `startedAt`, split `{ input, output, total }` tokens, plus `totalActive`/`omitted` overflow counts) to successful `status` replies; `capabilities.launchResolvedExtensions` advertises parent-resolved opaque launch-extension identifiers in status details; `capabilities.runtimeAcknowledgedExtensions` advertises the best-effort child-runtime acknowledgement projection fed by cooperating extensions emitting `subagent:acknowledge-extension`. Foreground `details.results[]` rows carry a stable numeric `index`; correlate children by `(runId, index)` rather than row position. Consumers should read status/result artifacts and RPC projections instead of scraping terminal output and must ignore unknown fields. `spawn` requires `workflowScript`, is async-only, and rejects management actions, `async: false`, or `clarify: true`; it reuses the normal executor, so discovery, validation, session attribution, configured spawn caps, child-safety depth, artifacts, and async status are shared with the `subagent` tool. `status`, acknowledged async `steer`, and `interrupt` map to the normal control actions. RPC steer disables pause-and-revive recovery and advertises `capabilities.nonRecoveringSteer`, preserving the caller's authority over the exact spawned child. `resume` requires a target plus non-empty message and delegates to the package-owned revival path; it may set a caller-owned `file-only` output path but cannot override the persisted child model, tools, budgets, session ownership, or exclusive session lease. For retained-child workflows, list children first and resume only rows reported `resumable`; otherwise start a same-role fallback challenge and label it as fallback. `stop` targets running async runs through the existing timeout control channel. `pi.events` is process-local, so separate Pi processes and child subagents need lifecycle artifact files or `pi-intercom` instead.
161
+ Methods: `ping`, `status`, `manage`, `spawn`, `steer`, `interrupt`, `resume`, `stop`, and `cost`. `ping` capability metadata advertises optional projections: `capabilities.fleetStatus: { version: 1 }` adds bounded current-session `data.fleet` records (opaque reconciliation `key`, resolved `agent`, optional `role`, `model`, `effort`, caller-facing `goal`, `startedAt`, split `{ input, output, total }` tokens, plus `totalActive`/`omitted` overflow counts) to successful `status` replies; `capabilities.launchResolvedExtensions` advertises parent-resolved opaque launch-extension identifiers in status details; `capabilities.runtimeAcknowledgedExtensions` advertises the best-effort child-runtime acknowledgement projection fed by cooperating extensions emitting `subagent:acknowledge-extension`; `capabilities.cost: { version: 1 }` advertises parent-plus-child accounting as data. Foreground `details.results[]` rows carry a stable numeric `index`; correlate children by `(runId, index)` rather than row position. Consumers should read status/result artifacts and RPC projections instead of scraping terminal output and must ignore unknown fields. `spawn` accepts either `{ agent, task? }`, an inline `workflowScript`, or `workflowScriptPath`; it is async-only and rejects management actions, `async: false`, or `clarify: true`. It reuses the normal executor, so discovery, validation, session attribution, configured spawn caps, child-safety depth, artifacts, and async status are shared with the `subagent` tool. `manage` accepts only the schedule actions advertised by `ping.capabilities.managementActions`. `status`, acknowledged async `steer`, and `interrupt` map to the normal control actions. RPC steer disables pause-and-revive recovery and advertises `capabilities.nonRecoveringSteer`, preserving the caller's authority over the exact spawned child. `resume` requires a target plus non-empty message and delegates to the package-owned revival path; it may set a caller-owned `file-only` output path but cannot override the persisted child model, tools, budgets, session ownership, or exclusive session lease. For retained-child workflows, resume only roster rows reported `resumable`; because that workflow-only roster is not exhaustive, inspect the exact status of a known direct-run candidate and attempt the authoritative resume when status identifies it. Start a labeled same-role fallback only when there is no known candidate or resume rejects eligibility. `stop` targets running async runs through the existing timeout control channel. `pi.events` is process-local, so separate Pi processes and child subagents need lifecycle artifact files or `pi-intercom` instead.
@@ -4,6 +4,14 @@ Use this reference when several independent tasks need coordinated workers, work
4
4
 
5
5
  Create lanes only after delegation is operator-authorized and each lane materially improves evidence, independent review, specialization, useful parallelism, or isolated execution. Do not manufacture parallelism: keep dependent work serial, and only split work when each lane has a distinct decision and useful output.
6
6
 
7
+ ## Mandatory implementation-topology preflight
8
+
9
+ Before launching a writer for substantial mutation work, classify the implementation as **single-seam** or **multi-seam**. Two or more independently testable contracts or source boundaries make it multi-seam. One PR does not imply one writer, and the one-writer-per-worktree rule prevents concurrent ownership conflicts; it does not authorize an issue-wide commission.
10
+
11
+ Record the classification and evidence on a lane board before writer launch. For multi-seam work, give each isolated component writer exclusive file or contract ownership and focused validation gates. Require every component to produce a committed or otherwise durable handoff, then start a separate integration-only owner after the component handoffs are ready. Mechanically reject and repartition a writer prompt if it owns all major outcomes across multiple independent boundaries.
12
+
13
+ A single complete writer remains valid only when the board records evidence that the work is genuinely one seam or that splitting it would create overlapping ownership or artificial handoffs. This preflight must not manufacture parallelism: do not split tightly coupled work merely to increase the lane count.
14
+
7
15
  ## Lane board and authority
8
16
 
9
17
  Before multiple mutation-capable lanes start, record this board in the parent context:
@@ -118,7 +118,7 @@ Use this after implementation when the user or applicable instructions request d
118
118
 
119
119
  ### Staged fix orchestration technique
120
120
 
121
- Use this when a broad diff has known reviewer findings across several items and the user wants the parent to “orchestrate subagents like a boss.” Keep the active worktree safe with a three-stage `workflowScript`:
121
+ Use this when a broad diff has known reviewer findings across several items and the user wants the parent to “orchestrate subagents like a boss.” Keep mutation ownership explicit in the `workflowScript`:
122
122
 
123
123
  When staged seams are available, a low-tier writer should not receive the
124
124
  end-to-end issue. Use `runs.lanes` inside `workflowScript` to keep stages narrow:
@@ -126,44 +126,45 @@ a scout/red test, helper-only change, one render seam, validation, minimality
126
126
  challenge, or fresh review. Give the writer only its assigned implementation
127
127
  stage; keep sequencing and synthesis with the parent.
128
128
 
129
- 1. A parallel read-only planning fanout, one reviewer per issue cluster. Each child inspects the real diff and returns exact files, line refs, proposed fixes, and focused validation. They must not edit.
130
- 2. One writer worker. It receives the reviewer summaries as the awaited planning results (or their durable output paths) interpolated into its task, plus the parent’s accepted scope, stop rules, and verification contract. It is the only child allowed to edit the active worktree.
131
- 3. A parallel read-only validation fanout. Validators inspect the worker diff from fresh context with distinct angles, report pass/fail, remaining blockers, and missing verification.
129
+ 1. A parallel read-only planning fanout, one reviewer per issue cluster or review angle. Each child inspects the real diff and returns exact files, line refs, proposed fixes, and focused validation. They must not edit.
130
+ 2. Classify the accepted fixes on the lane board before writer launch. If issue clusters are independently testable source or contract boundaries, use isolated component writers with exclusive file/contract ownership and focused gates. Each component must commit or produce another durable handoff; only after those handoffs are ready, start one integration-only owner.
131
+ 3. Use one writer for the complete fix only when the accepted fixes are one tightly coupled existing diff/seam and the lane board records evidence that splitting would create overlapping ownership or artificial handoffs. Give that writer the planning summaries, accepted scope, stop rules, and verification contract.
132
+ 4. Run fresh-context, read-only validation against the integrated or single-seam result. Validators use distinct angles and report pass/fail, remaining blockers, and missing verification.
132
133
 
133
134
  Prefer `async: true`, `context: "fresh"` for reviewers/validators, `outputMode: "file-only"` for large summaries, and per-stage output names that will not collide. Use stable `runs` keys plus `phase` and `label` on each launch item to make async status readable, and hold each awaited result in an ordinary JavaScript variable when a later step needs that specific result — interpolate it (or the durable output path you declared for that child) into the later task text instead of passing a whole aggregate blob. Use this pattern instead of launching several writer workers into a dirty worktree. Include non-blocking suggestions in the writer prompt only when they are small, safe, and do not expand product scope; otherwise record them as deferred.
134
135
 
135
136
  When one child returns a structured target list, use ordinary JavaScript to validate/filter it and map bounded entries into `runs.all`; do not use the removed chain fanout DSL.
136
137
 
137
- Example shape:
138
+ Single-seam example shape (the lane board records that these are review angles on one tightly coupled deployment-lifecycle diff, not independent implementation contracts):
138
139
 
139
140
  ```typescript
140
141
  subagent({
141
142
  async: true,
142
143
  context: "fresh",
143
144
  workflowScript: `
144
- // Stage 1: parallel read-only planning fanout (stable keys, one per issue cluster)
145
+ // Stage 1: parallel read-only review angles on one recorded single seam
145
146
  const plans = await runs.all([
146
- { key: "deploy-plan", agent: "reviewer", phase: "Planning", label: "Deploy docs", task: "Plan fixes for deploy docs/workflow. Inspect the current diff. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "plans/deploy.md", outputMode: "file-only" },
147
- { key: "scheduler-plan", agent: "reviewer", phase: "Planning", label: "Scheduler contract", task: "Plan fixes for scheduler contract. Inspect the current diff. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "plans/scheduler.md", outputMode: "file-only" },
148
- { key: "sandbox-plan", agent: "reviewer", phase: "Planning", label: "Sandbox/security", task: "Plan fixes for sandbox/security. Inspect the current diff. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "plans/sandbox.md", outputMode: "file-only" }
147
+ { key: "correctness-plan", agent: "reviewer", phase: "Planning", label: "Review lifecycle correctness", task: "Plan correctness fixes for the same deployment-lifecycle diff. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "plans/correctness.md", outputMode: "file-only" },
148
+ { key: "regression-plan", agent: "reviewer", phase: "Planning", label: "Review lifecycle regressions", task: "Plan regression coverage for the same deployment-lifecycle diff. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "plans/regressions.md", outputMode: "file-only" },
149
+ { key: "minimality-plan", agent: "reviewer", phase: "Planning", label: "Review lifecycle minimality", task: "Plan minimality fixes for the same deployment-lifecycle diff. Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "plans/minimality.md", outputMode: "file-only" }
149
150
  ]);
150
151
 
151
- // Stage 2: single writer — the only child allowed to edit the active worktree.
152
+ // Stage 2: one writer for this lane-board-recorded single seam.
152
153
  // Under outputMode "file-only" the awaited .output is the saved-output
153
154
  // reference, so pass those managed artifact references to the writer.
154
155
  const worker = await runs.run("apply-fixes", {
155
156
  agent: "worker",
156
157
  phase: "Implementation",
157
158
  label: "Apply accepted fixes",
158
- task: "Apply only the accepted fixes from these planning summaries. You are the sole writer for the active worktree. Run focused validation and report changed files, commands, failures, and remaining issues.\\n\\nDeploy plan: " + plans[0].output + "\\n\\nScheduler plan: " + plans[1].output + "\\n\\nSandbox plan: " + plans[2].output,
159
+ task: "Apply only the accepted fixes to the one deployment-lifecycle seam. The lane board records that splitting this existing diff would create overlapping ownership. You are the sole writer for this seam. Run focused validation and report changed files, commands, failures, and remaining issues.\\n\\nCorrectness plan: " + plans[0].output + "\\n\\nRegression plan: " + plans[1].output + "\\n\\nMinimality plan: " + plans[2].output,
159
160
  output: "worker/fixes.md",
160
161
  outputMode: "file-only"
161
162
  });
162
163
 
163
164
  // Stage 3: parallel read-only validation fanout
164
165
  const validations = await runs.all([
165
- { key: "validate-deploy-scheduler", agent: "reviewer", phase: "Validation", label: "Deploy/scheduler validation", task: "Validate the post-worker diff for deploy and scheduler fixes. Start from the worker result: " + worker.output + ". Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "validation/deploy-scheduler.md", outputMode: "file-only" },
166
- { key: "validate-sandbox", agent: "reviewer", phase: "Validation", label: "Sandbox validation", task: "Validate the post-worker diff for sandbox/security fixes. Start from the worker result: " + worker.output + ". Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "validation/sandbox.md", outputMode: "file-only" }
166
+ { key: "validate-behavior", agent: "reviewer", phase: "Validation", label: "Validate lifecycle behavior", task: "Validate behavior in the post-worker deployment-lifecycle diff. Start from the worker result: " + worker.output + ". Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "validation/behavior.md", outputMode: "file-only" },
167
+ { key: "validate-minimality", agent: "reviewer", phase: "Validation", label: "Validate lifecycle minimality", task: "Validate minimality in the same post-worker deployment-lifecycle diff. Start from the worker result: " + worker.output + ". Do not modify project/source files; returning findings via the configured output artifact is allowed.", output: "validation/minimality.md", outputMode: "file-only" }
167
168
  ]);
168
169
 
169
170
  return { worker: worker.output, validations: validations.map(v => v.output) };
@@ -186,7 +187,7 @@ and user/project agents override builtins with the same name.
186
187
  | `oracle` | Rare hard-decision/root-cause escalation | top-reasoning critic tier, bounded read-only; high thinking escalation only | Advisory trajectory review, not routine code review |
187
188
  | `advisor` | Compatibility alias for `oracle` | top-reasoning critic tier, bounded read-only; high thinking escalation only | Same advisory escalation role as `oracle` |
188
189
 
189
- Builtin `worker` and `delegate` use strict tool allowlists and do not inherit ambient parent extension tools. To give a child an extension tool, name it in `tools` and load its provider via `extensions`, a path-like `tools` entry, or `subagentOnlyExtensions`. Custom agents without an `extensions` field follow `subagents.defaultExtensions` when set.
190
+ Builtin `worker` and `delegate` use strict tool allowlists and do not inherit ambient parent extension tools. To give a child an extension tool, name it in `tools` and load its provider via `extensions`, a path-like `tools` entry, or `subagentOnlyExtensions`. Agents without the corresponding field follow `subagents.defaultExtensions` or the ambient-preserving `subagents.defaultSubagentOnlyExtensions` when set.
190
191
 
191
192
  Builtin agents inherit the current Pi default model unless a run, user setting, project setting, or `subagents.defaultModel` overrides `model`. The table records recommended tier routing, not shipped hard defaults; explicit run, user, or project settings still win. Keep the parent/orchestrator on the ordinary strong default model unless parent/user policy says otherwise. Override builtin defaults before copying full agent files when a small tweak is enough.
192
193
 
@@ -294,6 +295,6 @@ If a provider rejects model IDs with thinking suffixes, use
294
295
  builtin thinking defaults globally. A higher-precedence per-agent `thinking`
295
296
  override can opt one builtin back in or replace custom-agent frontmatter thinking.
296
297
 
297
- Set `subagents.defaultExtensions` to give agents without an `extensions` field a shared child extension allowlist. Omit it to preserve ambient extension discovery, set it to `[]` to disable ambient extensions by default, or use `agentOverrides.<name>.extensions` for one agent. A matching override replaces custom-agent frontmatter for that field.
298
+ Set `subagents.defaultExtensions` to give agents without an `extensions` field a shared child extension allowlist. Omit it to preserve ambient extension discovery, set it to `[]` to disable ambient extensions by default, or use `agentOverrides.<name>.extensions` for one agent. Set `subagents.defaultSubagentOnlyExtensions` to add shared child-only paths without disabling ambient discovery. For either field, explicit frontmatter suppresses the default and a matching override replaces or false-clears it; lists are not combined.
298
299
 
299
300
  Tool description modes live in `~/.pi/agent/extensions/subagent/config.json`, not `subagents` settings. The default uses split prompt metadata: a short tool description plus active `promptSnippet` and `promptGuidelines`. Set `toolDescriptionMode` to `full` or `compact` to force one description string, or `custom` to read `subagent-tool-description.md` from the project config dir or agent dir; invalid custom files fall back to full mode and the safety guidance is still appended.
@@ -14,7 +14,7 @@ import { serializeAgent } from "./agent-serializer.ts";
14
14
  import { resolveSkillsWithFallback } from "./skills.ts";
15
15
  import { parseFrontmatter } from "./frontmatter.ts";
16
16
  import { resolvePiLaunchToolPlan } from "../runs/shared/child-tool-plan.ts";
17
- import { availableAgentNames, nameExistsInScope, sanitizeName } from "./agent-management.ts";
17
+ import { availableAgentNamesForCwd, nameExistsInScopeForCwd, sanitizeName } from "./agent-management.ts";
18
18
 
19
19
  export type AgentEjectionScope = "user" | "project";
20
20
 
@@ -250,11 +250,11 @@ export function ejectAgentDefinition(input: EjectAgentDefinitionInput): EjectAge
250
250
  ok: false,
251
251
  code: "missing_source",
252
252
  scope: input.scope,
253
- message: `Agent '${raw}' not found or is not a bundled/package agent. eject copies a builtin or package agent to ${input.scope} scope so it can be customized. Available: ${availableAgentNames(input.cwd).join(", ") || "none"}.`,
253
+ message: `Agent '${raw}' not found or is not a bundled/package agent. eject copies a builtin or package agent to ${input.scope} scope so it can be customized. Available: ${availableAgentNamesForCwd(input.cwd).join(", ") || "none"}.`,
254
254
  };
255
255
  }
256
256
  const runtimeName = source.name;
257
- if (nameExistsInScope(input.cwd, input.scope, runtimeName)) {
257
+ if (nameExistsInScopeForCwd(input.cwd, input.scope, runtimeName)) {
258
258
  return {
259
259
  ok: false,
260
260
  code: "name_conflict",