@xzzpig/pi-subagents 0.14.0 → 0.15.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 (198) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/README.md +6 -5
  3. package/agents/evidence-auditor.md +34 -0
  4. package/agents/researcher.md +23 -13
  5. package/agents/reviewer.md +3 -2
  6. package/docs/agents.md +56 -15
  7. package/docs/configuration.md +92 -14
  8. package/docs/extension-api.md +132 -19
  9. package/docs/missions.md +10 -2
  10. package/docs/models.md +11 -22
  11. package/docs/observability.md +63 -11
  12. package/docs/standalone-background.md +59 -0
  13. package/docs/tool-reference.md +42 -23
  14. package/docs/watchdog.md +39 -10
  15. package/docs/workflows.md +58 -19
  16. package/index.ts +5 -2
  17. package/inspector-runner.mjs +2 -2
  18. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +13 -3
  19. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +18 -6
  20. package/node_modules/@xzzpig/pi-components/src/transcript.ts +26 -6
  21. package/package.json +9 -4
  22. package/prompts/parallel-review.md +1 -1
  23. package/runner-peer-loader.mjs +24 -0
  24. package/runner-peer-preload.mjs +36 -0
  25. package/skills/pi-subagents/SKILL.md +34 -22
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  27. package/skills/pi-subagents/references/execution-controls.md +27 -8
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  31. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  32. package/src/agents/advertised-agent-prompt.ts +94 -0
  33. package/src/agents/agent-management.ts +71 -59
  34. package/src/agents/agent-serializer.ts +6 -3
  35. package/src/agents/agents.ts +198 -72
  36. package/src/agents/builtin-names.ts +1 -0
  37. package/src/agents/chain-serializer.ts +5 -0
  38. package/src/agents/runtime-agent-registry.ts +7 -6
  39. package/src/api/delegation.ts +4 -0
  40. package/src/api/preflight.ts +110 -71
  41. package/src/api/required-child-extensions.ts +6 -0
  42. package/src/api/shared-types.ts +3 -1
  43. package/src/api/workflow-resources.ts +6 -0
  44. package/src/extension/config.ts +14 -37
  45. package/src/extension/fanout-child.ts +68 -5
  46. package/src/extension/herdr-pi-bridge.ts +164 -0
  47. package/src/extension/index.ts +141 -51
  48. package/src/extension/public-execution.ts +7 -6
  49. package/src/extension/rpc.ts +8 -21
  50. package/src/extension/schemas.ts +86 -84
  51. package/src/extension/tool-description.ts +32 -79
  52. package/src/inspectors/actions.ts +148 -0
  53. package/src/inspectors/ghostty/actions.ts +74 -0
  54. package/src/inspectors/ghostty/plugin.ts +17 -0
  55. package/src/inspectors/herdr/actions.ts +99 -179
  56. package/src/inspectors/herdr/plugin.ts +20 -0
  57. package/src/inspectors/herdr/project-panes.ts +4 -1
  58. package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
  59. package/src/inspectors/plugins.ts +8 -0
  60. package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
  61. package/src/inspectors/types.ts +51 -0
  62. package/src/integrations/pi-web-session-liveness.ts +73 -0
  63. package/src/intercom/intercom-bridge.ts +50 -8
  64. package/src/intercom/native-supervisor-channel.ts +142 -115
  65. package/src/intercom/supervisor-ui.ts +3 -2
  66. package/src/missions/workflow-state.ts +37 -16
  67. package/src/policy/authority.ts +4 -0
  68. package/src/profiles/profiles.ts +12 -6
  69. package/src/runs/background/active-async-capacity.ts +22 -18
  70. package/src/runs/background/active-run-index.ts +17 -1
  71. package/src/runs/background/async-execution.ts +359 -176
  72. package/src/runs/background/async-job-tracker.ts +41 -7
  73. package/src/runs/background/async-resume.ts +19 -12
  74. package/src/runs/background/async-retention.ts +20 -0
  75. package/src/runs/background/async-status-snapshot.ts +10 -12
  76. package/src/runs/background/async-status.ts +32 -13
  77. package/src/runs/background/auto-drain.ts +59 -35
  78. package/src/runs/background/binary-bootstrap.ts +38 -0
  79. package/src/runs/background/chain-append.ts +1 -1
  80. package/src/runs/background/chain-root-attachment.ts +22 -33
  81. package/src/runs/background/control-channel.ts +78 -44
  82. package/src/runs/background/fleet-view.ts +30 -2
  83. package/src/runs/background/notify.ts +193 -19
  84. package/src/runs/background/owned-process-tree.ts +35 -8
  85. package/src/runs/background/process-terminal.ts +23 -23
  86. package/src/runs/background/result-files.ts +8 -4
  87. package/src/runs/background/result-watcher.ts +19 -2
  88. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  89. package/src/runs/background/run-child-session.ts +118 -41
  90. package/src/runs/background/run-status.ts +78 -5
  91. package/src/runs/background/runner-aliases.ts +22 -5
  92. package/src/runs/background/runner-child-launch.ts +93 -0
  93. package/src/runs/background/runner-child-sessions.ts +5 -4
  94. package/src/runs/background/runner-http-dispatcher.ts +119 -0
  95. package/src/runs/background/scheduled-runs.ts +51 -18
  96. package/src/runs/background/stale-run-reconciler.ts +38 -12
  97. package/src/runs/background/steering.ts +20 -2
  98. package/src/runs/background/subagent-runner.ts +766 -432
  99. package/src/runs/background/subagent-wait.ts +179 -28
  100. package/src/runs/background/wait-completions.ts +79 -27
  101. package/src/runs/background/wait-subscriptions.ts +9 -3
  102. package/src/runs/background/wait-tool.ts +5 -3
  103. package/src/runs/foreground/async-steering-action.ts +37 -7
  104. package/src/runs/foreground/async-stop-action.ts +93 -3
  105. package/src/runs/foreground/execution.ts +174 -194
  106. package/src/runs/foreground/foreground-history.ts +5 -2
  107. package/src/runs/foreground/prompt-audit.ts +12 -6
  108. package/src/runs/foreground/subagent-executor.ts +896 -397
  109. package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
  110. package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
  111. package/src/runs/shared/acceptance.ts +54 -14
  112. package/src/runs/shared/agent-contract.ts +1 -1
  113. package/src/runs/shared/async-status-projection.ts +172 -78
  114. package/src/runs/shared/capability-ceiling.ts +2 -0
  115. package/src/runs/shared/child-hooks.ts +167 -3
  116. package/src/runs/shared/child-launch-plan.ts +15 -3
  117. package/src/runs/shared/child-launch.ts +44 -16
  118. package/src/runs/shared/child-lifecycle.ts +6 -3
  119. package/src/runs/shared/child-runtime-config.ts +8 -1
  120. package/src/runs/shared/child-session.ts +130 -24
  121. package/src/runs/shared/child-tool-plan.ts +145 -14
  122. package/src/runs/shared/completion-evidence.ts +2 -2
  123. package/src/runs/shared/completion-guard.ts +6 -3
  124. package/src/runs/shared/dynamic-fanout.ts +2 -2
  125. package/src/runs/shared/effective-system-prompt.ts +33 -0
  126. package/src/runs/shared/external-cli-contract.ts +11 -1
  127. package/src/runs/shared/external-cli-preflight.ts +6 -2
  128. package/src/runs/shared/external-cli-runner.ts +9 -7
  129. package/src/runs/shared/herdr-connection.ts +134 -0
  130. package/src/runs/shared/herdr-external-adapters.ts +169 -0
  131. package/src/runs/shared/herdr-machine.ts +279 -0
  132. package/src/runs/shared/herdr-pi-protocol.ts +59 -0
  133. package/src/runs/shared/herdr-placed-run.ts +263 -0
  134. package/src/runs/shared/host-step-status.ts +11 -11
  135. package/src/runs/shared/llm-intent-arbiter.ts +40 -21
  136. package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
  137. package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
  138. package/src/runs/shared/model-scope.ts +1 -1
  139. package/src/runs/shared/nested-events.ts +19 -10
  140. package/src/runs/shared/orca-progress-tabs.ts +7 -1
  141. package/src/runs/shared/parallel-handoff.ts +57 -12
  142. package/src/runs/shared/parallel-utils.ts +10 -4
  143. package/src/runs/shared/pi-spawn.ts +10 -0
  144. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  145. package/src/runs/shared/run-fanout-budget.ts +8 -8
  146. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  147. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  148. package/src/runs/shared/task-intent.ts +46 -13
  149. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  150. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  151. package/src/runs/shared/worktree-setup-command.ts +213 -0
  152. package/src/runs/shared/worktree.ts +437 -214
  153. package/src/shared/child-cache-retention.ts +43 -0
  154. package/src/shared/fork-context.ts +15 -72
  155. package/src/shared/launch-contract.ts +70 -8
  156. package/src/shared/model-response-aliases.ts +13 -0
  157. package/src/shared/opencode-session-headers.ts +30 -0
  158. package/src/shared/pruned-fork.ts +1 -1
  159. package/src/shared/required-child-extensions.ts +81 -0
  160. package/src/shared/settings.ts +5 -2
  161. package/src/shared/shortcuts.ts +0 -4
  162. package/src/shared/types.ts +163 -90
  163. package/src/shared/utils.ts +10 -2
  164. package/src/shared/watch-strategy.ts +2 -0
  165. package/src/shared/workflow-child-permit.ts +18 -13
  166. package/src/slash/delegation-adapters.ts +3 -1
  167. package/src/slash/delegation-request.ts +14 -0
  168. package/src/slash/slash-commands.ts +2 -7
  169. package/src/slash/subagents-admin.ts +31 -14
  170. package/src/tui/fleet-status.ts +165 -20
  171. package/src/tui/fleet.ts +30 -19
  172. package/src/tui/render.ts +210 -50
  173. package/src/watchdog/child-status.ts +28 -28
  174. package/src/watchdog/lsp-diagnostics.ts +1 -1
  175. package/src/watchdog/model-selection.ts +21 -1
  176. package/src/watchdog/permission-arbiter.ts +5 -2
  177. package/src/watchdog/register-child.ts +10 -2
  178. package/src/watchdog/register-main.ts +39 -35
  179. package/src/watchdog/render.ts +1 -1
  180. package/src/watchdog/review.ts +122 -74
  181. package/src/watchdog/rules.ts +1 -1
  182. package/src/watchdog/runtime.ts +100 -27
  183. package/src/watchdog/scope.ts +1 -1
  184. package/src/watchdog/settings.ts +3 -0
  185. package/src/watchdog/tool-actions.ts +13 -12
  186. package/src/watchdog/turn-delta.ts +23 -0
  187. package/src/watchdog/types.ts +5 -3
  188. package/src/watchdog/warning-format.ts +1 -1
  189. package/src/workflows/chat-progress.ts +3 -3
  190. package/src/workflows/scripted-workflow.ts +349 -26
  191. package/src/workflows/workflow-checklist.ts +17 -20
  192. package/src/workflows/workflow-child-summary.ts +57 -8
  193. package/src/workflows/workflow-preflight.ts +19 -19
  194. package/src/workflows/workflow-receipt.ts +24 -6
  195. package/src/workflows/workflow-resources.ts +108 -22
  196. package/src/workflows/workflow-settlement.ts +3 -0
  197. package/src/runs/shared/model-exclusions.ts +0 -373
  198. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -0,0 +1,76 @@
1
+ export interface ChildModelResolutionDiagnostic {
2
+ agent?: string;
3
+ model?: string;
4
+ host?: "parent" | "runner";
5
+ /** The launch's resolved capability ceiling, when one is active. */
6
+ capabilityCeiling?: { denyExtensions: boolean; sources?: readonly string[] };
7
+ }
8
+
9
+ /**
10
+ * Pi core's model-resolution failure text. `resolveCliModel` reports an
11
+ * unknown provider or model and cannot know which extension would have
12
+ * registered it, so these two shapes are the ones that mean "the child's
13
+ * model registry was missing a provider", not "the provider is unhealthy".
14
+ */
15
+ const MODEL_RESOLUTION_FAILURE_PATTERNS = [
16
+ /^Model .+ not found\b/i,
17
+ /^Unknown provider "/i,
18
+ ];
19
+
20
+ /** True for a core model-resolution failure, which a missing extension can explain. */
21
+ export function isChildModelResolutionFailure(error: string | undefined): boolean {
22
+ const text = typeof error === "string" ? error.trim() : "";
23
+ return MODEL_RESOLUTION_FAILURE_PATTERNS.some((pattern) => pattern.test(text));
24
+ }
25
+
26
+ /**
27
+ * A `capabilityCeiling.denyExtensions` launch loads no extension at all:
28
+ * ambient, listed, and MCP provider extensions are all suppressed, so neither
29
+ * `async: true` nor a frontmatter list can register the provider. Saying only
30
+ * the ambient-extension rule would direct the operator at remedies the ceiling
31
+ * discards.
32
+ */
33
+ function capabilityCeilingDeniesExtensions(diagnostic: ChildModelResolutionDiagnostic): boolean {
34
+ return diagnostic.capabilityCeiling?.denyExtensions === true;
35
+ }
36
+
37
+ function denyExtensionsClause(diagnostic: ChildModelResolutionDiagnostic): string {
38
+ const sources = diagnostic.capabilityCeiling?.sources ?? [];
39
+ return `Capability ceiling from ${sources.length > 0 ? sources.join(", ") : "an unnamed source"} denies extensions`;
40
+ }
41
+
42
+ /**
43
+ * Explain a child model that did not resolve because the extension serving its
44
+ * provider never loaded: a foreground child never loads the parent's ambient
45
+ * extensions, an explicit `extensions` list keeps a background child from
46
+ * loading them, and a capability ceiling denies extensions to both. The caller
47
+ * keeps the core error intact and appends this explanation, so a genuinely
48
+ * unknown model id still reads as one.
49
+ */
50
+ export function formatChildModelResolutionDiagnostic(diagnostic: ChildModelResolutionDiagnostic): string {
51
+ const subject = diagnostic.agent ? `Agent '${diagnostic.agent}'` : "Subagent";
52
+ const model = diagnostic.model ? `'${diagnostic.model}'` : "this model";
53
+ if (capabilityCeilingDeniesExtensions(diagnostic)) {
54
+ return (diagnostic.host === "parent"
55
+ ? [
56
+ `${subject} ran as a foreground child, which never loads the parent's ambient extensions.`,
57
+ `${denyExtensionsClause(diagnostic)}, so if ${model} is served by a provider extension, that extension cannot load for this child: \`async: true\` does not help either, and listed \`subagentOnlyExtensions\` or \`extensions\` entries are suppressed.`,
58
+ "Relax the capability ceiling to allow extensions, or use a model that the parent's model registry already resolves.",
59
+ ]
60
+ : [
61
+ `${subject} ran as a background child without the ambient extensions.`,
62
+ `${denyExtensionsClause(diagnostic)}, so if ${model} is served by a provider extension, that extension cannot load for this child: listed \`subagentOnlyExtensions\` or \`extensions\` entries are suppressed, and leaving \`extensions\` unset does not enable ambient loading.`,
63
+ "Relax the capability ceiling to allow extensions, or use a model that the child's model registry already resolves.",
64
+ ]).join("\n");
65
+ }
66
+ if (diagnostic.host === "parent") {
67
+ return [
68
+ `${subject} ran as a foreground child, which never loads the parent's ambient extensions but inherits the providers they registered.`,
69
+ `If ${model} is served by a provider extension, check the parent's \`/model\` list and the child extension diagnostics, or load the extension for this child with \`subagentOnlyExtensions\` or \`extensions\` in the agent frontmatter.`,
70
+ ].join("\n");
71
+ }
72
+ return [
73
+ `${subject} ran as a background child without the ambient extensions.`,
74
+ `If ${model} is served by a provider extension, that extension is not loaded for this child: list it in \`subagentOnlyExtensions\` or \`extensions\` in the agent frontmatter, or leave \`extensions\` unset so the child loads the ambient extensions.`,
75
+ ].join("\n");
76
+ }
@@ -1,26 +1,26 @@
1
- import { splitKnownThinkingSuffix, type ModelInfo as AvailableModelInfo } from "../../shared/model-info.ts";
2
- import type { Usage } from "../../shared/types.ts";
3
- import { filterFallbackCandidates, findModelExclusion, parseModelKey, recordModelFailure } from "./model-exclusions.ts";
1
+ import { splitKnownThinkingSuffix as splitThinkingSuffix, type ModelInfo as AvailableModelInfo } from "../../shared/model-info.ts";
4
2
  import { checkModelScope, type ModelScopeCheckRule, type ModelScopeViolation, type ModelSource } from "./model-scope.ts";
5
- import { redactSecretValues } from "./permissions.ts";
6
3
 
7
4
  export type { AvailableModelInfo };
8
5
 
9
- interface ModelAttemptSummary {
10
- model: string;
11
- success: boolean;
12
- exitCode?: number | null;
13
- error?: string;
14
- usage?: Usage;
6
+ export interface ModelSelectionEvidence {
7
+ model?: string;
8
+ requestedModel?: string;
15
9
  }
16
10
 
17
- export function splitThinkingSuffix(model: string): { baseModel: string; thinkingSuffix: string } {
18
- return splitKnownThinkingSuffix(model);
19
- }
11
+ export { splitThinkingSuffix };
20
12
 
21
- export function formatSubagentModelVerificationError(expectedModel: string, observedModel: string, availableModels: AvailableModelInfo[] | undefined): string | undefined {
13
+ /** Aliases apply only to the resolved launch candidate (without its thinking suffix) and the exact raw response ID. */
14
+ export function formatSubagentModelVerificationError(
15
+ expectedModel: string,
16
+ observedModel: string,
17
+ availableModels: AvailableModelInfo[] | undefined,
18
+ modelResponseAliases?: Record<string, string[]>,
19
+ ): string | undefined {
22
20
  if (!availableModels || availableModels.length === 0) return undefined;
23
21
  const expectedBase = splitThinkingSuffix(expectedModel).baseModel;
22
+ if (modelResponseAliases && Object.hasOwn(modelResponseAliases, expectedBase)
23
+ && modelResponseAliases[expectedBase]?.includes(observedModel)) return undefined;
24
24
  const observedBase = splitThinkingSuffix(observedModel).baseModel;
25
25
  if (expectedBase === observedBase) return undefined;
26
26
  const expectedEntry = availableModels.find((entry) => entry.fullId === expectedBase);
@@ -30,7 +30,7 @@ export function formatSubagentModelVerificationError(expectedModel: string, obse
30
30
  const expectedFullIdLeaf = expectedEntry.fullId.slice(expectedEntry.fullId.lastIndexOf("/") + 1);
31
31
  if (expectedIdLeaf === observedBase || expectedFullIdLeaf === observedBase) return undefined;
32
32
  }
33
- return `model_verification_failed: child reported a different model than the launch candidate. Expected '${expectedModel}' but observed '${observedModel}'.`;
33
+ return `model_verification_failed: native Pi child reported a different model than the launch candidate. Expected '${expectedModel}' but observed '${observedModel}'. If you have independently verified this response ID identifies the requested model, declare the exact mapping in modelResponseAliases in ~/.pi/agent/extensions/subagent/config.json (see docs/configuration.md#modelresponsealiases). Use the resolved provider/model ID without its thinking suffix as the key. This leaves the outgoing request unchanged. Configuration changes affect new independent native runs; resumed native runs retain their launch-time declaration. External CLI adapters do not use this setting.`;
34
34
  }
35
35
 
36
36
  /** Sentinel model value requesting that a subagent inherit the parent session's model. */
@@ -284,39 +284,6 @@ function enforceModelScopes(
284
284
  for (const violation of violations) (onWarn ?? defaultScopeWarn)(violation);
285
285
  }
286
286
 
287
- const MODEL_EXCLUSION_DIAGNOSTIC_MAX_LENGTH = 240;
288
- const MODEL_EXCLUSION_DIAGNOSTIC_MAX_ENTRIES = 20;
289
-
290
- function sanitizeModelExclusionDiagnostic(value: string | undefined, fallback: string): string {
291
- const normalized = typeof value === "string"
292
- ? value.replace(/[\u0000-\u001f\u007f\u2028\u2029]+/g, " ").trim()
293
- : "";
294
- return redactSecretValues(normalized || fallback).slice(0, MODEL_EXCLUSION_DIAGNOSTIC_MAX_LENGTH);
295
- }
296
-
297
- function formatModelExclusionExpiry(expiresAt: number): string {
298
- if (!Number.isFinite(expiresAt)) return "unknown";
299
- const date = new Date(expiresAt);
300
- return Number.isNaN(date.getTime()) ? "unknown" : date.toISOString();
301
- }
302
-
303
- function formatExcludedCandidateEvidence(candidate: string, exclusion: NonNullable<ReturnType<typeof findModelExclusion>>): string {
304
- const { provider, modelId } = parseModelKey(candidate);
305
- const displayCandidate = sanitizeModelExclusionDiagnostic(candidate, "unknown");
306
- const displayModel = sanitizeModelExclusionDiagnostic(modelId, "unknown");
307
- const displayProvider = sanitizeModelExclusionDiagnostic(provider ?? exclusion.provider, "unspecified");
308
- const reason = sanitizeModelExclusionDiagnostic(exclusion.reason, "runtime-failure");
309
- return `${displayCandidate} — model: ${displayModel}; provider: ${displayProvider}; reason: ${reason}; expires: ${formatModelExclusionExpiry(exclusion.expiresAt)}`;
310
- }
311
-
312
- function throwForExplicitModelExclusion(model: string): void {
313
- const exclusion = findModelExclusion(model);
314
- if (!exclusion) return;
315
- const reason = redactSecretValues((exclusion.reason ?? "runtime-failure").replace(/[\u0000-\u001f\u007f]+/g, " ")).slice(0, 240);
316
- const expiry = Number.isFinite(exclusion.expiresAt) ? `; expires: ${new Date(exclusion.expiresAt).toISOString()}` : "";
317
- throw new Error(`Requested subagent model '${model}' is excluded and cannot be replaced by a fallback (reason: ${reason}${expiry}).`);
318
- }
319
-
320
287
  /**
321
288
  * Resolve the `--model` override passed to a spawned subagent.
322
289
  *
@@ -353,7 +320,6 @@ export function resolveSubagentModelOverride(
353
320
  const candidate = resolveSubagentModelCandidate(explicit, availableModels, preferredProvider);
354
321
  if (options?.source === "explicit") {
355
322
  resolved = candidate ?? resolveRequiredSubagentModelCandidate(explicit, availableModels, preferredProvider);
356
- throwForExplicitModelExclusion(resolved);
357
323
  resolvedFromRegistry = true;
358
324
  } else if (candidate) {
359
325
  resolved = candidate;
@@ -397,19 +363,15 @@ export function resolveEffectiveSubagentModel(
397
363
 
398
364
  export type ModelOrigin = ModelSource | "configured";
399
365
 
400
- export interface BuildModelCandidatesOptions {
401
- /** Fallback models warn by default and throw when strict scope enforcement is enabled. */
366
+ export interface ResolveModelSelectionOptions {
402
367
  scope?: ModelScopeCheckRule | ModelScopeCheckRule[];
403
368
  onWarn?: (violation: ModelScopeViolation) => void;
404
369
  /** The primary model came from the running parent session, not configuration. */
405
370
  primaryModelFromParent?: boolean;
406
- /** How the primary model was selected. Explicit stays strict and does not rotate to fallbacks. */
371
+ /** How the model was selected. */
407
372
  origin?: ModelOrigin;
408
373
  }
409
374
 
410
- const ZERO_USABLE_MODEL_CANDIDATES_ERROR =
411
- "No usable subagent models remain after registry, scope, and cached-exclusion filtering.";
412
-
413
375
  export function resolveModelOrigin(input: {
414
376
  explicitModel?: string | boolean;
415
377
  agentModel?: string | boolean;
@@ -434,169 +396,30 @@ export function inheritsParentModel(
434
396
  return Boolean(parentModel && (!trimmed || trimmed === INHERIT_MODEL));
435
397
  }
436
398
 
437
- export function buildModelCandidates(
438
- primaryModel: string | undefined,
439
- fallbackModels: string[] | undefined,
399
+ export function resolveModelSelection(
400
+ model: string | undefined,
440
401
  availableModels: AvailableModelInfo[] | undefined,
441
402
  preferredProvider?: string,
442
- options?: BuildModelCandidatesOptions,
443
- ): string[] {
444
- if (!primaryModel) throwForUnresolvedEnforcedInheritScope(options?.scope, true);
403
+ options?: ResolveModelSelectionOptions,
404
+ ): ModelSelectionEvidence {
405
+ if (!model) throwForUnresolvedEnforcedInheritScope(options?.scope, true);
445
406
  const origin = options?.origin ?? (options?.primaryModelFromParent ? "inherited" : "configured");
407
+ const requestedModel = origin === "inherited" ? undefined : model;
446
408
  const scopes = configuredScopes(options?.scope);
447
- type ExcludedCandidate = { candidate: string; exclusion: NonNullable<ReturnType<typeof findModelExclusion>> };
448
- const excludedCandidates: ExcludedCandidate[] = [];
449
- let excludedCandidateCount = 0;
450
- const warnCachedExclusion = (candidate: string, exclusion: NonNullable<ReturnType<typeof findModelExclusion>>) => {
451
- excludedCandidateCount++;
452
- if (excludedCandidates.length < MODEL_EXCLUSION_DIAGNOSTIC_MAX_ENTRIES) excludedCandidates.push({ candidate, exclusion });
453
- const displayCandidate = sanitizeModelExclusionDiagnostic(candidate, "unknown");
454
- const reason = sanitizeModelExclusionDiagnostic(exclusion.reason, "runtime-failure");
455
- console.warn(`[pi-subagents] Skipping model '${displayCandidate}' due to a cached exclusion (reason: ${reason}; expires: ${formatModelExclusionExpiry(exclusion.expiresAt)}).`);
456
- };
457
- if (origin === "explicit" && primaryModel) {
458
- const normalized = resolveRequiredSubagentModelCandidate(primaryModel.trim(), availableModels, preferredProvider);
459
- throwForExplicitModelExclusion(normalized);
409
+ if (origin === "explicit" && model) {
410
+ const normalized = resolveRequiredSubagentModelCandidate(model.trim(), availableModels, preferredProvider);
460
411
  enforceModelScopes(normalized, scopes, "explicit", options?.onWarn);
461
- primaryModel = normalized;
462
- }
463
- const seen = new Set<string>();
464
- const candidates: string[] = [];
465
- const rawCandidates = [primaryModel, ...(fallbackModels ?? [])];
466
- let skippedPrimary: string | undefined;
467
- let skippedFallback: string | undefined;
468
- for (let index = 0; index < rawCandidates.length; index++) {
469
- const raw = rawCandidates[index];
470
- if (!raw) continue;
471
- const model = raw.trim();
472
- const normalized = index === 0 && (origin === "inherited" || origin === "explicit" || options?.primaryModelFromParent)
473
- ? model
474
- : resolveSubagentModelCandidate(model, availableModels, preferredProvider);
475
- if (!normalized) {
476
- if (index === 0) skippedPrimary = model;
477
- else {
478
- skippedFallback ??= model;
479
- console.warn(`[pi-subagents] Skipping fallback model '${model}' because it is unavailable in this environment.`);
480
- }
481
- continue;
482
- }
483
- if (seen.has(normalized)) continue;
484
- if (index > 0 || scopes.some((scope) => scope.enforce === true && scope.strict === true)) {
485
- enforceModelScopes(normalized, scopes, "inherited", options?.onWarn);
486
- }
487
- seen.add(normalized);
488
- candidates.push(normalized);
412
+ model = normalized;
489
413
  }
490
- const resolved = filterFallbackCandidates(candidates, { onExcluded: warnCachedExclusion });
491
- if (resolved.length === 0) {
492
- if (skippedPrimary) resolveRequiredSubagentModelCandidate(skippedPrimary, availableModels, preferredProvider);
493
- if (candidates.length === 0 && skippedFallback) resolveRequiredSubagentModelCandidate(skippedFallback, availableModels, preferredProvider);
494
- if (candidates.length > 0) {
495
- const shownExclusions = excludedCandidates;
496
- const omittedExclusions = excludedCandidateCount - shownExclusions.length;
497
- const evidence = shownExclusions.length > 0
498
- ? ` (excluded: ${shownExclusions.map(({ candidate, exclusion }) => formatExcludedCandidateEvidence(candidate, exclusion)).join("; ")}${omittedExclusions > 0 ? `; ... and ${omittedExclusions} more` : ""})`
499
- : "";
500
- throw new Error(`${ZERO_USABLE_MODEL_CANDIDATES_ERROR}${evidence}`);
501
- }
502
- return resolved;
414
+ const resolved = model && (origin === "inherited" || origin === "explicit" || options?.primaryModelFromParent)
415
+ ? model.trim()
416
+ : model ? resolveRequiredSubagentModelCandidate(model.trim(), availableModels, preferredProvider) : undefined;
417
+ if (resolved && scopes.some((scope) => scope.enforce === true && scope.strict === true)) {
418
+ enforceModelScopes(resolved, scopes, "inherited", options?.onWarn);
503
419
  }
504
- if (skippedPrimary) {
505
- console.warn(`[pi-subagents] Skipping primary model '${skippedPrimary}' because it is unavailable in this environment.`);
506
- }
507
- return resolved;
420
+ return { ...(resolved ? { model: resolved } : {}), ...(requestedModel ? { requestedModel } : {}) };
508
421
  }
509
-
510
- const RETRYABLE_MODEL_FAILURE_PATTERNS = [
511
- /rate\s*limit/i,
512
- /usage\s*limit/i,
513
- /too many requests/i,
514
- /\b429\b/,
515
- /quota/i,
516
- /billing/i,
517
- /credit/i,
518
- /auth(?:entication)?/i,
519
- /unauthori[sz]ed/i,
520
- /forbidden/i,
521
- /api key/i,
522
- /token expired/i,
523
- /invalid key/i,
524
- /provider.*unavailable/i,
525
- /model.*unavailable/i,
526
- /model.*disabled/i,
527
- /model.*not found/i,
528
- /unknown model/i,
529
- /overloaded/i,
530
- /service unavailable/i,
531
- /temporar(?:ily)? unavailable/i,
532
- /connection\s+(?:error|reset|closed|aborted)/i,
533
- /connection refused/i,
534
- /fetch failed/i,
535
- /network error/i,
536
- /socket hang up/i,
537
- /stream ended without finish_reason/i,
538
- /upstream/i,
539
- /timed? out/i,
540
- /timeout/i,
541
- /\b500\b/,
542
- /\b502\b/,
543
- /\b503\b/,
544
- /\b504\b/,
545
- /internal server error/i,
546
- /cold.?start/i,
547
- /empty response/i,
548
- /no output/i,
549
- /model.*(?:load|fail|error)/i,
550
- ];
551
-
552
- /**
553
- * Failures reported as `<tool> failed (exit N): ...` or `<tool> failed with
554
- * exit code N` come from a tool call inside the child's task, not from the
555
- * provider/model, however network-flavored their details read. Retrying a
556
- * different model cannot fix them and would rerun the whole task. Tool names
557
- * include namespaced forms like `mcp.server/write`.
558
- */
559
- const TOOL_FAILURE_PREFIX = /^[\w.:@/-]+ failed (?:(?:\(exit \d+\):)|(?:with exit code \d+))(?:\s|$)/i;
560
-
561
- export function isRetryableModelFailure(error: string | undefined): boolean {
562
- if (!error) return false;
563
- if (TOOL_FAILURE_PREFIX.test(error.trim())) return false;
564
- return RETRYABLE_MODEL_FAILURE_PATTERNS.some((pattern) => pattern.test(error));
565
- }
566
-
567
- function messageError(message: unknown): string | undefined {
568
- if (!message || typeof message !== "object") return undefined;
569
- const value = (message as { errorMessage?: unknown }).errorMessage;
570
- return typeof value === "string" ? value : undefined;
571
- }
572
-
573
- export function isRetryableModelFailureAttempt(input: { error: string | undefined; messages?: readonly unknown[]; toolCount?: number; startupBlocked?: boolean }): boolean {
574
- // A startup guard blocked the child before its first model turn: no model
575
- // change can fix it, and recording it as a model failure would poison the
576
- // model registry with a long-lived exclusion for a policy decision.
577
- if (input.startupBlocked === true) return false;
578
- if (!isRetryableModelFailure(input.error)) return false;
579
- if ((input.toolCount ?? 0) > 0) return false;
580
- if (input.error === "Subagent produced no output (possible model cold-start or empty response)." || /^Subagent produced no output after terminal assistant stopReason "[^"]+"\.$/.test(input.error ?? "")) return true;
581
- if ((input.toolCount ?? 0) === 0 && (input.messages?.length ?? 0) === 0) return true;
582
- const error = input.error?.trim();
583
- return Boolean(error && input.messages?.some((message) => messageError(message)?.trim() === error));
584
- }
585
-
586
- export function recordRetryableModelFailure(model: string | undefined, error: string | undefined): void {
587
- if (!model || !isRetryableModelFailure(error)) return;
588
- const { provider, modelId } = parseModelKey(model);
589
- recordModelFailure({ modelId, reason: error, ...(provider ? { provider } : {}) });
590
- }
591
-
592
- /**
593
- * Context-overflow signals. These are deliberately NOT part of
594
- * {@link RETRYABLE_MODEL_FAILURE_PATTERNS}: an overflow means the input was too
595
- * large for the model's context window, so retrying the same input on another
596
- * model (or the same model again) cannot succeed. Callers should treat overflow
597
- * as a terminal, non-retryable failure and surface a clear "input too large"
598
- * error instead of burning fallback attempts on a guaranteed failure.
599
- */
422
+ /** Context-overflow signals used to surface a clear input-too-large error. */
600
423
  const CONTEXT_OVERFLOW_PATTERNS = [
601
424
  /context(?: length| window| limit)? (?:exceed|overflow|too long)/i,
602
425
  /maximum context length/i,
@@ -613,13 +436,6 @@ const CONTEXT_OVERFLOW_PATTERNS = [
613
436
 
614
437
  export function isContextOverflow(error: string | undefined): boolean {
615
438
  if (!error) return false;
616
- if (TOOL_FAILURE_PREFIX.test(error.trim())) return false;
439
+ if (/^[\w.:@/-]+ failed (?:(?:\(exit \d+\):)|(?:with exit code \d+))(?:\s|$)/i.test(error.trim())) return false;
617
440
  return CONTEXT_OVERFLOW_PATTERNS.some((pattern) => pattern.test(error));
618
441
  }
619
-
620
- export function formatModelAttemptNote(attempt: ModelAttemptSummary, nextModel?: string): string {
621
- const failure = attempt.error?.trim() || `exit ${attempt.exitCode ?? 1}`;
622
- return nextModel
623
- ? `[fallback] ${attempt.model} failed: ${failure}. Retrying with ${nextModel}.`
624
- : `[fallback] ${attempt.model} failed: ${failure}.`;
625
- }
@@ -17,7 +17,7 @@ import { splitKnownThinkingSuffix } from "../../shared/model-info.ts";
17
17
 
18
18
  export interface ModelScopeRule {
19
19
  enforce?: boolean;
20
- /** Reject inherited and fallback models outside the allowlist instead of warning. */
20
+ /** Reject inherited models outside the allowlist instead of warning. */
21
21
  strict?: boolean;
22
22
  /** Glob-style allow patterns (only `*` is special), matched against `provider/id`. */
23
23
  allow?: string[];
@@ -6,8 +6,8 @@ import {
6
6
  TEMP_ROOT_DIR,
7
7
  type AsyncJobState,
8
8
  type AsyncStatus,
9
- type LaunchResolvedChildExtensionsV1,
10
- type RuntimeAcknowledgedChildExtensionsV1,
9
+ type LaunchResolvedChildExtensions,
10
+ type RuntimeAcknowledgedChildExtensions,
11
11
  type NestedRouteInfo,
12
12
  type TurnBudgetState,
13
13
  type NestedRunSummary,
@@ -229,7 +229,7 @@ function sanitizeCost(value: unknown): NestedRunSummary["totalCost"] | undefined
229
229
  : undefined;
230
230
  }
231
231
 
232
- function sanitizeLaunchResolvedExtensions(value: unknown): LaunchResolvedChildExtensionsV1 | undefined {
232
+ function sanitizeLaunchResolvedExtensions(value: unknown): LaunchResolvedChildExtensions | undefined {
233
233
  if (!value || typeof value !== "object") return undefined;
234
234
  const raw = value as Record<string, unknown>;
235
235
  if (raw.version !== 1 || raw.source !== "launch-resolved" || typeof raw.disableAmbientExtensions !== "boolean") return undefined;
@@ -244,16 +244,18 @@ function sanitizeLaunchResolvedExtensions(value: unknown): LaunchResolvedChildEx
244
244
  disableAmbientExtensions: raw.disableAmbientExtensions,
245
245
  runtime: stringList(raw.runtime),
246
246
  configured: stringList(raw.configured),
247
+ required: Array.isArray(raw.required) ? raw.required.filter((item): item is string => typeof item === "string" && /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(item)).slice(0, 32) : [],
247
248
  effective: stringList(raw.effective),
248
249
  omitted: {
249
250
  runtime: omittedCount("runtime"),
250
251
  configured: omittedCount("configured"),
252
+ required: omittedCount("required"),
251
253
  effective: omittedCount("effective"),
252
254
  },
253
255
  };
254
256
  }
255
257
 
256
- function sanitizeRuntimeAcknowledgedExtensions(value: unknown): RuntimeAcknowledgedChildExtensionsV1 | undefined {
258
+ function sanitizeRuntimeAcknowledgedExtensions(value: unknown): RuntimeAcknowledgedChildExtensions | undefined {
257
259
  if (!value || typeof value !== "object") return undefined;
258
260
  const raw = value as Record<string, unknown>;
259
261
  if (raw.version !== 1 || raw.source !== "child-runtime" || !Array.isArray(raw.ids)) return undefined;
@@ -273,7 +275,7 @@ function sanitizeRuntimeAcknowledgedExtensions(value: unknown): RuntimeAcknowled
273
275
  };
274
276
  }
275
277
 
276
- function runtimeAcknowledgedEntry(value: unknown): { runtimeAcknowledgedExtensions: RuntimeAcknowledgedChildExtensionsV1 } | Record<string, never> {
278
+ function runtimeAcknowledgedEntry(value: unknown): { runtimeAcknowledgedExtensions: RuntimeAcknowledgedChildExtensions } | Record<string, never> {
277
279
  const sanitized = sanitizeRuntimeAcknowledgedExtensions(value);
278
280
  return sanitized ? { runtimeAcknowledgedExtensions: sanitized } : {};
279
281
  }
@@ -298,7 +300,7 @@ function sanitizeTurnBudget(value: unknown): TurnBudgetState | undefined {
298
300
  }
299
301
 
300
302
  function sanitizeState(value: unknown, fallback: NestedRunState): NestedRunState {
301
- return value === "queued" || value === "running" || value === "complete" || value === "failed" || value === "partial" || value === "paused" || value === "stopped"
303
+ return value === "queued" || value === "running" || value === "complete" || value === "failed" || value === "partial" || value === "paused" || value === "stopped" || value === "rejected"
302
304
  ? value
303
305
  : fallback;
304
306
  }
@@ -324,7 +326,7 @@ function sanitizeStep(input: unknown, depth: number): NestedStepSummary | undefi
324
326
  const raw = input as Record<string, unknown>;
325
327
  const agent = stringValue(raw.agent, 128);
326
328
  if (!agent) return undefined;
327
- const status = raw.status === "pending" || raw.status === "running" || raw.status === "complete" || raw.status === "completed" || raw.status === "failed" || raw.status === "paused" || raw.status === "stopped"
329
+ const status = raw.status === "pending" || raw.status === "running" || raw.status === "complete" || raw.status === "completed" || raw.status === "failed" || raw.status === "partial" || raw.status === "paused" || raw.status === "stopped" || raw.status === "rejected"
328
330
  ? raw.status
329
331
  : "pending";
330
332
  const model = stringValue(raw.model);
@@ -475,7 +477,7 @@ export function parseNestedEventRecords(content: string, route: NestedRoute): Ne
475
477
  }
476
478
 
477
479
  function terminal(state: NestedRunState): boolean {
478
- return state === "complete" || state === "failed" || state === "partial" || state === "paused" || state === "stopped";
480
+ return state === "complete" || state === "failed" || state === "partial" || state === "paused" || state === "rejected" || state === "stopped";
479
481
  }
480
482
 
481
483
  function mergeBoundedChildren(existing: NestedRunSummary[] | undefined, incoming: NestedRunSummary[] | undefined): NestedRunSummary[] | undefined {
@@ -1108,8 +1110,15 @@ export function isTopLevelAsyncDir(asyncDir: string): boolean {
1108
1110
  return containedPath(DIRS.async, resolved) && !containedPath(path.join(TEMP_ROOT_DIR, "nested-subagent-runs"), resolved);
1109
1111
  }
1110
1112
 
1111
- export function nestedResultsPath(rootRunId: string, id: string): string {
1113
+ export function nestedRunScope(rootRunId: string) {
1112
1114
  assertSafeId("rootRunId", rootRunId);
1115
+ return {
1116
+ asyncDirRoot: path.join(TEMP_ROOT_DIR, "nested-subagent-runs", rootRunId),
1117
+ resultsDir: path.join(DIRS.results, "nested", rootRunId),
1118
+ };
1119
+ }
1120
+
1121
+ export function nestedResultsPath(rootRunId: string, id: string): string {
1113
1122
  assertSafeId("id", id);
1114
- return path.join(DIRS.results, "nested", rootRunId, `${id}.json`);
1123
+ return path.join(nestedRunScope(rootRunId).resultsDir, `${id}.json`);
1115
1124
  }
@@ -29,7 +29,7 @@ const ORCA_CREATE_WATCHDOG_SCRIPT = [
29
29
  "function exists(file){try{return fs.existsSync(file)}catch{return false}}",
30
30
  "function keepQueued(){try{const now=new Date();fs.utimesSync(done,now,now)}catch{}}",
31
31
  "function predecessorReady(){if(previous==='-')return true;if(exists(previous.replace(/\\.pending$/,'.ready')))return true;try{return Date.now()-fs.statSync(previous).mtimeMs>=waitTimeout}catch{return true}}",
32
- "function updateManifest(state,stdout=''){if(manifest==='-')return;try{const payload=JSON.parse(fs.readFileSync(manifest,'utf8'));payload.state=state;payload.updatedAt=new Date().toISOString();const raw=stdout.trim().split(/\\r?\\n/).filter(Boolean).at(-1);if(raw){try{payload.orca=JSON.parse(raw)}catch{payload.orcaRaw=raw.slice(0,4096)}}fs.writeFileSync(manifest,JSON.stringify(payload,null,2)+'\\n')}catch{}}",
32
+ "function updateManifest(state,stdout=''){if(manifest==='-')return;try{const payload=JSON.parse(fs.readFileSync(manifest,'utf8'));payload.state=state;payload.updatedAt=new Date().toISOString();const raw=stdout.trim();if(raw){try{payload.orca=JSON.parse(raw)}catch{payload.orcaRaw=raw.slice(0,4096)}}fs.writeFileSync(manifest,JSON.stringify(payload,null,2)+'\\n')}catch{}}",
33
33
  "function start(){",
34
34
  " try{",
35
35
  " const child=spawn(command,args,{stdio:['ignore','pipe','ignore'],windowsHide:true});",
@@ -53,6 +53,8 @@ const ORCA_CLEANUP_WATCHDOG_SCRIPT = [
53
53
  ].join("");
54
54
 
55
55
  export interface OrcaProgressTab {
56
+ /** Resolves when the terminal-create watchdog closes, after its final manifest/queue writes (success or failure). Not viewer completion. */
57
+ readonly creationSettled: Promise<void>;
56
58
  append(text: string): void;
57
59
  section(input: { agent: string; index: number; count: number }): void;
58
60
  event(event: { type?: string; message?: Message; toolName?: string; args?: unknown }): void;
@@ -402,6 +404,8 @@ export function createOrcaProgressTab(input: {
402
404
  }
403
405
  };
404
406
  let createSettled = false;
407
+ let resolveCreationSettled!: () => void;
408
+ const creationSettled = new Promise<void>((resolve) => { resolveCreationSettled = resolve; });
405
409
  let cleanupPaths: string[] | undefined;
406
410
  const scheduleDeferredCleanup = () => {
407
411
  if (!createSettled || cleanupPaths === undefined) return;
@@ -434,6 +438,7 @@ export function createOrcaProgressTab(input: {
434
438
  createSettled = true;
435
439
  if (code !== 0) failObserver();
436
440
  scheduleDeferredCleanup();
441
+ resolveCreationSettled();
437
442
  });
438
443
  watchdog.once("error", () => {
439
444
  markCreateReady();
@@ -450,6 +455,7 @@ export function createOrcaProgressTab(input: {
450
455
 
451
456
  let finished = false;
452
457
  return {
458
+ creationSettled,
453
459
  append(text) {
454
460
  if (finished) return;
455
461
  writeProgress(text);
@@ -17,6 +17,7 @@ import type {
17
17
  WorktreeCleanupReport,
18
18
  WorktreeDiff,
19
19
  WorktreeSetup,
20
+ WorktreeSetupProgress,
20
21
  WorktreeCleanupIntent,
21
22
  } from "./worktree.ts";
22
23
  import { cleanupWorktrees } from "./worktree.ts";
@@ -614,18 +615,62 @@ export function parallelHandoffPath(baseDir: string, runId?: string): string {
614
615
  return runId ? path.join(baseDir, "handoffs", `${runId}.json`) : path.join(baseDir, "handoff.json");
615
616
  }
616
617
 
617
- export function writePendingParallelHandoff(input: {
618
- manifestPath: string;
619
- runId: string;
620
- mode: "single" | "parallel" | "chain";
621
- source: "foreground" | "async";
622
- cwd: string;
623
- stepIndex: number;
624
- flatStartIndex: number;
625
- setup: WorktreeSetup;
626
- laneBindings?: ParallelHandoffLaneBinding[];
627
- }): ParallelHandoffReference {
628
- return writeParallelHandoffGroup({ ...input, diffs: [], results: [] });
618
+ /** Synchronous onProgress projection shared by setup owners; snapshots are cumulative. */
619
+ export function writeWorktreeSetupHandoff(input: Omit<Parameters<typeof writeParallelHandoffGroup>[0], "setup" | "diffs" | "results" | "cleanup" | "now"> & {
620
+ progress: WorktreeSetupProgress;
621
+ }): ParallelHandoffReference | undefined {
622
+ const { progress, ...handoff } = input;
623
+ const { setup, attempts, cleanup } = progress;
624
+ // Preflight has no allocation identity yet. Its original error belongs to the caller.
625
+ if (attempts.length === 0 && setup.worktrees.length === 0) return undefined;
626
+ if (!setup.cwd || !setup.baseCommit) throw new Error("Cannot publish worktree allocation evidence without repository and base commit.");
627
+ const diagnostic = (text: string): string => text.slice(0, 512);
628
+ // Never copy argv, environment, Error objects or captured stdout/stderr into artifacts.
629
+ const commandEvidence = (command: WorktreeSetupProgress["command"]) => command && ({
630
+ pid: command.pid,
631
+ processGroupId: command.processGroupId,
632
+ ...(command.result ? {
633
+ status: command.result.status,
634
+ signal: command.result.signal,
635
+ failed: Boolean(command.result.error),
636
+ outputIncomplete: command.result.outputIncomplete,
637
+ processTree: command.result.processTree?.state,
638
+ } : {}),
639
+ });
640
+ const errors = [
641
+ `Worktree setup ${JSON.stringify({ runId: input.runId, stepIndex: input.stepIndex, phase: progress.phase,
642
+ unknown: Boolean(progress.unknown), command: commandEvidence(progress.command) })}`,
643
+ ...attempts.map((attempt) => {
644
+ const task = cleanup?.tasks.find((candidate) => candidate.index === attempt.index);
645
+ return `Allocation attempt ${JSON.stringify({ index: attempt.index, branch: attempt.branch,
646
+ path: attempt.path ?? null, validated: attempt.validated,
647
+ command: commandEvidence(attempt.command), hookCommand: commandEvidence(attempt.hookCommand),
648
+ ...(task ? { worktreeRemoved: task.worktreeRemoved, branchRemoved: task.branchRemoved,
649
+ preserved: task.preserved, reason: task.reason && diagnostic(task.reason), errors: task.errors?.map(diagnostic) } : {}),
650
+ })}`;
651
+ }),
652
+ ...(cleanup?.errors?.map(diagnostic) ?? []),
653
+ ...(progress.unknown ? ["Setup settlement unknown; manual reconciliation required."] : []),
654
+ ];
655
+ return writeParallelHandoffGroup({
656
+ ...handoff, setup, diffs: [], results: [],
657
+ laneBindings: input.laneBindings?.filter((binding) => setup.worktrees.some((worktree) => worktree.index === binding.taskIndex)),
658
+ cleanup: {
659
+ state: cleanup?.state ?? "partial",
660
+ pruned: cleanup?.pruned ?? false,
661
+ errors,
662
+ // An attempted native path is not a validated recovery task, even during rollback.
663
+ tasks: setup.worktrees.map((worktree) => {
664
+ const task = cleanup?.tasks.find((candidate) => candidate.index === worktree.index);
665
+ return task ? { ...task, reason: task.reason && diagnostic(task.reason), errors: task.errors?.map(diagnostic) } : {
666
+ index: worktree.index, path: worktree.path, branch: worktree.branch,
667
+ provider: worktree.provider, naming: worktree.naming,
668
+ worktreeRemoved: false, branchRemoved: false, preserved: true,
669
+ reason: "setup pending durable handoff capture",
670
+ };
671
+ }),
672
+ },
673
+ });
629
674
  }
630
675
 
631
676
  export function formatParallelHandoffReference(reference: ParallelHandoffReference): string {