@xzzpig/pi-subagents 0.7.0 → 0.9.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 (234) hide show
  1. package/CHANGELOG.md +456 -4
  2. package/README.md +3 -3
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +13 -3
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +154 -42
  12. package/docs/configuration.md +85 -26
  13. package/docs/extension-api.md +81 -16
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +75 -11
  16. package/docs/observability.md +34 -21
  17. package/docs/tool-reference.md +142 -18
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +148 -4
  20. package/index.ts +10 -1
  21. package/install.mjs +1 -1
  22. package/package.json +7 -6
  23. package/prompts/council.md +19 -7
  24. package/prompts/parallel-review.md +5 -1
  25. package/prompts/review-loop.md +11 -7
  26. package/skills/council-mode/SKILL.md +44 -215
  27. package/skills/council-mode/references/pass-contracts.md +150 -0
  28. package/skills/pi-subagents/SKILL.md +90 -32
  29. package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
  30. package/skills/pi-subagents/references/execution-controls.md +104 -19
  31. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  32. package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
  33. package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
  34. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  35. package/src/agents/agent-management.ts +471 -114
  36. package/src/agents/agent-refinements.ts +4 -4
  37. package/src/agents/agent-serializer.ts +16 -4
  38. package/src/agents/agents.ts +1076 -351
  39. package/src/agents/builtin-names.ts +6 -0
  40. package/src/agents/runtime-agent-events.ts +70 -0
  41. package/src/agents/runtime-agent-registry.ts +31 -20
  42. package/src/api/agents.ts +10 -5
  43. package/src/api/background-work.ts +12 -3
  44. package/src/api/capability-ceiling.ts +0 -1
  45. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  46. package/src/api/delegation.ts +0 -7
  47. package/src/api/external-job-provider.ts +10 -1
  48. package/src/api/external-runs.ts +67 -4
  49. package/src/api/preflight.ts +97 -34
  50. package/src/api/project-panes.ts +2 -0
  51. package/src/api/shared-types.ts +6 -0
  52. package/src/extension/config.ts +90 -0
  53. package/src/extension/doctor.ts +15 -13
  54. package/src/extension/fanout-child.ts +17 -16
  55. package/src/extension/index.ts +139 -41
  56. package/src/extension/public-execution.ts +113 -22
  57. package/src/extension/rpc.ts +182 -13
  58. package/src/extension/schemas.ts +63 -21
  59. package/src/extension/tool-description.ts +48 -23
  60. package/src/extension/tool-result.ts +19 -0
  61. package/src/inspectors/herdr/actions.ts +2 -1
  62. package/src/inspectors/herdr/client.ts +3 -3
  63. package/src/inspectors/herdr/focus.ts +55 -0
  64. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  65. package/src/inspectors/herdr/project-panes.ts +228 -44
  66. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  67. package/src/integrations/herdr-status.ts +75 -5
  68. package/src/intercom/native-supervisor-channel.ts +138 -60
  69. package/src/intercom/result-intercom.ts +2 -0
  70. package/src/intercom/supervisor-ui.ts +243 -0
  71. package/src/profiles/profiles.ts +5 -6
  72. package/src/runs/background/active-async-capacity.ts +103 -18
  73. package/src/runs/background/async-execution.ts +492 -125
  74. package/src/runs/background/async-job-tracker.ts +127 -28
  75. package/src/runs/background/async-resume.ts +67 -29
  76. package/src/runs/background/async-retention.ts +21 -4
  77. package/src/runs/background/async-status-snapshot.ts +23 -261
  78. package/src/runs/background/async-status.ts +199 -14
  79. package/src/runs/background/auto-drain.ts +1 -1
  80. package/src/runs/background/chain-append.ts +8 -3
  81. package/src/runs/background/chain-root-attachment.ts +79 -8
  82. package/src/runs/background/control-channel.ts +101 -214
  83. package/src/runs/background/fleet-view.ts +38 -22
  84. package/src/runs/background/inspect-rpc.ts +8 -8
  85. package/src/runs/background/notify.ts +295 -8
  86. package/src/runs/background/process-terminal.ts +16 -0
  87. package/src/runs/background/result-delivery-ownership.ts +45 -0
  88. package/src/runs/background/result-files.ts +28 -14
  89. package/src/runs/background/result-watcher.ts +43 -19
  90. package/src/runs/background/resume-guidance.ts +2 -2
  91. package/src/runs/background/retained-children.ts +1 -1
  92. package/src/runs/background/run-child-session.ts +613 -0
  93. package/src/runs/background/run-status.ts +99 -18
  94. package/src/runs/background/runner-aliases.ts +125 -0
  95. package/src/runs/background/runner-child-sessions.ts +31 -0
  96. package/src/runs/background/scheduled-runs.ts +174 -18
  97. package/src/runs/background/stale-run-reconciler.ts +13 -4
  98. package/src/runs/background/steering.ts +8 -15
  99. package/src/runs/background/subagent-runner.ts +959 -1159
  100. package/src/runs/background/subagent-wait.ts +86 -31
  101. package/src/runs/background/terminal-run-index.ts +1 -1
  102. package/src/runs/background/wait-completions.ts +45 -2
  103. package/src/runs/background/wait-config.ts +23 -9
  104. package/src/runs/background/wait-tool.ts +27 -19
  105. package/src/runs/foreground/async-steering-action.ts +3 -19
  106. package/src/runs/foreground/async-stop-action.ts +23 -2
  107. package/src/runs/foreground/execution.ts +585 -481
  108. package/src/runs/foreground/foreground-control.ts +13 -0
  109. package/src/runs/foreground/foreground-history.ts +26 -3
  110. package/src/runs/foreground/subagent-executor.ts +1549 -410
  111. package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
  112. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  113. package/src/runs/shared/abort-recovery.ts +119 -0
  114. package/src/runs/shared/acceptance.ts +147 -39
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +565 -0
  117. package/src/runs/shared/background-process-options.ts +9 -0
  118. package/src/runs/shared/capability-ceiling.ts +2 -2
  119. package/src/runs/shared/child-hooks.ts +25 -0
  120. package/src/runs/shared/child-identity.ts +62 -0
  121. package/src/runs/shared/child-launch-plan.ts +151 -0
  122. package/src/runs/shared/child-launch.ts +314 -0
  123. package/src/runs/shared/child-lifecycle.ts +25 -0
  124. package/src/runs/shared/child-runtime-config.ts +126 -0
  125. package/src/runs/shared/child-session.ts +342 -0
  126. package/src/runs/shared/child-tool-plan.ts +540 -0
  127. package/src/runs/shared/claude-code-adapter.ts +133 -0
  128. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  129. package/src/runs/shared/completion-evidence.ts +89 -0
  130. package/src/runs/shared/completion-guard.ts +57 -6
  131. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  132. package/src/runs/shared/dynamic-fanout.ts +4 -4
  133. package/src/runs/shared/extension-bindings.ts +78 -0
  134. package/src/runs/shared/external-cli-contract.ts +167 -0
  135. package/src/runs/shared/external-cli-preflight.ts +138 -0
  136. package/src/runs/shared/external-cli-runner.ts +349 -54
  137. package/src/runs/shared/external-job-bridge.ts +53 -37
  138. package/src/runs/shared/external-job-runner.ts +126 -23
  139. package/src/runs/shared/fast-mode-extension.ts +10 -0
  140. package/src/runs/shared/host-step-status.ts +231 -0
  141. package/src/runs/shared/lane-metadata.ts +126 -0
  142. package/src/runs/shared/launch-cwd.ts +16 -0
  143. package/src/runs/shared/long-running-guard.ts +2 -1
  144. package/src/runs/shared/mcp-config-sources.ts +422 -0
  145. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  146. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  147. package/src/runs/shared/model-exclusions.ts +141 -10
  148. package/src/runs/shared/model-fallback.ts +187 -33
  149. package/src/runs/shared/model-scope.ts +106 -39
  150. package/src/runs/shared/mutation-evidence.ts +199 -0
  151. package/src/runs/shared/nested-events.ts +38 -48
  152. package/src/runs/shared/nested-path.ts +0 -14
  153. package/src/runs/shared/nested-render.ts +9 -5
  154. package/src/runs/shared/orca-progress-tabs.ts +83 -16
  155. package/src/runs/shared/parallel-handoff.ts +423 -7
  156. package/src/runs/shared/parallel-utils.ts +28 -5
  157. package/src/runs/shared/permissions.ts +1 -14
  158. package/src/runs/shared/pi-spawn.ts +69 -35
  159. package/src/runs/shared/process-signal.ts +16 -0
  160. package/src/runs/shared/run-fanout-budget.ts +0 -13
  161. package/src/runs/shared/run-history.ts +21 -1
  162. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  163. package/src/runs/shared/single-output.ts +89 -22
  164. package/src/runs/shared/structured-output.ts +61 -7
  165. package/src/runs/shared/subagent-control.ts +6 -2
  166. package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
  167. package/src/runs/shared/task-intent.ts +21 -7
  168. package/src/runs/shared/tool-availability.ts +18 -64
  169. package/src/runs/shared/tool-budget.ts +0 -14
  170. package/src/runs/shared/tool-timeout.ts +1 -1
  171. package/src/runs/shared/workflow-graph.ts +16 -0
  172. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  173. package/src/runs/shared/worktree.ts +571 -62
  174. package/src/shared/atomic-json.ts +3 -1
  175. package/src/shared/child-session-name.ts +46 -0
  176. package/src/shared/extension-context.ts +24 -0
  177. package/src/shared/fork-context.ts +21 -12
  178. package/src/shared/fork-session-cwd.ts +27 -0
  179. package/src/shared/formatters.ts +18 -3
  180. package/src/shared/jsonl-writer.ts +11 -0
  181. package/src/shared/launch-contract.ts +20 -6
  182. package/src/shared/pruned-fork.ts +450 -0
  183. package/src/shared/session-file-trust.ts +19 -0
  184. package/src/shared/session-tokens.ts +14 -3
  185. package/src/shared/settings.ts +21 -102
  186. package/src/shared/shortcuts.ts +17 -0
  187. package/src/shared/thinking-ceiling.ts +46 -0
  188. package/src/shared/types.ts +644 -75
  189. package/src/shared/utils.ts +60 -93
  190. package/src/shared/workflow-child-permit.ts +207 -0
  191. package/src/slash/delegation-adapters.ts +1 -9
  192. package/src/slash/delegation-request.ts +0 -4
  193. package/src/slash/prompt-template-bridge.ts +37 -1
  194. package/src/slash/slash-bridge.ts +1 -2
  195. package/src/slash/slash-commands.ts +383 -116
  196. package/src/slash/slash-live-state.ts +22 -11
  197. package/src/slash/subagents-admin.ts +29 -12
  198. package/src/tui/fleet-native-transcript.ts +4 -0
  199. package/src/tui/fleet-status.ts +278 -90
  200. package/src/tui/fleet-transcript.ts +11 -5
  201. package/src/tui/fleet.ts +54 -28
  202. package/src/tui/render-helpers.ts +31 -0
  203. package/src/tui/render.ts +1433 -166
  204. package/src/watchdog/change-signature.ts +40 -1
  205. package/src/watchdog/child-status.ts +54 -34
  206. package/src/watchdog/diff-tool.ts +77 -0
  207. package/src/watchdog/emission-guard.ts +5 -3
  208. package/src/watchdog/guidance.ts +20 -0
  209. package/src/watchdog/permission-arbiter.ts +59 -52
  210. package/src/watchdog/register-child.ts +28 -25
  211. package/src/watchdog/register-main.ts +10 -9
  212. package/src/watchdog/render.ts +4 -5
  213. package/src/watchdog/review.ts +15 -4
  214. package/src/watchdog/rules.ts +70 -0
  215. package/src/watchdog/runtime.ts +75 -92
  216. package/src/watchdog/scope.ts +0 -11
  217. package/src/watchdog/settings.ts +48 -104
  218. package/src/watchdog/turn-delta.ts +1 -1
  219. package/src/watchdog/types.ts +18 -32
  220. package/src/watchdog/warning-format.ts +0 -1
  221. package/src/workflows/chat-progress.ts +7 -3
  222. package/src/workflows/host-command.ts +235 -0
  223. package/src/workflows/scripted-workflow.ts +1142 -69
  224. package/src/workflows/workflow-checklist.ts +439 -0
  225. package/src/workflows/workflow-child-summary.ts +121 -0
  226. package/src/workflows/workflow-preflight.ts +297 -0
  227. package/src/workflows/workflow-receipt.ts +232 -6
  228. package/src/workflows/workflow-resources.ts +150 -0
  229. package/src/workflows/workflow-settlement.ts +246 -0
  230. package/src/runs/shared/child-protocol.ts +0 -401
  231. package/src/runs/shared/pi-args.ts +0 -858
  232. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  233. package/src/runs/shared/turn-budget.ts +0 -98
  234. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -14,8 +14,24 @@ import {
14
14
  createCompletionBatcher,
15
15
  resolveCompletionBatchConfig,
16
16
  } from "./completion-batcher.ts";
17
- import { SUBAGENT_ASYNC_COMPLETE_EVENT, SUBAGENT_FOREGROUND_COMPLETE_EVENT, type ParallelHandoffReference, type ScheduleOrigin, type SubagentState } from "../../shared/types.ts";
17
+ import { SUBAGENT_ASYNC_COMPLETE_EVENT, SUBAGENT_FOREGROUND_COMPLETE_EVENT, type ChildWatchdogProgress, type ChildWatchdogWarningSummary, type ParallelHandoffReference, type ScheduleOrigin, type SubagentState } from "../../shared/types.ts";
18
+ import { safeTerminalText } from "../../shared/display-text.ts";
19
+ import { resolveSubagentResultStatus } from "../../intercom/result-intercom.ts";
18
20
  import { isUnexplainedProcessSignal } from "../shared/process-signal.ts";
21
+ import type { ResultDeliveryOwnership } from "./result-delivery-ownership.ts";
22
+
23
+ export interface SubagentNotifyChildOutput {
24
+ workflowKey?: string;
25
+ runId?: string;
26
+ agent?: string;
27
+ status: string;
28
+ savedOutputPath?: string;
29
+ preview: string;
30
+ previewTruncated?: boolean;
31
+ previewUnavailableReason?: string;
32
+ }
33
+
34
+ export type SubagentNotifyWatchdogBlocker = Pick<ChildWatchdogWarningSummary, "summary" | "addressed" | "stalemate"> & { agent: string };
19
35
 
20
36
  export interface SubagentNotifyDetails {
21
37
  agent: string;
@@ -24,11 +40,16 @@ export interface SubagentNotifyDetails {
24
40
  taskInfo?: string;
25
41
  resultPreview: string;
26
42
  durationMs?: number;
43
+ workflowRunId?: string;
44
+ childRuns?: Array<{ runId: string; workflowKey?: string; agent?: string; status?: string }>;
45
+ childOutputs?: SubagentNotifyChildOutput[];
46
+ reconciledFromDetachedChild?: string;
27
47
  sessionLabel?: string;
28
48
  sessionValue?: string;
29
49
  handoffPath?: string;
30
50
  /** Present when a durable schedule launched the run. */
31
51
  scheduleOrigin?: ScheduleOrigin;
52
+ watchdogBlockers?: SubagentNotifyWatchdogBlocker[];
32
53
  }
33
54
 
34
55
  export interface CompletionNotification {
@@ -40,21 +61,36 @@ export interface CompletionNotification {
40
61
  summary?: string;
41
62
  exitCode?: number;
42
63
  state?: string;
64
+ mode?: string;
65
+ runId?: string | null;
66
+ reconciledFromDetachedChild?: string;
43
67
  processSignal?: string | null;
44
68
  interrupted?: boolean;
45
69
  timedOut?: boolean;
46
70
  stopped?: boolean;
47
71
  turnBudgetExceeded?: boolean;
48
72
  results?: Array<{
73
+ runId?: string;
74
+ workflowKey?: string;
75
+ agent?: string;
49
76
  status?: string;
77
+ state?: string;
50
78
  success?: boolean;
79
+ output?: string;
80
+ structuredOutput?: unknown;
81
+ outputState?: "present" | "absent" | "unknown";
82
+ outputReference?: string | { path?: string };
83
+ artifactPaths?: { outputPath?: string };
84
+ detached?: boolean;
51
85
  exitCode?: number | null;
52
86
  processSignal?: string | null;
53
87
  interrupted?: boolean;
54
88
  timedOut?: boolean;
55
89
  stopped?: boolean;
56
90
  turnBudgetExceeded?: boolean;
91
+ watchdog?: ChildWatchdogProgress;
57
92
  }>;
93
+ watchdog?: ChildWatchdogProgress;
58
94
  timestamp?: number;
59
95
  durationMs?: number;
60
96
  cwd?: string;
@@ -82,6 +118,7 @@ export interface RegisterSubagentNotifyOptions {
82
118
  batchConfig?: CompletionBatchConfig;
83
119
  timers?: NotifyTimerApi;
84
120
  now?: () => number;
121
+ ownership?: Pick<ResultDeliveryOwnership, "owns">;
85
122
  }
86
123
 
87
124
  export interface CompletionNotifier {
@@ -89,13 +126,156 @@ export interface CompletionNotifier {
89
126
  dispose(): void;
90
127
  }
91
128
 
129
+ const CHILD_OUTPUT_PREVIEW_MAX_BYTES = 4 * 1024;
130
+ const CHILD_OUTPUT_PREVIEW_COUNT = 8;
131
+ const PREVIEW_TRUNCATION_MARKER = "...[preview truncated]";
132
+ type CompletionChild = NonNullable<CompletionNotification["results"]>[number];
133
+
134
+ function truncateUtf8Head(value: string, maxBytes: number): { text: string; truncated: boolean } {
135
+ const bytes = Buffer.from(value, "utf8");
136
+ if (bytes.length <= maxBytes) return { text: value, truncated: false };
137
+ const markerBytes = Buffer.byteLength(PREVIEW_TRUNCATION_MARKER, "utf8");
138
+ const contentBytes = Math.max(0, maxBytes - markerBytes);
139
+ let end = contentBytes;
140
+ while (end > 0 && (bytes[end]! & 0xc0) === 0x80) end -= 1;
141
+ return {
142
+ text: `${bytes.subarray(0, end).toString("utf8")}${PREVIEW_TRUNCATION_MARKER}`,
143
+ truncated: true,
144
+ };
145
+ }
146
+
147
+ function boundedSafeText(value: string, maxBytes = 1_024): string {
148
+ return truncateUtf8Head(safeTerminalText(value).replace(/\n/g, "\\n"), maxBytes).text;
149
+ }
150
+
151
+ function outputPathFromReference(value: CompletionChild["outputReference"]): string | undefined {
152
+ if (typeof value === "string" && value.trim()) return value.trim();
153
+ if (value && typeof value === "object" && typeof value.path === "string" && value.path.trim()) return value.path.trim();
154
+ return undefined;
155
+ }
156
+
157
+ function childSavedOutputPath(child: CompletionChild): string | undefined {
158
+ return outputPathFromReference(child.outputReference);
159
+ }
160
+
161
+ function childStatus(child: CompletionChild, workflowState?: string): string {
162
+ const knownStatus = child.status === "complete"
163
+ ? "completed"
164
+ : child.status === "completed" || child.status === "failed" || child.status === "paused" || child.status === "stopped" || child.status === "detached"
165
+ ? child.status
166
+ : undefined;
167
+ if (knownStatus) return knownStatus;
168
+ return resolveSubagentResultStatus({
169
+ success: child.success,
170
+ state: child.state ?? (child.success === undefined ? workflowState : undefined),
171
+ interrupted: child.interrupted,
172
+ detached: child.detached,
173
+ processSignal: child.processSignal,
174
+ timedOut: child.timedOut,
175
+ stopped: child.stopped,
176
+ turnBudgetExceeded: child.turnBudgetExceeded,
177
+ exitCode: typeof child.exitCode === "number" ? child.exitCode : undefined,
178
+ });
179
+ }
180
+
181
+ function structuredOutputText(value: unknown): string | undefined {
182
+ if (value === undefined) return undefined;
183
+ try {
184
+ const serialized = JSON.stringify(value, null, 2);
185
+ return typeof serialized === "string" ? serialized : undefined;
186
+ } catch {
187
+ return undefined;
188
+ }
189
+ }
190
+
191
+ function childInlinePreview(child: CompletionChild): { preview?: string; truncated?: boolean; unavailableReason?: string } {
192
+ const output = typeof child.output === "string" ? child.output : "";
193
+ const outputReference = childSavedOutputPath(child);
194
+ const referenceOnly = Boolean(outputReference && output.trim().startsWith("Output saved to:"));
195
+ const raw = child.outputState === "absent" || referenceOnly ? structuredOutputText(child.structuredOutput) : output || structuredOutputText(child.structuredOutput);
196
+ if (!raw?.trim()) {
197
+ return { unavailableReason: referenceOnly ? "saved output is file-only" : "no safe inline output" };
198
+ }
199
+ const safe = safeTerminalText(raw);
200
+ if (!safe.trim()) return { unavailableReason: "no safe inline output" };
201
+ const bounded = truncateUtf8Head(safe, CHILD_OUTPUT_PREVIEW_MAX_BYTES);
202
+ return { preview: bounded.text, ...(bounded.truncated ? { truncated: true } : {}) };
203
+ }
204
+
205
+ function formatChildOutputBlock(children: SubagentNotifyChildOutput[] | undefined): string | undefined {
206
+ if (!children?.length) return undefined;
207
+ const lines = ["Child outputs:"];
208
+ for (let index = 0; index < children.length; index++) {
209
+ const child = children[index]!;
210
+ const key = child.workflowKey ? boundedSafeText(child.workflowKey) : "unavailable";
211
+ const runId = child.runId ? boundedSafeText(child.runId) : "unavailable";
212
+ const status = boundedSafeText(child.status) || "unavailable";
213
+ lines.push(`- key=${key} run=${runId} status=${status}`);
214
+ lines.push(` Saved output: ${child.savedOutputPath ? boundedSafeText(child.savedOutputPath) : "unavailable"}`);
215
+ if (index >= CHILD_OUTPUT_PREVIEW_COUNT) {
216
+ lines.push(" Preview: unavailable (notice preview budget exceeded)");
217
+ continue;
218
+ }
219
+ if (!child.preview) {
220
+ lines.push(` Preview: unavailable (${child.previewUnavailableReason ?? "no safe inline output"})`);
221
+ continue;
222
+ }
223
+ lines.push(" Preview:");
224
+ for (const line of child.preview.split("\n")) lines.push(` | ${line}`);
225
+ }
226
+ if (children.length > CHILD_OUTPUT_PREVIEW_COUNT) {
227
+ lines.push(`- ${children.length - CHILD_OUTPUT_PREVIEW_COUNT} additional child preview(s) omitted by notice budget; child run metadata is retained below.`);
228
+ }
229
+ return lines.join("\n");
230
+ }
231
+
232
+ function formatResultPreview(details: SubagentNotifyDetails): string {
233
+ const summary = details.resultPreview.trim() ? details.resultPreview : "(no output)";
234
+ const childOutputs = formatChildOutputBlock(details.childOutputs);
235
+ return childOutputs ? `${summary}\n\n${childOutputs}` : summary;
236
+ }
237
+
92
238
  function formatSessionLine(details: SubagentNotifyDetails): string | undefined {
93
239
  if (!details.sessionValue) return undefined;
94
240
  return details.sessionLabel ? `${details.sessionLabel}: ${details.sessionValue}` : details.sessionValue;
95
241
  }
96
242
 
243
+ function formatChildRun(child: { runId: string; workflowKey?: string; agent?: string; status?: string }): string {
244
+ const label = child.workflowKey ?? child.agent;
245
+ const status = child.status ? ` (${child.status})` : "";
246
+ return `${label ? `${label}=` : ""}${child.runId}${status}`;
247
+ }
248
+
249
+ function formatCorrelationLines(details: SubagentNotifyDetails): string[] {
250
+ return [
251
+ details.workflowRunId ? `Workflow run: ${details.workflowRunId}` : undefined,
252
+ details.childRuns?.length ? `Child runs: ${details.childRuns.map(formatChildRun).join(", ")}` : undefined,
253
+ details.reconciledFromDetachedChild ? `Reconciled detached child: ${details.reconciledFromDetachedChild}` : undefined,
254
+ ].filter((line): line is string => line !== undefined);
255
+ }
256
+
257
+ const WATCHDOG_BLOCKERS_HEADING = "Watchdog blockers:";
258
+
259
+ function formatWatchdogBlockerLines(details: SubagentNotifyDetails): string[] {
260
+ if (!details.watchdogBlockers?.length) return [];
261
+ return [WATCHDOG_BLOCKERS_HEADING, ...details.watchdogBlockers.map((blocker) => `- ${blocker.agent}: ${blocker.summary} (${blocker.stalemate ? "stalemate" : blocker.addressed ? "addressed" : "unaddressed"})`)];
262
+ }
263
+
264
+ // A stalemate blocker parses back as unaddressed; acceptance treats both as unresolved.
265
+ function parseWatchdogBlockerLines(lines: string[]): SubagentNotifyWatchdogBlocker[] {
266
+ const blockers: SubagentNotifyWatchdogBlocker[] = [];
267
+ for (const line of lines) {
268
+ const match = line.match(/^- (.+?): (.+) \((addressed|unaddressed|stalemate)\)$/);
269
+ if (!match) break;
270
+ blockers.push({ agent: match[1]!, summary: match[2]!, addressed: match[3] === "addressed", stalemate: match[3] === "stalemate" });
271
+ }
272
+ return blockers;
273
+ }
274
+
97
275
  export function formatSingleCompletion(details: SubagentNotifyDetails): string {
98
276
  const sessionLine = formatSessionLine(details);
277
+ const correlationLines = formatCorrelationLines(details);
278
+ const watchdogLines = formatWatchdogBlockerLines(details);
99
279
  const taskKind = details.source === "foreground" ? "Detached foreground task" : "Background task";
100
280
  const scheduleLine = details.scheduleOrigin
101
281
  ? `Scheduled run from **${details.scheduleOrigin.name ?? details.scheduleOrigin.id}** (schedule ${details.scheduleOrigin.id}).`
@@ -105,9 +285,12 @@ export function formatSingleCompletion(details: SubagentNotifyDetails): string {
105
285
  "",
106
286
  scheduleLine,
107
287
  scheduleLine ? "" : undefined,
108
- details.resultPreview.trim() ? details.resultPreview : "(no output)",
288
+ formatResultPreview(details),
289
+ ...(watchdogLines.length ? ["", ...watchdogLines] : []),
109
290
  details.handoffPath ? "" : undefined,
110
291
  details.handoffPath ? `Parallel handoff: ${details.handoffPath}` : undefined,
292
+ correlationLines.length && !details.handoffPath ? "" : undefined,
293
+ ...correlationLines,
111
294
  sessionLine ? "" : undefined,
112
295
  sessionLine,
113
296
  ]
@@ -139,11 +322,29 @@ export function parseSubagentNotifyContent(content: string): SubagentNotifyDetai
139
322
  }
140
323
  const sessionLine = sessionIndex >= 0 ? body[sessionIndex] : undefined;
141
324
  const handoffIndex = body.findIndex((line) => line.startsWith("Parallel handoff: "));
142
- const metadataIndexes = [sessionIndex, handoffIndex].filter((index) => index >= 0);
325
+ const workflowRunIndex = body.findIndex((line) => line.startsWith("Workflow run: "));
326
+ const childRunsIndex = body.findIndex((line) => line.startsWith("Child runs: "));
327
+ const reconciledIndex = body.findIndex((line) => line.startsWith("Reconciled detached child: "));
328
+ const watchdogIndex = body.findIndex((line) => line === WATCHDOG_BLOCKERS_HEADING);
329
+ const watchdogBlockers = watchdogIndex >= 0 ? parseWatchdogBlockerLines(body.slice(watchdogIndex + 1)) : [];
330
+ const metadataIndexes = [sessionIndex, handoffIndex, workflowRunIndex, childRunsIndex, reconciledIndex, watchdogIndex].filter((index) => index >= 0);
143
331
  const firstMetadataIndex = metadataIndexes.length ? Math.min(...metadataIndexes) : body.length;
144
332
  const resultEnd = firstMetadataIndex > 0 && body[firstMetadataIndex - 1]?.trim() === "" ? firstMetadataIndex - 1 : firstMetadataIndex;
145
333
  const resultPreview = body.slice(0, resultEnd).join("\n").trim() || "(no output)";
146
334
  const handoffPath = handoffIndex >= 0 ? body[handoffIndex]!.slice("Parallel handoff: ".length).trim() : undefined;
335
+ const workflowRunId = workflowRunIndex >= 0 ? body[workflowRunIndex]!.slice("Workflow run: ".length).trim() : undefined;
336
+ const childRuns = childRunsIndex >= 0
337
+ ? body[childRunsIndex]!.slice("Child runs: ".length).split(", ").map((part) => {
338
+ const trimmed = part.trim();
339
+ const statusMatch = trimmed.match(/^(.*?)(?: \(([^)]*)\))?$/);
340
+ const raw = statusMatch?.[1] ?? trimmed;
341
+ const separator = raw.indexOf("=");
342
+ return separator >= 0
343
+ ? { workflowKey: raw.slice(0, separator), runId: raw.slice(separator + 1), ...(statusMatch?.[2] ? { status: statusMatch[2] } : {}) }
344
+ : { runId: raw, ...(statusMatch?.[2] ? { status: statusMatch[2] } : {}) };
345
+ }).filter((child) => child.runId)
346
+ : undefined;
347
+ const reconciledFromDetachedChild = reconciledIndex >= 0 ? body[reconciledIndex]!.slice("Reconciled detached child: ".length).trim() : undefined;
147
348
  let sessionLabel: string | undefined;
148
349
  let sessionValue: string | undefined;
149
350
  if (sessionLine) {
@@ -159,6 +360,10 @@ export function parseSubagentNotifyContent(content: string): SubagentNotifyDetai
159
360
  ...(parsedScheduleOrigin ? { scheduleOrigin: parsedScheduleOrigin } : {}),
160
361
  resultPreview,
161
362
  ...(handoffPath ? { handoffPath } : {}),
363
+ ...(workflowRunId ? { workflowRunId } : {}),
364
+ ...(childRuns?.length ? { childRuns } : {}),
365
+ ...(reconciledFromDetachedChild ? { reconciledFromDetachedChild } : {}),
366
+ ...(watchdogBlockers.length ? { watchdogBlockers } : {}),
162
367
  ...(sessionLabel && sessionValue ? { sessionLabel, sessionValue } : {}),
163
368
  };
164
369
  }
@@ -171,8 +376,10 @@ export function formatGroupedCompletion(details: SubagentNotifyDetails[]): strin
171
376
  if (!detail) continue;
172
377
  const sessionLine = formatSessionLine(detail);
173
378
  blocks.push(`${index + 1}. ${detail.agent}${detail.taskInfo ?? ""}${detail.scheduleOrigin ? ` — scheduled run from ${detail.scheduleOrigin.name ?? detail.scheduleOrigin.id} (schedule ${detail.scheduleOrigin.id})` : ""}`);
174
- blocks.push(detail.resultPreview.trim() ? detail.resultPreview : "(no output)");
379
+ blocks.push(formatResultPreview(detail));
380
+ blocks.push(...formatWatchdogBlockerLines(detail));
175
381
  if (detail.handoffPath) blocks.push(`Parallel handoff: ${detail.handoffPath}`);
382
+ blocks.push(...formatCorrelationLines(detail));
176
383
  if (sessionLine) blocks.push(sessionLine);
177
384
  blocks.push("");
178
385
  }
@@ -182,6 +389,8 @@ export function formatGroupedCompletion(details: SubagentNotifyDetails[]): strin
182
389
  interface PendingCompletion {
183
390
  key: string;
184
391
  details: SubagentNotifyDetails;
392
+ sessionId: string;
393
+ completionOwnerId: unknown;
185
394
  triggerTurn: boolean;
186
395
  resolve(accepted: boolean): void;
187
396
  }
@@ -225,6 +434,7 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
225
434
  const paused = !stopped && !result.success && (
226
435
  result.exitCode === 0
227
436
  || result.state === "paused"
437
+ || result.interrupted === true
228
438
  || summary.startsWith("Paused after interrupt.")
229
439
  );
230
440
  const status = stopped ? "stopped" : paused ? "paused" : result.success ? "completed" : "failed";
@@ -237,6 +447,59 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
237
447
  ? result.parallelHandoff as { path?: unknown }
238
448
  : undefined;
239
449
  const handoffPath = typeof parallelHandoff?.path === "string" ? parallelHandoff.path : undefined;
450
+ const rawRunId = typeof result.runId === "string" ? result.runId : typeof result.id === "string" ? result.id : undefined;
451
+ const workflowRunId = (result.mode === "workflow" || agent === "workflow") && rawRunId ? rawRunId : undefined;
452
+ const directChild = !workflowRunId && result.results?.length === 1 ? result.results[0]! : undefined;
453
+ const directStructuredPreview = directChild
454
+ ? childInlinePreview(directChild).preview
455
+ : undefined;
456
+ const directSummary = summary.trim();
457
+ const directAgent = typeof directChild?.agent === "string" ? directChild.agent : agent;
458
+ const directNoOutputSummary = directChild && (!directSummary
459
+ || directSummary === "(no output)"
460
+ || (directAgent && directSummary === `${directAgent}:\n(no output)`));
461
+ const resultPreview = directStructuredPreview && directNoOutputSummary
462
+ ? `Structured output:\n${directStructuredPreview}`
463
+ : summary;
464
+ const childRuns = result.results?.flatMap((child) => {
465
+ const runId = typeof child.runId === "string" && child.runId.trim() ? child.runId.trim() : undefined;
466
+ const workflowKey = typeof child.workflowKey === "string" && child.workflowKey.trim() ? child.workflowKey.trim() : undefined;
467
+ if (!runId && (!workflowRunId || !workflowKey)) return [];
468
+ return [{
469
+ runId: runId ?? "unavailable",
470
+ ...(workflowKey ? { workflowKey } : {}),
471
+ ...(typeof child.agent === "string" ? { agent: child.agent } : {}),
472
+ status: childStatus(child, workflowRunId ? result.state : undefined),
473
+ }];
474
+ }) ?? [];
475
+ const childOutputs = workflowRunId && result.results?.length
476
+ ? result.results.map((child) => {
477
+ const inline = childInlinePreview(child);
478
+ const workflowKey = typeof child.workflowKey === "string" && child.workflowKey.trim() ? child.workflowKey.trim() : undefined;
479
+ const runId = typeof child.runId === "string" && child.runId.trim() ? child.runId.trim() : undefined;
480
+ const savedOutputPath = childSavedOutputPath(child);
481
+ return {
482
+ ...(workflowKey ? { workflowKey } : {}),
483
+ ...(runId ? { runId } : {}),
484
+ ...(typeof child.agent === "string" ? { agent: child.agent } : {}),
485
+ status: childStatus(child, result.state),
486
+ ...(savedOutputPath ? { savedOutputPath } : {}),
487
+ ...(inline.preview ? { preview: inline.preview } : { preview: "" }),
488
+ ...(inline.truncated ? { previewTruncated: true } : {}),
489
+ ...(inline.unavailableReason ? { previewUnavailableReason: inline.unavailableReason } : {}),
490
+ };
491
+ })
492
+ : undefined;
493
+ const reconciledFromDetachedChild = typeof result.reconciledFromDetachedChild === "string" ? result.reconciledFromDetachedChild : undefined;
494
+ const watchdogBlockers: SubagentNotifyWatchdogBlocker[] = [];
495
+ const collectWatchdogBlockers = (owner: string, progress: ChildWatchdogProgress | undefined) => {
496
+ for (const warning of progress?.warnings ?? []) {
497
+ if (warning.severity !== "blocker") continue;
498
+ watchdogBlockers.push({ agent: owner, summary: warning.summary, addressed: warning.addressed, stalemate: warning.stalemate });
499
+ }
500
+ };
501
+ collectWatchdogBlockers(agent, result.watchdog);
502
+ for (const child of result.results ?? []) collectWatchdogBlockers(typeof child.agent === "string" ? child.agent : agent, child.watchdog);
240
503
  const session =
241
504
  result.shareUrl
242
505
  ? { label: "Session", value: result.shareUrl }
@@ -255,9 +518,14 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
255
518
  ...(scheduleOrigin ? { scheduleOrigin } : {}),
256
519
  ...(result.source ? { source: result.source } : {}),
257
520
  ...(taskInfo ? { taskInfo } : {}),
258
- resultPreview: summary,
521
+ resultPreview,
259
522
  ...(typeof result.durationMs === "number" ? { durationMs: result.durationMs } : {}),
260
523
  ...(handoffPath ? { handoffPath } : {}),
524
+ ...(workflowRunId ? { workflowRunId } : {}),
525
+ ...(childRuns.length ? { childRuns } : {}),
526
+ ...(childOutputs?.length ? { childOutputs } : {}),
527
+ ...(reconciledFromDetachedChild ? { reconciledFromDetachedChild } : {}),
528
+ ...(watchdogBlockers.length ? { watchdogBlockers } : {}),
261
529
  ...(session ? { sessionLabel: session.label, sessionValue: session.value } : {}),
262
530
  };
263
531
  }
@@ -274,6 +542,10 @@ export default function registerSubagentNotify(
274
542
  const batchConfig = resolveCompletionBatchConfig(options.batchConfig);
275
543
  const batchers = new Map<string, CompletionBatcher<PendingCompletion>>();
276
544
  let disposed = false;
545
+ const ownsResult = options.ownership?.owns
546
+ ?? ((sessionId: string, completionOwnerId: unknown) => sessionId === state.currentSessionId
547
+ && typeof completionOwnerId === "string"
548
+ && completionOwnerId === state.completionOwnerId);
277
549
 
278
550
  const settle = (items: PendingCompletion[], accepted: boolean) => {
279
551
  for (const item of items) {
@@ -282,7 +554,18 @@ export default function registerSubagentNotify(
282
554
  item.resolve(accepted);
283
555
  }
284
556
  };
285
- const emit = (items: PendingCompletion[]) => settle(items, sendCompletion(pi, items));
557
+ const emit = (items: PendingCompletion[]) => {
558
+ const accepted: PendingCompletion[] = [];
559
+ const rejected: PendingCompletion[] = [];
560
+ for (const item of items) {
561
+ const owned = item.details.source === "foreground"
562
+ ? item.sessionId === state.currentSessionId
563
+ : ownsResult(item.sessionId, item.completionOwnerId);
564
+ (owned ? accepted : rejected).push(item);
565
+ }
566
+ settle(rejected, false);
567
+ settle(accepted, sendCompletion(pi, accepted));
568
+ };
286
569
  const getBatcher = (result: CompletionNotification) => {
287
570
  const key = completionBatchKey(result);
288
571
  let batcher = batchers.get(key);
@@ -299,8 +582,10 @@ export default function registerSubagentNotify(
299
582
  };
300
583
 
301
584
  const deliver = (result: CompletionNotification): Promise<boolean> => {
302
- if (disposed || typeof result.sessionId !== "string" || result.sessionId !== state.currentSessionId) return Promise.resolve(false);
303
- if (result.source !== "foreground" && (!state.completionOwnerId || result.completionOwnerId !== state.completionOwnerId)) return Promise.resolve(false);
585
+ if (disposed || typeof result.sessionId !== "string") return Promise.resolve(false);
586
+ if (result.source === "foreground") {
587
+ if (result.sessionId !== state.currentSessionId) return Promise.resolve(false);
588
+ } else if (!ownsResult(result.sessionId, result.completionOwnerId)) return Promise.resolve(false);
304
589
  if (result.intercomDelivered === true) return Promise.resolve(true);
305
590
  const key = buildCompletionKey(result, "notify");
306
591
  const seenAt = seen.get(key);
@@ -315,6 +600,8 @@ export default function registerSubagentNotify(
315
600
  const item: PendingCompletion = {
316
601
  key,
317
602
  details,
603
+ sessionId: result.sessionId,
604
+ completionOwnerId: result.completionOwnerId,
318
605
  triggerTurn: result.triggerTurn !== false,
319
606
  resolve,
320
607
  };
@@ -115,6 +115,22 @@ export function writeProcessTerminalCandidate(asyncDir: string, candidate: Proce
115
115
  writePrivateAtomicJson(processTerminalCandidatePath(asyncDir), candidate);
116
116
  }
117
117
 
118
+ /** Establish ownership before authorizing a runner to start any child session. */
119
+ export function initializeProcessTerminal(asyncDir: string, runId: string, runnerProcessInstanceId: string): void {
120
+ writeProcessTerminalCandidate(asyncDir, {
121
+ version: 1,
122
+ runId,
123
+ runnerProcessInstanceId,
124
+ writers: {},
125
+ });
126
+ writeAtomicJson(processTerminalPath(asyncDir), {
127
+ version: 1,
128
+ state: "pending",
129
+ runId,
130
+ runnerProcessInstanceId,
131
+ });
132
+ }
133
+
118
134
  export function markProcessTerminalCandidateLeaseRelease(asyncDir: string, token: string, acknowledged: boolean): void {
119
135
  const candidate = readProcessTerminalCandidate(asyncDir);
120
136
  if (!candidate || candidate.revivalLeaseToken !== token) return;
@@ -0,0 +1,45 @@
1
+ import type { SubagentState } from "../../shared/types.ts";
2
+
3
+ const MAX_CLAIMED_PREDECESSOR_SESSIONS = 8;
4
+
5
+ type ResultDeliveryState = Pick<SubagentState, "currentSessionId" | "completionOwnerId">;
6
+
7
+ export interface ResultDeliveryOwnership {
8
+ owns(sessionId: string, completionOwnerId: unknown): boolean;
9
+ claimedSessionIds(): readonly string[];
10
+ claimPredecessor(previousSessionFile: string | undefined, previousRuntimeSessionId: string | null): boolean;
11
+ clear(): void;
12
+ }
13
+
14
+ export function createResultDeliveryOwnership(state: ResultDeliveryState): ResultDeliveryOwnership {
15
+ const claimed = new Map<string, string>();
16
+
17
+ const currentOwner = (): string | undefined => typeof state.completionOwnerId === "string" && state.completionOwnerId
18
+ ? state.completionOwnerId
19
+ : undefined;
20
+
21
+ return {
22
+ owns(sessionId, completionOwnerId) {
23
+ const owner = currentOwner();
24
+ if (!owner || completionOwnerId !== owner) return false;
25
+ return sessionId === state.currentSessionId || claimed.get(sessionId) === owner;
26
+ },
27
+ claimedSessionIds() {
28
+ const owner = currentOwner();
29
+ if (!owner) return [];
30
+ return [...claimed].flatMap(([sessionId, claimedOwner]) => claimedOwner === owner ? [sessionId] : []);
31
+ },
32
+ claimPredecessor(previousSessionFile, previousRuntimeSessionId) {
33
+ const owner = currentOwner();
34
+ if (!owner || !previousSessionFile || !previousRuntimeSessionId) return false;
35
+ if (previousSessionFile !== previousRuntimeSessionId || state.currentSessionId !== previousRuntimeSessionId) return false;
36
+ claimed.delete(previousRuntimeSessionId);
37
+ claimed.set(previousRuntimeSessionId, owner);
38
+ while (claimed.size > MAX_CLAIMED_PREDECESSOR_SESSIONS) claimed.delete(claimed.keys().next().value!);
39
+ return true;
40
+ },
41
+ clear() {
42
+ claimed.clear();
43
+ },
44
+ };
45
+ }
@@ -40,6 +40,11 @@ function nonEmptyString(value: unknown): string | undefined {
40
40
  return typeof value === "string" && value.length > 0 ? value : undefined;
41
41
  }
42
42
 
43
+ /** A legacy alias can be valid metadata while still being unaddressable on the current filesystem. */
44
+ function isUnaddressableResultCandidate(error: unknown): boolean {
45
+ return (error as NodeJS.ErrnoException)?.code === "ENAMETOOLONG";
46
+ }
47
+
43
48
  export function resultFileName(runId: string): string {
44
49
  return `${runId}${JSON_EXTENSION}`;
45
50
  }
@@ -227,7 +232,7 @@ function existingResultFile(resultPath: string): boolean {
227
232
  try {
228
233
  return fs.statSync(resultPath).isFile();
229
234
  } catch (error) {
230
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Failed to inspect async result payload '${resultPath}':`, error);
235
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" && !isUnaddressableResultCandidate(error)) console.error(`Failed to inspect async result payload '${resultPath}':`, error);
231
236
  return false;
232
237
  }
233
238
  }
@@ -241,7 +246,7 @@ function pendingResultPayloadMatches(filePath: string, sessionId: string, runId:
241
246
  const data = JSON.parse(fs.readFileSync(filePath, "utf-8")) as Record<string, unknown>;
242
247
  return (nonEmptyString(data.runId) ?? nonEmptyString(data.id)) === runId && nonEmptyString(data.sessionId) === sessionId;
243
248
  } catch (error) {
244
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Ignoring invalid pending async result '${filePath}':`, error);
249
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" && !isUnaddressableResultCandidate(error)) console.error(`Ignoring invalid pending async result '${filePath}':`, error);
245
250
  return false;
246
251
  }
247
252
  }
@@ -263,11 +268,11 @@ export function promotePendingResultFile(resultsDir: string, sessionId: string,
263
268
  return existingResultFile(resultPath) ? "promoted" : "pending";
264
269
  } catch (error) {
265
270
  const code = (error as NodeJS.ErrnoException).code;
266
- if (code === "ENOENT" || code === "EEXIST" || code === "EPERM" || code === "EACCES") {
271
+ if (code === "ENOENT" || code === "EEXIST" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) {
267
272
  const pendingExists = existingResultFile(pendingPath);
268
273
  const resultExists = existingResultFile(resultPath);
269
274
  if (pendingExists) {
270
- if (!resultExists && options.logFailure !== false) console.error(`Failed to promote pending async result '${pendingPath}' to '${resultPath}':`, error);
275
+ if (!resultExists && options.logFailure !== false && !isUnaddressableResultCandidate(error)) console.error(`Failed to promote pending async result '${pendingPath}' to '${resultPath}':`, error);
271
276
  return "pending";
272
277
  }
273
278
  if (resultExists) return "promoted";
@@ -318,7 +323,7 @@ function readResultIndexForSessionRun(resultsDir: string, sessionId: string, run
318
323
  } catch (error) {
319
324
  const code = (error as NodeJS.ErrnoException).code;
320
325
  if (code === "EPERM" || code === "EACCES") throw error;
321
- if (code !== "ENOENT" && code !== "ENOTDIR") {
326
+ if (code !== "ENOENT" && code !== "ENOTDIR" && !isUnaddressableResultCandidate(error)) {
322
327
  console.error(`Ignoring invalid async result index for '${runId}':`, error);
323
328
  }
324
329
  }
@@ -338,7 +343,8 @@ export function resultPayloadPathForMissionObserverRun(resultsDir: string, runId
338
343
  if (!entry || entry.runId !== runId) return undefined;
339
344
  return resultPayloadLocationFromIndex(resultsDir, entry)?.path;
340
345
  } catch (error) {
341
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Ignoring invalid async result observer index for '${runId}':`, error);
346
+ const code = (error as NodeJS.ErrnoException).code;
347
+ if (code !== "ENOENT" && code !== "ENOTDIR" && !isUnaddressableResultCandidate(error)) console.error(`Ignoring invalid async result observer index for '${runId}':`, error);
342
348
  return undefined;
343
349
  }
344
350
  }
@@ -356,9 +362,12 @@ export function resultPayloadPathForIndexedRun(resultsDir: string, runId: string
356
362
  fs.rmSync(entryPath, { force: true });
357
363
  } catch (error) {
358
364
  const code = (error as NodeJS.ErrnoException).code;
365
+ if (isUnaddressableResultCandidate(error)) return undefined;
359
366
  if (code !== "ENOENT" && code !== "ENOTDIR") {
360
367
  console.error(`Ignoring invalid async result run index '${entryPath}':`, error);
361
- try { fs.rmSync(entryPath, { force: true }); } catch {}
368
+ try { fs.rmSync(entryPath, { force: true }); } catch {
369
+ // Invalid optional run-index cleanup is best-effort.
370
+ }
362
371
  }
363
372
  }
364
373
  return undefined;
@@ -378,7 +387,7 @@ function listIndexFiles(dir: string): string[] {
378
387
  .map((entry) => path.join(dir, entry.name));
379
388
  } catch (error) {
380
389
  const code = (error as NodeJS.ErrnoException).code;
381
- if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES") return [];
390
+ if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) return [];
382
391
  throw error;
383
392
  }
384
393
  return files;
@@ -396,7 +405,7 @@ function resultFilesFromIndexDir(resultsDir: string, dir: string, includePending
396
405
  const resultFile = indexedResultFile(resultsDir, entry, includePending);
397
406
  if (resultFile) candidates.add(resultFile);
398
407
  } catch (error) {
399
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Ignoring invalid async result index '${entryPath}':`, error);
408
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" && !isUnaddressableResultCandidate(error)) console.error(`Ignoring invalid async result index '${entryPath}':`, error);
400
409
  }
401
410
  }
402
411
  return [...candidates];
@@ -418,7 +427,7 @@ function pendingResultFilesForSession(resultsDir: string, sessionId: string): st
418
427
  entries = fs.readdirSync(dir, { withFileTypes: true });
419
428
  } catch (error) {
420
429
  const code = (error as NodeJS.ErrnoException).code;
421
- if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES") continue;
430
+ if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) continue;
422
431
  throw error;
423
432
  }
424
433
  for (const entry of entries) {
@@ -429,7 +438,7 @@ function pendingResultFilesForSession(resultsDir: string, sessionId: string): st
429
438
  const runId = nonEmptyString(data.runId) ?? nonEmptyString(data.id);
430
439
  if (runId && nonEmptyString(data.sessionId) === sessionId) files.add(resultFileName(runId));
431
440
  } catch (error) {
432
- if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Ignoring invalid pending async result '${pendingPath}':`, error);
441
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" && !isUnaddressableResultCandidate(error)) console.error(`Ignoring invalid pending async result '${pendingPath}':`, error);
433
442
  }
434
443
  }
435
444
  }
@@ -471,14 +480,16 @@ export function cleanupResultIndexes(resultsDir: string, now = Date.now(), maxAg
471
480
  entries = fs.readdirSync(dir, { withFileTypes: true });
472
481
  } catch (error) {
473
482
  const code = (error as NodeJS.ErrnoException).code;
474
- if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES") return;
483
+ if (code === "ENOENT" || code === "ENOTDIR" || code === "EPERM" || code === "EACCES" || isUnaddressableResultCandidate(error)) return;
475
484
  throw error;
476
485
  }
477
486
  for (const entry of entries) {
478
487
  const fullPath = path.join(dir, entry.name);
479
488
  if (entry.isDirectory()) {
480
489
  visit(fullPath);
481
- try { fs.rmdirSync(fullPath); } catch {}
490
+ try { fs.rmdirSync(fullPath); } catch {
491
+ // Non-empty or concurrently removed index directories are left in place.
492
+ }
482
493
  continue;
483
494
  }
484
495
  if (!entry.isFile() || !entry.name.endsWith(".json")) continue;
@@ -492,11 +503,14 @@ export function cleanupResultIndexes(resultsDir: string, now = Date.now(), maxAg
492
503
  removed += 1;
493
504
  }
494
505
  } catch (error) {
506
+ if (isUnaddressableResultCandidate(error)) continue;
495
507
  if ((error as NodeJS.ErrnoException).code !== "ENOENT") console.error(`Ignoring invalid async result index '${fullPath}':`, error);
496
508
  try {
497
509
  fs.rmSync(fullPath, { force: true });
498
510
  removed += 1;
499
- } catch {}
511
+ } catch {
512
+ // Invalid optional index cleanup is best-effort.
513
+ }
500
514
  }
501
515
  }
502
516
  };