@xzzpig/pi-subagents 0.16.0 → 0.19.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 (166) hide show
  1. package/CHANGELOG.md +233 -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 +34 -21
  9. package/docs/configuration.md +82 -7
  10. package/docs/extension-api.md +75 -8
  11. package/docs/missions.md +13 -13
  12. package/docs/models.md +7 -5
  13. package/docs/observability.md +23 -13
  14. package/docs/standalone-background.md +5 -5
  15. package/docs/tool-reference.md +98 -100
  16. package/docs/watchdog.md +2 -0
  17. package/docs/workflows.md +214 -162
  18. package/inspector-runner.mjs +1 -1
  19. package/node_modules/@xzzpig/pi-components/package.json +4 -4
  20. package/package.json +15 -9
  21. package/prompts/council.md +6 -3
  22. package/prompts/review-loop.md +1 -1
  23. package/runner-peer-loader.mjs +4 -7
  24. package/runner-peer-preload.mjs +5 -7
  25. package/skills/council-mode/SKILL.md +1 -1
  26. package/skills/pi-subagents/SKILL.md +13 -5
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +8 -5
  28. package/skills/pi-subagents/references/execution-controls.md +72 -69
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +4 -4
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +9 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +52 -54
  32. package/src/agents/advertised-agent-prompt.ts +21 -41
  33. package/src/agents/agent-eject.ts +3 -3
  34. package/src/agents/agent-management.ts +63 -54
  35. package/src/agents/agent-memory.ts +90 -3
  36. package/src/agents/agent-serializer.ts +4 -4
  37. package/src/agents/agents.ts +132 -51
  38. package/src/agents/global-npm-root.ts +58 -0
  39. package/src/agents/proactive-skills.ts +4 -1
  40. package/src/agents/runtime-agent-registry.ts +14 -11
  41. package/src/agents/skills.ts +42 -9
  42. package/src/api/delegation.ts +15 -0
  43. package/src/api/inspectors.ts +27 -0
  44. package/src/api/preflight.ts +7 -2
  45. package/src/extension/config.ts +12 -4
  46. package/src/extension/control-notices.ts +3 -0
  47. package/src/extension/doctor.ts +10 -4
  48. package/src/extension/fanout-child.ts +20 -3
  49. package/src/extension/herdr-pi-bridge.ts +2 -0
  50. package/src/extension/index.ts +168 -206
  51. package/src/extension/public-execution.ts +69 -35
  52. package/src/extension/reply-workflow-script.ts +58 -0
  53. package/src/extension/rpc.ts +39 -11
  54. package/src/extension/schemas.ts +47 -138
  55. package/src/extension/subagent-guide.ts +12 -4
  56. package/src/extension/tool-activation.ts +146 -0
  57. package/src/extension/tool-description.ts +62 -27
  58. package/src/extension/upgrade-notice.ts +40 -0
  59. package/src/inspectors/ghostty/plugin.ts +13 -1
  60. package/src/inspectors/plugins.ts +70 -3
  61. package/src/integrations/herdr-status.ts +19 -3
  62. package/src/intercom/intercom-bridge.ts +2 -0
  63. package/src/intercom/native-supervisor-channel.ts +26 -16
  64. package/src/intercom/result-intercom.ts +4 -0
  65. package/src/runs/background/active-async-capacity.ts +3 -25
  66. package/src/runs/background/async-execution.ts +60 -95
  67. package/src/runs/background/async-job-tracker.ts +91 -56
  68. package/src/runs/background/async-resume.ts +16 -8
  69. package/src/runs/background/async-retention.ts +46 -16
  70. package/src/runs/background/async-status.ts +2 -0
  71. package/src/runs/background/await-async-run.ts +76 -0
  72. package/src/runs/background/binary-bootstrap.ts +34 -6
  73. package/src/runs/background/chain-root-attachment.ts +4 -4
  74. package/src/runs/background/control-channel.ts +18 -2
  75. package/src/runs/background/fleet-view.ts +51 -7
  76. package/src/runs/background/notify.ts +98 -7
  77. package/src/runs/background/pid-namespace.ts +18 -0
  78. package/src/runs/background/process-terminal-candidate.ts +98 -0
  79. package/src/runs/background/process-terminal.ts +17 -96
  80. package/src/runs/background/result-watcher.ts +1 -1
  81. package/src/runs/background/retained-children.ts +3 -2
  82. package/src/runs/background/run-child-session.ts +20 -6
  83. package/src/runs/background/run-id-resolver.ts +10 -5
  84. package/src/runs/background/run-status.ts +16 -4
  85. package/src/runs/background/runner-aliases.ts +54 -16
  86. package/src/runs/background/runner-child-launch.ts +4 -2
  87. package/src/runs/background/runner-startup-failure.ts +56 -0
  88. package/src/runs/background/scheduled-runs.ts +5 -5
  89. package/src/runs/background/stale-run-reconciler.ts +19 -3
  90. package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
  91. package/src/runs/background/subagent-runner.ts +111 -288
  92. package/src/runs/background/wait-tool.ts +2 -0
  93. package/src/runs/background/workflow-terminal-proof.ts +68 -0
  94. package/src/runs/foreground/async-stop-action.ts +17 -3
  95. package/src/runs/foreground/execution.ts +111 -139
  96. package/src/runs/foreground/prompt-audit.ts +3 -9
  97. package/src/runs/foreground/subagent-executor.ts +715 -258
  98. package/src/runs/shared/acceptance.ts +167 -68
  99. package/src/runs/shared/async-status-projection.ts +5 -0
  100. package/src/runs/shared/capability-ceiling.ts +4 -1
  101. package/src/runs/shared/child-hooks.ts +1 -16
  102. package/src/runs/shared/child-launch.ts +37 -16
  103. package/src/runs/shared/child-runtime-config.ts +3 -0
  104. package/src/runs/shared/child-session.ts +144 -8
  105. package/src/runs/shared/child-tool-plan.ts +38 -116
  106. package/src/runs/shared/dynamic-fanout.ts +1 -1
  107. package/src/runs/shared/external-cli-runner.ts +3 -1
  108. package/src/runs/shared/external-job-bridge.ts +54 -0
  109. package/src/runs/shared/git-environment.ts +29 -0
  110. package/src/runs/shared/mcp-config-sources.ts +5 -1
  111. package/src/runs/shared/mcp-direct-tool-allowlist.ts +104 -12
  112. package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
  113. package/src/runs/shared/model-resolution.ts +35 -10
  114. package/src/runs/shared/model-scope.ts +28 -9
  115. package/src/runs/shared/nested-events.ts +12 -0
  116. package/src/runs/shared/orca-progress-tabs.ts +3 -2
  117. package/src/runs/shared/parallel-utils.ts +4 -1
  118. package/src/runs/shared/pi-spawn.ts +1 -3
  119. package/src/runs/shared/single-output.ts +11 -2
  120. package/src/runs/shared/structured-output.ts +227 -7
  121. package/src/runs/shared/subagent-control.ts +2 -16
  122. package/src/runs/shared/subagent-prompt-runtime.ts +29 -5
  123. package/src/runs/shared/tool-availability.ts +2 -2
  124. package/src/runs/shared/tool-budget.ts +21 -0
  125. package/src/runs/shared/usage-reconciliation.ts +73 -0
  126. package/src/runs/shared/worktree.ts +36 -9
  127. package/src/shared/child-session-name.ts +4 -2
  128. package/src/shared/disabled-features.ts +123 -0
  129. package/src/shared/extension-context.ts +13 -0
  130. package/src/shared/fork-context.ts +11 -4
  131. package/src/shared/launch-contract.ts +1 -1
  132. package/src/shared/model-info.ts +9 -0
  133. package/src/shared/pruned-fork.ts +69 -56
  134. package/src/shared/settings.ts +1 -1
  135. package/src/shared/types.ts +73 -16
  136. package/src/slash/delegation-adapters.ts +25 -1
  137. package/src/slash/prompt-template-bridge.ts +18 -3
  138. package/src/slash/prompt-workflows.ts +12 -1
  139. package/src/slash/slash-commands.ts +17 -246
  140. package/src/slash/subagent-cost.ts +313 -0
  141. package/src/slash/subagents-admin.ts +4 -5
  142. package/src/tui/fleet-status.ts +38 -8
  143. package/src/tui/fleet.ts +21 -6
  144. package/src/tui/render.ts +166 -71
  145. package/src/tui/running-tone.ts +28 -0
  146. package/src/watchdog/diff-tool.ts +47 -12
  147. package/src/watchdog/permission-arbiter.ts +13 -15
  148. package/src/watchdog/register-child.ts +13 -5
  149. package/src/watchdog/register-main.ts +3 -3
  150. package/src/watchdog/review.ts +16 -16
  151. package/src/watchdog/runtime.ts +2 -1
  152. package/src/watchdog/turn-delta.ts +12 -6
  153. package/src/workflows/chat-progress.ts +2 -2
  154. package/src/workflows/scripted-workflow.ts +225 -59
  155. package/src/workflows/structured-workflow-scripts.ts +177 -0
  156. package/src/workflows/workflow-checklist.ts +6 -0
  157. package/src/workflows/workflow-child-summary.ts +4 -2
  158. package/src/workflows/workflow-receipt.ts +8 -2
  159. package/src/workflows/workflow-resources.ts +37 -12
  160. package/src/workflows/workflow-reuse.ts +120 -0
  161. package/src/workflows/workflow-revival.ts +123 -0
  162. package/src/workflows/workflow-settlement.ts +4 -1
  163. package/src/runs/shared/completion-evidence.ts +0 -89
  164. package/src/runs/shared/completion-guard.ts +0 -255
  165. package/src/runs/shared/llm-intent-arbiter.ts +0 -321
  166. package/src/runs/shared/task-intent.ts +0 -244
@@ -18,6 +18,7 @@ import type {
18
18
  AcceptanceReviewResult,
19
19
  AcceptanceVerifyCommand,
20
20
  AcceptanceVerifyResult,
21
+ JsonSchemaObject,
21
22
  ResolvedAcceptanceConfig,
22
23
  ResolvedAcceptanceGate,
23
24
  SingleResult,
@@ -26,7 +27,7 @@ import type {
26
27
  } from "../../shared/types.ts";
27
28
  import { unresolvedChildWatchdogBlockers } from "../../watchdog/child-status.ts";
28
29
  import { isAgentContract } from "./agent-contract.ts";
29
- import { classifyTaskMutationIntent, stripSeverityCompounds, taskMayMutate } from "./task-intent.ts";
30
+ import { validateStructuredOutputValue } from "./structured-output.ts";
30
31
 
31
32
  const LEVEL_RANK: Record<Exclude<AcceptanceLevel, "auto">, number> = {
32
33
  none: 0,
@@ -50,9 +51,9 @@ const VALID_EVIDENCE_KINDS: AcceptanceEvidenceKind[] = [
50
51
  const VALID_EVIDENCE = new Set<AcceptanceEvidenceKind>(VALID_EVIDENCE_KINDS);
51
52
  const ACCEPTANCE_EVIDENCE_HELP = `Supported evidence kinds: ${VALID_EVIDENCE_KINDS.join(", ")}. Example: { level: "checked", evidence: ["commands-run", "changed-files"] }.`;
52
53
  const ACCEPTANCE_OBJECT_EXAMPLE = "Example: { level: \"checked\", evidence: [\"commands-run\", \"changed-files\"] }.";
53
- const ACCEPTANCE_CONFIG_KEYS = new Set(["level", "report", "criteria", "evidence", "verify", "review", "stopRules", "reason"]);
54
+ const ACCEPTANCE_CONFIG_KEYS = new Set(["level", "report", "preserveStagedIndex", "criteria", "evidence", "verify", "review", "stopRules", "reason"]);
54
55
  const ACCEPTANCE_GATE_KEYS = new Set(["id", "must", "evidence", "severity"]);
55
- const ACCEPTANCE_VERIFY_KEYS = new Set(["id", "command", "timeoutMs", "cwd", "env", "allowFailure"]);
56
+ const ACCEPTANCE_VERIFY_KEYS = new Set(["id", "command", "timeoutMs", "cwd", "env", "allowFailure", "output", "schema"]);
56
57
  const ACCEPTANCE_REVIEW_KEYS = new Set(["agent", "focus", "required"]);
57
58
  const EXPLICIT_REVIEWED_UNAVAILABLE = "is an achieved status, not a requestable acceptance level. For a read-only reviewer call, omit acceptance. To require independent review of a writer result, use acceptance.review.required and orchestrate the reviewer separately.";
58
59
 
@@ -86,38 +87,8 @@ function inferLevel(input: {
86
87
  dynamic?: boolean;
87
88
  dynamicGroup?: boolean;
88
89
  }): { level: Exclude<AcceptanceLevel, "auto">; reasons: string[]; criteria: string[]; evidence: AcceptanceEvidenceKind[]; review?: { agent?: string; required?: boolean } } {
89
- const agent = input.agentName.toLowerCase();
90
- const task = input.task?.toLowerCase() ?? "";
91
- const reasons: string[] = [];
92
- // Declared roles replace name heuristics, so use the full writer grammar to detect explicit mutation independently of the actual agent name.
93
- const intent = classifyTaskMutationIntent(input.acceptanceRole ? "worker" : input.agentName, input.task ?? "");
94
- const readOnlyTask = intent.kind === "read-only"
95
- || (intent.kind === "unknown" && /\b(?:read[- ]only|review[- ]only|no edits|without edits|inspect|summari[sz]e)\b/.test(task));
96
- const rolePatchTask = input.acceptanceRole !== undefined
97
- && intent.kind !== "read-only"
98
- && !/\b(?:do not|don't|must not)\s+patch\b/.test(task)
99
- && /\bpatch\s+(?:(?:\.{0,2}[\\/])?(?:[\w.-]+[\\/])+[\w.-]+|[\w.-]+\.[a-z0-9]+\b|(?:the\s+)?parser\b)/.test(stripSeverityCompounds(task));
100
- const taskMayWrite = readOnlyTask ? false : taskMayMutate(input.task ?? "") || intent.kind === "implementation" || rolePatchTask;
101
- const readOnlyAgent = input.acceptanceRole === "read-only"
102
- || (input.acceptanceRole === undefined && /\b(?:reviewer|oracle|scout|researcher|analyst)\b/.test(agent));
103
- const writeTask = taskMayWrite
104
- || (input.acceptanceRole === "writer" && !readOnlyTask)
105
- || (input.acceptanceRole === undefined && /\bworker\b/.test(agent) && !readOnlyTask);
106
- const inferredReadOnly = readOnlyTask || ((readOnlyAgent || input.acceptanceRole === "read-only") && !taskMayWrite);
107
- const roleResolvesReadOnly = input.acceptanceRole !== undefined && inferredReadOnly;
108
- const dynamicResolvesReadOnly = inferredReadOnly && !writeTask;
109
- const riskyKeywordPattern = /\b(?:release|migration|migrate|security|data[- ]loss|destructive|post-review|fix pass)\b/;
110
- // Topic keywords cannot override classified read-only intent; unknown tasks keep their risk gate.
111
- const keywordRiskReadOnly = input.acceptanceRole === undefined
112
- ? intent.kind === "read-only"
113
- : inferredReadOnly;
114
- const risky = Boolean(input.async && writeTask)
115
- || (Boolean(input.dynamic) && !roleResolvesReadOnly && !dynamicResolvesReadOnly)
116
- || (Boolean(input.dynamicGroup) && !roleResolvesReadOnly && !dynamicResolvesReadOnly)
117
- || (!keywordRiskReadOnly && riskyKeywordPattern.test(task));
118
-
119
- if (risky) {
120
- reasons.push(input.async ? "async write-capable or risky run" : "risky write-capable run");
90
+ if (input.acceptanceRole === "writer" && (input.async || input.dynamic || input.dynamicGroup)) {
91
+ const reasons = [input.async ? "async declared writer" : "dynamic declared writer"];
121
92
  if (input.dynamic || input.dynamicGroup) reasons.push("dynamic fanout context");
122
93
  return {
123
94
  level: "checked",
@@ -127,28 +98,25 @@ function inferLevel(input: {
127
98
  review: { agent: "reviewer", required: true },
128
99
  };
129
100
  }
130
- if (writeTask && !readOnlyTask) {
131
- reasons.push(input.acceptanceRole === "writer" && !taskMayWrite ? "declared writer acceptance role" : "write-capable worker/task");
101
+ if (input.acceptanceRole === "writer") {
132
102
  return {
133
103
  level: "checked",
134
- reasons,
104
+ reasons: ["declared writer acceptance role"],
135
105
  criteria: ["Implement the requested change without widening scope"],
136
106
  evidence: requiredEvidenceForLevel("checked"),
137
107
  };
138
108
  }
139
- if (readOnlyAgent || readOnlyTask) {
140
- reasons.push(input.acceptanceRole === "read-only" && !readOnlyTask ? "declared read-only acceptance role" : readOnlyAgent ? "read-only/reviewer-style agent" : "read-only task wording");
109
+ if (input.acceptanceRole === "read-only") {
141
110
  return {
142
111
  level: "none",
143
- reasons,
112
+ reasons: ["declared read-only acceptance role"],
144
113
  criteria: ["Return concrete findings with file paths and severity when applicable"],
145
114
  evidence: ["review-findings", "residual-risks"],
146
115
  };
147
116
  }
148
- reasons.push("default lightweight attestation");
149
117
  return {
150
118
  level: "attested",
151
- reasons,
119
+ reasons: ["default lightweight attestation"],
152
120
  criteria: ["Return a concise result and residual risks when applicable"],
153
121
  evidence: ["manual-notes", "residual-risks"],
154
122
  };
@@ -200,15 +168,59 @@ type GateAcceptanceNormalizationResult =
200
168
  | { ok: true; acceptance?: AcceptanceInput }
201
169
  | { ok: false; error: string };
202
170
 
171
+ const GATE_OBJECT_KEYS = new Set(["command", "output", "schema", "timeoutMs"]);
172
+ export const GATE_INPUT_ERROR = "gate must be a non-empty command string or { command, output?: \"json\", schema?, timeoutMs? }.";
173
+
174
+ export interface GateObjectInput {
175
+ command: string;
176
+ output?: "json";
177
+ schema?: JsonSchemaObject;
178
+ timeoutMs?: number;
179
+ }
180
+
181
+ /** Validates the two accepted gate shapes without normalizing them. Shared by preflight and the workflow sandbox mirror. */
182
+ export function parseGateInput(gate: unknown): { ok: true; gate: GateObjectInput } | { ok: false; error: string } {
183
+ if (typeof gate === "string") {
184
+ return gate.trim() ? { ok: true, gate: { command: gate.trim() } } : { ok: false, error: GATE_INPUT_ERROR };
185
+ }
186
+ if (!gate || typeof gate !== "object" || Array.isArray(gate)) return { ok: false, error: GATE_INPUT_ERROR };
187
+ const value = gate as Record<string, unknown>;
188
+ for (const key of Object.keys(value)) {
189
+ if (!GATE_OBJECT_KEYS.has(key)) return { ok: false, error: `gate.${key} is not supported.` };
190
+ }
191
+ if (typeof value.command !== "string" || !value.command.trim()) return { ok: false, error: GATE_INPUT_ERROR };
192
+ if (value.output !== undefined && value.output !== "json") return { ok: false, error: "gate.output must be \"json\" when present." };
193
+ if (value.schema !== undefined) {
194
+ if (value.output !== "json") return { ok: false, error: "gate.schema requires gate.output: \"json\"." };
195
+ if (!value.schema || typeof value.schema !== "object" || Array.isArray(value.schema)) return { ok: false, error: "gate.schema must be a JSON Schema object." };
196
+ }
197
+ if (value.timeoutMs !== undefined && (!Number.isInteger(value.timeoutMs) || (value.timeoutMs as number) < 1)) return { ok: false, error: "gate.timeoutMs must be an integer >= 1." };
198
+ const parsed: GateObjectInput = { command: value.command.trim() };
199
+ if (value.output === "json") parsed.output = "json";
200
+ // SAFETY: schema was checked above to be a non-array object; timeoutMs to be an integer >= 1.
201
+ if (value.schema !== undefined) parsed.schema = value.schema as JsonSchemaObject;
202
+ if (value.timeoutMs !== undefined) parsed.timeoutMs = value.timeoutMs as number;
203
+ return { ok: true, gate: parsed };
204
+ }
205
+
206
+ /** True when an acceptance policy declares at least one `output: "json"` verify command, from either the gate shorthand or an explicit verify list. */
207
+ export function acceptanceHasTypedVerify(acceptance: AcceptanceInput | undefined): boolean {
208
+ if (!acceptance || typeof acceptance !== "object") return false;
209
+ return Array.isArray(acceptance.verify) && acceptance.verify.some((command) => command && typeof command === "object" && command.output === "json");
210
+ }
211
+
212
+ export const TYPED_VERIFY_OUTPUT_SCHEMA_CONFLICT = "a typed verify command (output: \"json\") cannot be combined with outputSchema; the child would have two structured-output sources.";
213
+
203
214
  export function normalizeGateAcceptance(gate: unknown, acceptance: AcceptanceInput | undefined): GateAcceptanceNormalizationResult {
204
215
  if (gate === undefined) {
205
216
  if (acceptance === undefined) return { ok: true };
206
217
  const normalized = normalizeAcceptanceValue(acceptance);
207
218
  return normalized.error ? { ok: false, error: normalized.error } : { ok: true, acceptance: normalized.value as AcceptanceInput };
208
219
  }
209
- if (typeof gate !== "string" || !gate.trim()) return { ok: false, error: "gate must be a non-empty command string." };
220
+ const parsed = parseGateInput(gate);
221
+ if (!parsed.ok) return { ok: false, error: parsed.error };
210
222
  if (acceptance !== undefined && acceptance !== false) return { ok: false, error: "gate cannot be combined with acceptance; use one gate command or acceptance.verify." + describeGateAcceptanceConflict(gate, acceptance) };
211
- return { ok: true, acceptance: { level: "verified", verify: [{ id: "gate", command: gate.trim() }] } };
223
+ return { ok: true, acceptance: { level: "verified", verify: [{ id: "gate", ...parsed.gate }] } };
212
224
  }
213
225
 
214
226
  export function describeGateAcceptanceConflict(gate: unknown, acceptance: unknown): string {
@@ -267,6 +279,12 @@ export function validateAcceptanceInput(input: unknown, pathLabel = "acceptance"
267
279
  if (value.report !== undefined && value.report !== "on" && value.report !== "off") {
268
280
  errors.push(`${pathLabel}.report must be on or off.`);
269
281
  }
282
+ if (value.preserveStagedIndex !== undefined && value.preserveStagedIndex !== true) {
283
+ errors.push(`${pathLabel}.preserveStagedIndex must be true when provided.`);
284
+ }
285
+ if (value.preserveStagedIndex === true && value.level !== "checked" && value.level !== "verified") {
286
+ errors.push(`${pathLabel}.preserveStagedIndex requires level checked or verified.`);
287
+ }
270
288
  if (value.level === "none" && (typeof value.reason !== "string" || !value.reason.trim())) {
271
289
  errors.push(`${pathLabel}.reason is required when level is none.`);
272
290
  }
@@ -348,6 +366,11 @@ export function validateAcceptanceInput(input: unknown, pathLabel = "acceptance"
348
366
  if (cmd.allowFailure !== undefined && typeof cmd.allowFailure !== "boolean") {
349
367
  errors.push(`${pathLabel}.verify[${index}].allowFailure must be a boolean.`);
350
368
  }
369
+ if (cmd.output !== undefined && cmd.output !== "json") errors.push(`${pathLabel}.verify[${index}].output must be "json" when present.`);
370
+ if (cmd.schema !== undefined) {
371
+ if (cmd.output !== "json") errors.push(`${pathLabel}.verify[${index}].schema requires output: "json".`);
372
+ if (!cmd.schema || typeof cmd.schema !== "object" || Array.isArray(cmd.schema)) errors.push(`${pathLabel}.verify[${index}].schema must be a JSON Schema object.`);
373
+ }
351
374
  }
352
375
  }
353
376
  if (value.review !== undefined && value.review !== false) {
@@ -471,6 +494,7 @@ export function resolveEffectiveAcceptance(input: {
471
494
  inferredReason: [],
472
495
  criteria,
473
496
  evidence,
497
+ preserveStagedIndex: explicit.preserveStagedIndex,
474
498
  verify: explicit.verify ?? [],
475
499
  review: explicit.review,
476
500
  stopRules: explicit.stopRules ?? [],
@@ -496,6 +520,7 @@ export function resolveEffectiveAcceptance(input: {
496
520
  inferredReason: inferred.reasons,
497
521
  criteria: level === "none" ? [] : criteria,
498
522
  evidence: level === "none" ? [] : evidence,
523
+ preserveStagedIndex: explicit.preserveStagedIndex,
499
524
  verify: explicit.verify ?? [],
500
525
  review,
501
526
  stopRules: explicit.stopRules ?? [],
@@ -527,6 +552,9 @@ export function formatAcceptancePrompt(acceptance: ResolvedAcceptanceConfig, opt
527
552
  "",
528
553
  `Required evidence: ${acceptance.evidence.join(", ") || "none"}`,
529
554
  ];
555
+ if (acceptance.preserveStagedIndex) {
556
+ lines.push("The host will verify that the staged index is unchanged from launch; report noStagedFiles truthfully even when the preserved index is non-empty.");
557
+ }
530
558
  if (acceptance.verify.length > 0) {
531
559
  lines.push("", "Runtime verification commands configured by parent:");
532
560
  for (const command of acceptance.verify) lines.push(`- ${command.id}: ${command.command}`);
@@ -1079,9 +1107,32 @@ function checkNoStagedFiles(cwd: string): AcceptanceRuntimeCheck {
1079
1107
  : { id: "no-staged-files", status: "failed", message: `Staged files present: ${staged.join(", ")}` };
1080
1108
  }
1081
1109
 
1110
+ /** Capture the repository-wide index tree. Throws when Git cannot provide trustworthy evidence. */
1111
+ export function captureStagedIndexBaseline(cwd: string): string {
1112
+ const result = spawnSync("git", ["write-tree"], { cwd, encoding: "utf-8", windowsHide: true });
1113
+ const oid = result.stdout.trim();
1114
+ if (result.status !== 0 || !oid) {
1115
+ const detail = result.stderr.trim();
1116
+ throw new Error(`Unable to capture staged index baseline${detail ? `: ${detail}` : "."}`);
1117
+ }
1118
+ return oid;
1119
+ }
1120
+
1121
+ function checkStagedIndexUnchanged(cwd: string, baseline: string): AcceptanceRuntimeCheck {
1122
+ try {
1123
+ const terminal = captureStagedIndexBaseline(cwd);
1124
+ return terminal === baseline
1125
+ ? { id: "staged-index-unchanged", status: "passed", message: "Staged index matches the launch baseline." }
1126
+ : { id: "staged-index-unchanged", status: "failed", message: "Staged index changed after launch." };
1127
+ } catch (error) {
1128
+ return { id: "staged-index-unchanged", status: "failed", message: error instanceof Error ? error.message : String(error) };
1129
+ }
1130
+ }
1131
+
1082
1132
  function runStructuralChecks(acceptance: ResolvedAcceptanceConfig, report: AcceptanceReport, cwd: string): AcceptanceRuntimeCheck[] {
1083
1133
  const checks: AcceptanceRuntimeCheck[] = [];
1084
1134
  for (const kind of acceptance.evidence) {
1135
+ if (kind === "no-staged-files" && acceptance.preserveStagedIndex) continue;
1085
1136
  if (kind === "no-staged-files" && report.noStagedFiles === undefined) continue;
1086
1137
  const status = reportEvidenceStatus(report, kind);
1087
1138
  checks.push({
@@ -1094,7 +1145,7 @@ function runStructuralChecks(acceptance: ResolvedAcceptanceConfig, report: Accep
1094
1145
  : `${kind} evidence missing from child report.`,
1095
1146
  });
1096
1147
  }
1097
- if (acceptance.evidence.includes("no-staged-files")) checks.push(checkNoStagedFiles(cwd));
1148
+ if (!acceptance.preserveStagedIndex && acceptance.evidence.includes("no-staged-files")) checks.push(checkNoStagedFiles(cwd));
1098
1149
  return checks;
1099
1150
  }
1100
1151
 
@@ -1202,6 +1253,43 @@ function isCachedVerifyResult(value: unknown): value is AcceptanceVerifyResult {
1202
1253
  && typeof result.durationMs === "number";
1203
1254
  }
1204
1255
 
1256
+ const TYPED_VERIFY_OUTPUT_MAX_BYTES = 12_000;
1257
+
1258
+ /**
1259
+ * A passing `output: "json"` command must print one JSON document on stdout.
1260
+ * The parsed value becomes the run's structured output; anything else turns
1261
+ * the passing run into a failed one so acceptance rejects rather than
1262
+ * silently dropping the verdict. Stdout is already bounded by trimOutput, so a
1263
+ * truncated document is detected by its marker instead of a parse guess.
1264
+ */
1265
+ async function applyTypedVerifyOutput(command: AcceptanceVerifyCommand, run: AcceptanceVerifyResult): Promise<void> {
1266
+ if (run.status !== "passed") return;
1267
+ const stdout = run.stdout ?? "";
1268
+ const fail = (message: string): void => {
1269
+ run.status = "failed";
1270
+ run.structuredOutputError = message;
1271
+ };
1272
+ if (!stdout.trim()) return fail("output: \"json\" command printed nothing on stdout.");
1273
+ if (stdout.endsWith("...[truncated]")) return fail(`output: "json" stdout exceeded ${TYPED_VERIFY_OUTPUT_MAX_BYTES} characters and was truncated.`);
1274
+ let value: unknown;
1275
+ try {
1276
+ value = JSON.parse(stdout);
1277
+ } catch (error) {
1278
+ return fail(`output: "json" stdout is not valid JSON: ${error instanceof Error ? error.message : String(error)}`);
1279
+ }
1280
+ if (command.schema) {
1281
+ const validation = await validateStructuredOutputValue(command.schema, value);
1282
+ if (validation.status === "invalid") return fail(`output: "json" stdout does not match gate.schema: ${validation.message}`);
1283
+ }
1284
+ run.structuredOutput = value;
1285
+ }
1286
+
1287
+ /** The first typed verify result on a ledger, if any command produced one. */
1288
+ export function typedVerifyOutput(ledger: AcceptanceLedger | undefined): { value: unknown } | undefined {
1289
+ const run = ledger?.verifyRuns?.find((entry) => entry.structuredOutput !== undefined);
1290
+ return run ? { value: run.structuredOutput } : undefined;
1291
+ }
1292
+
1205
1293
  async function runMemoizedVerifyCommand(command: AcceptanceVerifyCommand, defaultCwd: string, options: {
1206
1294
  signal?: AbortSignal;
1207
1295
  abortMessage?: string;
@@ -1215,7 +1303,9 @@ async function runMemoizedVerifyCommand(command: AcceptanceVerifyCommand, defaul
1215
1303
  } catch {
1216
1304
  workspaceState = undefined;
1217
1305
  }
1218
- if (!workspaceState || !options.artifactsDir || !options.runId) {
1306
+ // Typed gates read inputs (a report file, a log) that can change without
1307
+ // the tracked tree changing, so their verdicts are never reused.
1308
+ if (!workspaceState || !options.artifactsDir || !options.runId || command.output === "json") {
1219
1309
  return runVerifyCommand(command, defaultCwd, options);
1220
1310
  }
1221
1311
  const envKeys = Object.keys(command.env ?? {}).sort();
@@ -1387,6 +1477,8 @@ export async function evaluateAcceptance(input: {
1387
1477
  acceptance: ResolvedAcceptanceConfig;
1388
1478
  output: string;
1389
1479
  cwd: string;
1480
+ /** Host-captured launch index tree; required by preserveStagedIndex. */
1481
+ stagedIndexBaseline?: string;
1390
1482
  /**
1391
1483
  * Content the child sent to its configured output file (from its own write
1392
1484
  * tool calls, not from disk, so a concurrent writer to the same path cannot
@@ -1482,30 +1574,36 @@ export async function evaluateAcceptance(input: {
1482
1574
  ledger.runtimeChecks.push({ id: "verification-config", status: "failed", message: "verified acceptance requires runtime verify commands." });
1483
1575
  ledger.status = "rejected";
1484
1576
  ledger.evidenceStatus = "rejected";
1485
- return ledger;
1486
- }
1487
- ledger.verifyRuns = [];
1488
- for (const command of acceptance.verify) {
1489
- ledger.verifyRuns.push(await runMemoizedVerifyCommand(command, input.cwd, {
1490
- signal: input.signal,
1491
- abortMessage: input.abortMessage,
1492
- artifactsDir: input.artifactsDir,
1493
- runId: input.runId,
1494
- }));
1495
- if (input.signal?.aborted) break;
1496
- }
1497
- if (ledger.verifyRuns.some((run) => run.status === "failed" || run.status === "timed-out")) {
1498
- ledger.status = "rejected";
1499
- ledger.evidenceStatus = "rejected";
1500
- return ledger;
1501
- }
1502
- if (!ledger.runtimeChecks.some((check) => check.status === "failed")) {
1503
- ledger.status = "verified";
1504
- ledger.evidenceStatus = "verified";
1577
+ } else {
1578
+ ledger.verifyRuns = [];
1579
+ for (const command of acceptance.verify) {
1580
+ const run = await runMemoizedVerifyCommand(command, input.cwd, {
1581
+ signal: input.signal,
1582
+ abortMessage: input.abortMessage,
1583
+ artifactsDir: input.artifactsDir,
1584
+ runId: input.runId,
1585
+ });
1586
+ if (command.output === "json") await applyTypedVerifyOutput(command, run);
1587
+ ledger.verifyRuns.push(run);
1588
+ if (input.signal?.aborted) break;
1589
+ }
1590
+ if (ledger.verifyRuns.some((run) => run.status === "failed" || run.status === "timed-out")) {
1591
+ ledger.status = "rejected";
1592
+ ledger.evidenceStatus = "rejected";
1593
+ } else if (!ledger.runtimeChecks.some((check) => check.status === "failed")) {
1594
+ ledger.status = "verified";
1595
+ ledger.evidenceStatus = "verified";
1596
+ }
1505
1597
  }
1506
1598
  }
1507
1599
 
1508
- if (ledger.runtimeChecks.some((check) => check.status === "failed")) {
1600
+ if (acceptance.preserveStagedIndex) {
1601
+ ledger.runtimeChecks.push(input.stagedIndexBaseline
1602
+ ? checkStagedIndexUnchanged(input.cwd, input.stagedIndexBaseline)
1603
+ : { id: "staged-index-unchanged", status: "failed", message: "Staged index launch baseline is unavailable." });
1604
+ }
1605
+
1606
+ if (ledger.status === "rejected" || ledger.runtimeChecks.some((check) => check.status === "failed")) {
1509
1607
  ledger.status = "rejected";
1510
1608
  ledger.evidenceStatus = "rejected";
1511
1609
  return ledger;
@@ -1559,6 +1657,7 @@ export function acceptanceFailureMessage(ledger: AcceptanceLedger): string | und
1559
1657
  const failedCheck = ledger.runtimeChecks.find((check) => check.status === "failed");
1560
1658
  if (failedCheck) return `Acceptance rejected: ${failedCheck.message}`;
1561
1659
  const failedVerify = ledger.verifyRuns.find((run) => run.status === "failed" || run.status === "timed-out");
1660
+ if (failedVerify?.structuredOutputError) return `Acceptance verification '${failedVerify.id}' failed: ${failedVerify.structuredOutputError}`;
1562
1661
  if (failedVerify) return `Acceptance verification '${failedVerify.id}' ${failedVerify.status}.`;
1563
1662
  if (ledger.reviewResult?.status === "blockers") return "Acceptance review found blockers.";
1564
1663
  return "Acceptance rejected.";
@@ -1,5 +1,6 @@
1
1
  import { sanitizeDisplayText, truncateDisplayText } from "../../shared/display-text.ts";
2
2
  import { formatModelThinking } from "../../shared/formatters.ts";
3
+ import { childThinkingLevel, type ThinkingLevel } from "../../shared/model-info.ts";
3
4
  import type { AsyncJobState, AsyncJobStep, HostStepFreshness, HostStepMonitorKind, HostStepNode, HostStepState, HostStepVerdict, NestedRunSummary, NestedStepSummary, SubagentRunMode, WorkflowGraphSnapshot, WorkflowPreflightLane, WorkflowPreflight } from "../../shared/types.ts";
4
5
  import { HOST_STEP_MAX_COUNT, HOST_STEP_MAX_DETAIL_CHARS, HOST_STEP_MAX_LABEL_CHARS, HOST_STEP_MAX_PROVIDER_CHARS, HOST_STEP_MAX_REASON_CHARS, HOST_STEP_MAX_REF_CHARS, HOST_STEP_MAX_ROLE_CHARS, HOST_STEP_MAX_TARGET_CHARS, hostStepReportName, parseHostStepNode, validHostStepNodes } from "./host-step-status.ts";
5
6
  import { workflowPreflightLaneForRuntimeKey } from "../../workflows/workflow-preflight.ts";
@@ -106,6 +107,8 @@ export interface AsyncStatusWorkflowRow {
106
107
  kind?: HostStepMonitorKind;
107
108
  context?: AsyncJobStep["context"];
108
109
  modelThinking?: string;
110
+ /** Thinking level of the child a child row stands for. */
111
+ thinking?: ThinkingLevel;
109
112
  activity?: string;
110
113
  startedAt?: number;
111
114
  endedAt?: number;
@@ -623,12 +626,14 @@ export function projectAsyncWorkflowRows(
623
626
 
624
627
  function projectLoadedWorkflowRow(step: AsyncJobStep, index: number, preflight?: WorkflowPreflightLane): AsyncStatusWorkflowRow {
625
628
  const modelThinking = formatModelThinking(step.model, step.thinking) || undefined;
629
+ const thinking = childThinkingLevel(step);
626
630
  const activity = workflowStepActivity(step);
627
631
  return {
628
632
  name: workflowStepName(step, index),
629
633
  state: step.status,
630
634
  ...(step.context ? { context: step.context } : {}),
631
635
  ...(modelThinking ? { modelThinking } : {}),
636
+ ...(thinking ? { thinking } : {}),
632
637
  ...(activity ? { activity } : {}),
633
638
  ...(step.startedAt !== undefined ? { startedAt: step.startedAt } : {}),
634
639
  ...(step.endedAt !== undefined ? { endedAt: step.endedAt } : {}),
@@ -30,7 +30,6 @@ export interface SubagentCapabilityAudit {
30
30
  agentAllowed: boolean;
31
31
  agentRestrictionSources?: string[];
32
32
  /** Builtin tools declared but unavailable on the host runtime. */
33
- unavailableHostBuiltins?: string[];
34
33
  }
35
34
 
36
35
  export interface RegisterSubagentCapabilityCeilingOptions {
@@ -64,6 +63,10 @@ function validateText(value: unknown, field: string): string {
64
63
  return value.trim();
65
64
  }
66
65
 
66
+ export function normalizeCapabilityCeilingAllowedAgents(values: unknown): string[] {
67
+ return normalizeCeiling({ allowedAgents: values } as SubagentCapabilityCeiling).allowedAgents!;
68
+ }
69
+
67
70
  function normalizeCeiling(ceiling: SubagentCapabilityCeiling): ResolvedSubagentCapabilityCeiling {
68
71
  if (!ceiling || typeof ceiling !== "object" || Array.isArray(ceiling)) throw new Error("Invalid capability ceiling; expected an object.");
69
72
  const hasAllowedTools = Object.hasOwn(ceiling, "allowedTools");
@@ -7,7 +7,6 @@ import registerSubagentPromptRuntime from "./subagent-prompt-runtime.ts";
7
7
  import type { ChildRuntimeConfig } from "./child-runtime-config.ts";
8
8
  import type { ChildToolDiagnostic } from "./tool-availability.ts";
9
9
  import type { ChildSessionLaunch } from "./child-session.ts";
10
- import type { ArbiterModelContext } from "./llm-intent-arbiter.ts";
11
10
  import type { ChildTranscriptWriter } from "../../shared/child-transcript.ts";
12
11
  import { projectRuntimeAcknowledgedExtensions } from "./runtime-acknowledged-extensions.ts";
13
12
 
@@ -128,10 +127,9 @@ export function createChildHooks(config: ChildRuntimeConfig): ChildHookExtension
128
127
  }
129
128
 
130
129
  /** Launch-owned bookkeeping, paired with the same private hook certificate (no callback registration API). */
131
- export function createCapturedChildHooks(config: ChildRuntimeConfig, runner = false) {
130
+ export function createCapturedChildHooks(config: ChildRuntimeConfig) {
132
131
  let diagnostic: ChildToolDiagnostic | undefined;
133
132
  let acknowledgedIds: string[] | undefined;
134
- let completionIntentContext: ArbiterModelContext | undefined;
135
133
  let finalDrainHeld = false;
136
134
  const capture: OwnedCapture = {
137
135
  toolDiagnostic: (value) => { diagnostic = value; },
@@ -139,21 +137,8 @@ export function createCapturedChildHooks(config: ChildRuntimeConfig, runner = fa
139
137
  };
140
138
  Object.assign(config, capture);
141
139
  const hooks = childHooks(config, capture, (held) => { finalDrainHeld = held; });
142
- if (runner) {
143
- hooks.push({ name: "pi-subagents:completion-intent", factory: (pi) => pi.on("session_start", (_event, childCtx) => {
144
- // Retain only attempt model services and the session id string, not the live child session.
145
- completionIntentContext = {
146
- model: childCtx.model,
147
- modelRegistry: childCtx.modelRegistry,
148
- sessionId: childCtx.sessionManager.getSessionId(),
149
- };
150
- }) });
151
- const proof = promptProofs.get(hooks[0]!.factory);
152
- if (proof) proof.factories = hooks.map((hook) => hook.factory);
153
- }
154
140
  return {
155
141
  hooks,
156
- completionIntentContext: () => completionIntentContext,
157
142
  toolDiagnostic: () => diagnostic,
158
143
  runtimeAcknowledgedExtensions: () => acknowledgedIds ? projectRuntimeAcknowledgedExtensions(acknowledgedIds) : undefined,
159
144
  finalDrainHeld: () => finalDrainHeld,