@xzzpig/pi-subagents 0.14.0 → 0.15.1

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 (206) hide show
  1. package/CHANGELOG.md +239 -0
  2. package/README.md +7 -6
  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 +55 -136
  7. package/docs/configuration.md +92 -14
  8. package/docs/extension-api.md +132 -74
  9. package/docs/fork-extensions.md +184 -0
  10. package/docs/missions.md +10 -2
  11. package/docs/models.md +11 -22
  12. package/docs/observability.md +63 -11
  13. package/docs/standalone-background.md +59 -0
  14. package/docs/tool-reference.md +42 -23
  15. package/docs/watchdog.md +39 -10
  16. package/docs/workflows.md +58 -19
  17. package/index.ts +5 -2
  18. package/inspector-runner.mjs +2 -2
  19. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +13 -3
  20. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +18 -6
  21. package/node_modules/@xzzpig/pi-components/src/transcript.ts +26 -6
  22. package/package.json +9 -4
  23. package/prompts/parallel-review.md +1 -1
  24. package/runner-peer-loader.mjs +24 -0
  25. package/runner-peer-preload.mjs +36 -0
  26. package/skills/pi-subagents/SKILL.md +34 -22
  27. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  28. package/skills/pi-subagents/references/execution-controls.md +27 -8
  29. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  30. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  31. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  32. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  33. package/src/agents/advertised-agent-prompt.ts +94 -0
  34. package/src/agents/agent-eject.ts +339 -0
  35. package/src/agents/agent-management.ts +79 -387
  36. package/src/agents/agent-serializer.ts +6 -3
  37. package/src/agents/agents.ts +198 -72
  38. package/src/agents/builtin-names.ts +1 -0
  39. package/src/agents/chain-serializer.ts +5 -0
  40. package/src/agents/runtime-agent-registry.ts +7 -6
  41. package/src/api/agent-management.ts +2 -2
  42. package/src/api/delegation.ts +4 -0
  43. package/src/api/preflight.ts +131 -86
  44. package/src/api/required-child-extensions.ts +6 -0
  45. package/src/api/shared-types.ts +3 -1
  46. package/src/api/workflow-resources.ts +6 -0
  47. package/src/extension/config.ts +14 -37
  48. package/src/extension/fanout-child.ts +68 -5
  49. package/src/extension/herdr-pi-bridge.ts +164 -0
  50. package/src/extension/index.ts +141 -51
  51. package/src/extension/public-execution.ts +7 -6
  52. package/src/extension/rpc.ts +8 -21
  53. package/src/extension/schemas.ts +86 -84
  54. package/src/extension/tool-description.ts +32 -79
  55. package/src/inspectors/actions.ts +148 -0
  56. package/src/inspectors/ghostty/actions.ts +74 -0
  57. package/src/inspectors/ghostty/plugin.ts +17 -0
  58. package/src/inspectors/herdr/actions.ts +99 -179
  59. package/src/inspectors/herdr/plugin.ts +20 -0
  60. package/src/inspectors/herdr/project-panes.ts +4 -1
  61. package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
  62. package/src/inspectors/plugins.ts +8 -0
  63. package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
  64. package/src/inspectors/types.ts +51 -0
  65. package/src/integrations/pi-web-session-liveness.ts +73 -0
  66. package/src/intercom/intercom-bridge.ts +50 -8
  67. package/src/intercom/native-supervisor-channel.ts +142 -115
  68. package/src/intercom/supervisor-ui.ts +3 -2
  69. package/src/missions/workflow-state.ts +37 -16
  70. package/src/policy/authority.ts +4 -0
  71. package/src/profiles/profiles.ts +12 -6
  72. package/src/runs/background/active-async-capacity.ts +22 -18
  73. package/src/runs/background/active-run-index.ts +17 -1
  74. package/src/runs/background/async-execution.ts +359 -176
  75. package/src/runs/background/async-job-tracker.ts +41 -7
  76. package/src/runs/background/async-resume.ts +19 -12
  77. package/src/runs/background/async-retention.ts +20 -0
  78. package/src/runs/background/async-status-snapshot.ts +10 -12
  79. package/src/runs/background/async-status.ts +38 -35
  80. package/src/runs/background/auto-drain.ts +59 -35
  81. package/src/runs/background/binary-bootstrap.ts +38 -0
  82. package/src/runs/background/chain-append.ts +1 -1
  83. package/src/runs/background/chain-root-attachment.ts +22 -33
  84. package/src/runs/background/control-channel.ts +78 -44
  85. package/src/runs/background/fleet-view.ts +30 -2
  86. package/src/runs/background/notify.ts +193 -19
  87. package/src/runs/background/owned-process-tree.ts +35 -8
  88. package/src/runs/background/process-terminal.ts +23 -23
  89. package/src/runs/background/result-files.ts +8 -4
  90. package/src/runs/background/result-watcher.ts +19 -2
  91. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  92. package/src/runs/background/run-child-session.ts +118 -41
  93. package/src/runs/background/run-status.ts +78 -5
  94. package/src/runs/background/runner-aliases.ts +22 -5
  95. package/src/runs/background/runner-child-launch.ts +93 -0
  96. package/src/runs/background/runner-child-sessions.ts +5 -4
  97. package/src/runs/background/runner-http-dispatcher.ts +119 -0
  98. package/src/runs/background/scheduled-runs.ts +51 -18
  99. package/src/runs/background/stale-run-reconciler.ts +38 -12
  100. package/src/runs/background/steering.ts +20 -2
  101. package/src/runs/background/subagent-runner.ts +770 -444
  102. package/src/runs/background/subagent-wait.ts +179 -28
  103. package/src/runs/background/wait-completions.ts +79 -27
  104. package/src/runs/background/wait-subscriptions.ts +9 -3
  105. package/src/runs/background/wait-tool.ts +5 -3
  106. package/src/runs/foreground/async-steering-action.ts +37 -7
  107. package/src/runs/foreground/async-stop-action.ts +93 -3
  108. package/src/runs/foreground/execution.ts +174 -194
  109. package/src/runs/foreground/foreground-history.ts +5 -2
  110. package/src/runs/foreground/prompt-audit.ts +12 -6
  111. package/src/runs/foreground/subagent-executor.ts +915 -411
  112. package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
  113. package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
  114. package/src/runs/shared/acceptance.ts +54 -14
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +172 -78
  117. package/src/runs/shared/capability-ceiling.ts +2 -0
  118. package/src/runs/shared/child-hooks.ts +167 -3
  119. package/src/runs/shared/child-launch-plan.ts +15 -3
  120. package/src/runs/shared/child-launch.ts +49 -85
  121. package/src/runs/shared/child-lifecycle.ts +6 -3
  122. package/src/runs/shared/child-runtime-config.ts +8 -1
  123. package/src/runs/shared/child-session.ts +130 -24
  124. package/src/runs/shared/child-tool-plan.ts +149 -112
  125. package/src/runs/shared/completion-evidence.ts +2 -2
  126. package/src/runs/shared/completion-guard.ts +6 -3
  127. package/src/runs/shared/dynamic-fanout.ts +2 -2
  128. package/src/runs/shared/effective-system-prompt.ts +33 -0
  129. package/src/runs/shared/external-cli-contract.ts +11 -1
  130. package/src/runs/shared/external-cli-preflight.ts +6 -2
  131. package/src/runs/shared/external-cli-runner.ts +9 -7
  132. package/src/runs/shared/herdr-connection.ts +134 -0
  133. package/src/runs/shared/herdr-external-adapters.ts +169 -0
  134. package/src/runs/shared/herdr-machine.ts +279 -0
  135. package/src/runs/shared/herdr-pi-protocol.ts +59 -0
  136. package/src/runs/shared/herdr-placed-run.ts +263 -0
  137. package/src/runs/shared/host-step-status.ts +11 -11
  138. package/src/runs/shared/llm-intent-arbiter.ts +40 -21
  139. package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
  140. package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
  141. package/src/runs/shared/model-scope.ts +1 -1
  142. package/src/runs/shared/nested-events.ts +27 -34
  143. package/src/runs/shared/orca-progress-tabs.ts +7 -1
  144. package/src/runs/shared/parallel-handoff.ts +57 -12
  145. package/src/runs/shared/parallel-utils.ts +10 -4
  146. package/src/runs/shared/pi-spawn.ts +10 -0
  147. package/src/runs/shared/profile-extensions.ts +134 -0
  148. package/src/runs/shared/profile-launch-env.ts +113 -0
  149. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  150. package/src/runs/shared/run-fanout-budget.ts +8 -8
  151. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  152. package/src/runs/shared/sandbox-profile-guard.ts +34 -0
  153. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  154. package/src/runs/shared/task-intent.ts +46 -13
  155. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  156. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  157. package/src/runs/shared/worktree-setup-command.ts +213 -0
  158. package/src/runs/shared/worktree.ts +437 -214
  159. package/src/shared/child-cache-retention.ts +43 -0
  160. package/src/shared/fork-context.ts +15 -72
  161. package/src/shared/launch-contract.ts +70 -8
  162. package/src/shared/model-response-aliases.ts +13 -0
  163. package/src/shared/opencode-session-headers.ts +30 -0
  164. package/src/shared/permission-profile.ts +14 -0
  165. package/src/shared/pruned-fork.ts +1 -1
  166. package/src/shared/required-child-extensions.ts +81 -0
  167. package/src/shared/sandbox-profile.ts +14 -0
  168. package/src/shared/settings.ts +5 -2
  169. package/src/shared/shortcuts.ts +0 -4
  170. package/src/shared/types.ts +163 -90
  171. package/src/shared/utils.ts +10 -2
  172. package/src/shared/watch-strategy.ts +2 -0
  173. package/src/shared/workflow-child-permit.ts +18 -13
  174. package/src/slash/delegation-adapters.ts +3 -1
  175. package/src/slash/delegation-request.ts +14 -0
  176. package/src/slash/slash-commands.ts +2 -7
  177. package/src/slash/subagents-admin.ts +31 -14
  178. package/src/tui/fleet-status.ts +165 -20
  179. package/src/tui/fleet.ts +30 -19
  180. package/src/tui/render.ts +210 -50
  181. package/src/watchdog/child-status.ts +28 -28
  182. package/src/watchdog/lsp-diagnostics.ts +1 -1
  183. package/src/watchdog/model-selection.ts +21 -1
  184. package/src/watchdog/permission-arbiter.ts +5 -2
  185. package/src/watchdog/register-child.ts +10 -2
  186. package/src/watchdog/register-main.ts +39 -35
  187. package/src/watchdog/render.ts +1 -1
  188. package/src/watchdog/review.ts +122 -74
  189. package/src/watchdog/rules.ts +1 -1
  190. package/src/watchdog/runtime.ts +100 -27
  191. package/src/watchdog/scope.ts +1 -1
  192. package/src/watchdog/settings.ts +3 -0
  193. package/src/watchdog/tool-actions.ts +13 -12
  194. package/src/watchdog/turn-delta.ts +23 -0
  195. package/src/watchdog/types.ts +5 -3
  196. package/src/watchdog/warning-format.ts +1 -1
  197. package/src/workflows/chat-progress.ts +3 -3
  198. package/src/workflows/scripted-workflow.ts +349 -26
  199. package/src/workflows/workflow-checklist.ts +17 -20
  200. package/src/workflows/workflow-child-summary.ts +57 -8
  201. package/src/workflows/workflow-preflight.ts +19 -19
  202. package/src/workflows/workflow-receipt.ts +24 -6
  203. package/src/workflows/workflow-resources.ts +108 -22
  204. package/src/workflows/workflow-settlement.ts +3 -0
  205. package/src/runs/shared/model-exclusions.ts +0 -373
  206. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -6,6 +6,8 @@
6
6
  * observation channel, not a delivery acknowledgement.
7
7
  */
8
8
 
9
+ import { statSync } from "node:fs";
10
+ import { debuglog } from "node:util";
9
11
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
10
12
  import { buildCompletionKey, markSeenWithTtl } from "./completion-dedupe.ts";
11
13
  import {
@@ -26,6 +28,10 @@ export interface SubagentNotifyChildOutput {
26
28
  agent?: string;
27
29
  status: string;
28
30
  savedOutputPath?: string;
31
+ outputArtifactPath?: string;
32
+ structuredOutputPath?: string;
33
+ outputArtifactError?: RetainedPathError;
34
+ structuredOutputError?: RetainedPathError;
29
35
  preview: string;
30
36
  previewTruncated?: boolean;
31
37
  previewUnavailableReason?: string;
@@ -34,6 +40,8 @@ export interface SubagentNotifyChildOutput {
34
40
  export type SubagentNotifyWatchdogBlocker = Pick<ChildWatchdogWarningSummary, "summary" | "addressed" | "stalemate"> & { agent: string };
35
41
 
36
42
  export interface SubagentNotifyDetails {
43
+ workflowReceiptPath?: string;
44
+ asyncDir?: string;
37
45
  agent: string;
38
46
  status: "completed" | "failed" | "paused" | "stopped";
39
47
  source?: "async" | "foreground";
@@ -52,6 +60,16 @@ export interface SubagentNotifyDetails {
52
60
  watchdogBlockers?: SubagentNotifyWatchdogBlocker[];
53
61
  }
54
62
 
63
+ export interface IncrementalChildCompletion {
64
+ workflowRunId: string;
65
+ childKey: string;
66
+ childRunId?: string;
67
+ outcome: "completed" | "failed" | "paused" | "stopped";
68
+ outputReference?: string;
69
+ error?: string;
70
+ workflowRunning: boolean;
71
+ }
72
+
55
73
  export interface CompletionNotification {
56
74
  [key: string]: unknown;
57
75
  id?: string | null;
@@ -78,9 +96,12 @@ export interface CompletionNotification {
78
96
  success?: boolean;
79
97
  output?: string;
80
98
  structuredOutput?: unknown;
99
+ structuredOutputPath?: string;
81
100
  outputState?: "present" | "absent" | "unknown";
82
101
  outputReference?: string | { path?: string };
83
102
  artifactPaths?: { outputPath?: string };
103
+ outputSaveError?: string;
104
+ artifactOutputSaveFailed?: true;
84
105
  detached?: boolean;
85
106
  exitCode?: number | null;
86
107
  processSignal?: string | null;
@@ -107,6 +128,7 @@ export interface CompletionNotification {
107
128
  intercomDelivered?: boolean;
108
129
  parallelHandoff?: ParallelHandoffReference;
109
130
  scheduleOrigin?: ScheduleOrigin;
131
+ asyncDir?: string;
110
132
  }
111
133
 
112
134
  interface NotifyTimerApi {
@@ -123,6 +145,7 @@ export interface RegisterSubagentNotifyOptions {
123
145
 
124
146
  export interface CompletionNotifier {
125
147
  deliver(result: CompletionNotification): Promise<boolean>;
148
+ hasPendingDelivery(): boolean;
126
149
  dispose(): void;
127
150
  }
128
151
 
@@ -130,6 +153,11 @@ const CHILD_OUTPUT_PREVIEW_MAX_BYTES = 4 * 1024;
130
153
  const CHILD_OUTPUT_PREVIEW_COUNT = 8;
131
154
  const PREVIEW_TRUNCATION_MARKER = "...[preview truncated]";
132
155
  type CompletionChild = NonNullable<CompletionNotification["results"]>[number];
156
+ interface RetainedPathError { path: string; code?: string; message: string }
157
+ type RetainedPathProjection =
158
+ | { status: "verified"; path: string }
159
+ | { status: "unavailable" }
160
+ | { status: "error"; error: RetainedPathError };
133
161
 
134
162
  function truncateUtf8Head(value: string, maxBytes: number): { text: string; truncated: boolean } {
135
163
  const bytes = Buffer.from(value, "utf8");
@@ -158,6 +186,27 @@ function childSavedOutputPath(child: CompletionChild): string | undefined {
158
186
  return outputPathFromReference(child.outputReference);
159
187
  }
160
188
 
189
+ function nonemptyPath(value: unknown): string | undefined {
190
+ return typeof value === "string" && value.trim() ? value.trim() : undefined;
191
+ }
192
+
193
+ function retainedChildPath(value: unknown, producerConfirmed = false): RetainedPathProjection {
194
+ const path = nonemptyPath(value);
195
+ if (!path) return { status: "unavailable" };
196
+ if (producerConfirmed) return { status: "verified", path };
197
+ try {
198
+ return statSync(path).isFile() ? { status: "verified", path } : { status: "unavailable" };
199
+ } catch (error) {
200
+ const code = typeof error === "object" && error !== null && "code" in error && typeof error.code === "string" ? error.code : undefined;
201
+ if (code === "ENOENT" || code === "ENOTDIR") return { status: "unavailable" };
202
+ return { status: "error", error: { path, ...(code ? { code } : {}), message: error instanceof Error ? error.message : String(error) } };
203
+ }
204
+ }
205
+
206
+ function formatRetainedPathError(label: string, error: RetainedPathError): string {
207
+ return ` ${label} verification failed: stat ${error.code ? boundedSafeText(error.code, 32) : "unknown"}; path=${boundedSafeText(error.path, 384)}; ${boundedSafeText(error.message, 512)}`;
208
+ }
209
+
161
210
  function childStatus(child: CompletionChild, workflowState?: string): string {
162
211
  const knownStatus = child.status === "complete"
163
212
  ? "completed"
@@ -188,11 +237,17 @@ function structuredOutputText(value: unknown): string | undefined {
188
237
  }
189
238
  }
190
239
 
240
+ function isDegenerateOutput(text: string): boolean {
241
+ return !text.trim() || text.trim() === "</think>";
242
+ }
243
+
191
244
  function childInlinePreview(child: CompletionChild): { preview?: string; truncated?: boolean; unavailableReason?: string } {
192
245
  const output = typeof child.output === "string" ? child.output : "";
193
246
  const outputReference = childSavedOutputPath(child);
194
247
  const referenceOnly = Boolean(outputReference && output.trim().startsWith("Output saved to:"));
195
- const raw = child.outputState === "absent" || referenceOnly ? structuredOutputText(child.structuredOutput) : output || structuredOutputText(child.structuredOutput);
248
+ const raw = child.outputState === "absent" || referenceOnly
249
+ ? structuredOutputText(child.structuredOutput)
250
+ : isDegenerateOutput(output) ? structuredOutputText(child.structuredOutput) ?? output : output;
196
251
  if (!raw?.trim()) {
197
252
  return { unavailableReason: referenceOnly ? "saved output is file-only" : "no safe inline output" };
198
253
  }
@@ -212,6 +267,11 @@ function formatChildOutputBlock(children: SubagentNotifyChildOutput[] | undefine
212
267
  const status = boundedSafeText(child.status) || "unavailable";
213
268
  lines.push(`- key=${key} run=${runId} status=${status}`);
214
269
  lines.push(` Saved output: ${child.savedOutputPath ? boundedSafeText(child.savedOutputPath) : "unavailable"}`);
270
+ if (child.outputArtifactPath) lines.push(` Output artifact (retention-managed): ${boundedSafeText(child.outputArtifactPath)}`);
271
+ if (child.structuredOutputPath) lines.push(` Structured output (retention-managed): ${boundedSafeText(child.structuredOutputPath)}`);
272
+ if (child.outputArtifactError) lines.push(formatRetainedPathError("Output artifact", child.outputArtifactError));
273
+ if (child.structuredOutputError) lines.push(formatRetainedPathError("Structured output", child.structuredOutputError));
274
+ if (child.previewTruncated && !child.savedOutputPath && !child.outputArtifactPath) lines.push(" Full output unavailable");
215
275
  if (index >= CHILD_OUTPUT_PREVIEW_COUNT) {
216
276
  lines.push(" Preview: unavailable (notice preview budget exceeded)");
217
277
  continue;
@@ -248,6 +308,7 @@ function formatChildRun(child: { runId: string; workflowKey?: string; agent?: st
248
308
 
249
309
  function formatCorrelationLines(details: SubagentNotifyDetails): string[] {
250
310
  return [
311
+ details.asyncDir ? `Retention-managed async directory: ${boundedSafeText(details.asyncDir)}` : undefined,
251
312
  details.workflowRunId ? `Workflow run: ${details.workflowRunId}` : undefined,
252
313
  details.childRuns?.length ? `Child runs: ${details.childRuns.map(formatChildRun).join(", ")}` : undefined,
253
314
  details.reconciledFromDetachedChild ? `Reconciled detached child: ${details.reconciledFromDetachedChild}` : undefined,
@@ -282,6 +343,7 @@ export function formatSingleCompletion(details: SubagentNotifyDetails): string {
282
343
  : undefined;
283
344
  return [
284
345
  `${taskKind} ${details.status}: **${details.agent}**${details.taskInfo ?? ""}`,
346
+ details.workflowReceiptPath ? `Workflow receipt: ${details.workflowReceiptPath}` : undefined,
285
347
  "",
286
348
  scheduleLine,
287
349
  scheduleLine ? "" : undefined,
@@ -298,11 +360,49 @@ export function formatSingleCompletion(details: SubagentNotifyDetails): string {
298
360
  .join("\n");
299
361
  }
300
362
 
363
+ export function scheduledCompletionTriggersTurn(origin: ScheduleOrigin | undefined, outcome: string): boolean {
364
+ return !(origin?.quiet === true && outcome === "completed");
365
+ }
366
+
367
+ /**
368
+ * Child settlement is useful context, but an ordinary successful child does not
369
+ * establish the workflow's dependency barrier while its workflow is running.
370
+ * Keep actionable outcomes waking the parent, and preserve a terminal child as
371
+ * the barrier for hosts that do not emit a separate workflow completion wake.
372
+ */
373
+ export function incrementalChildCompletionTriggersTurn(
374
+ child: Pick<IncrementalChildCompletion, "outcome" | "workflowRunning">,
375
+ origin: ScheduleOrigin | undefined,
376
+ ): boolean {
377
+ if (child.workflowRunning && child.outcome === "completed") return false;
378
+ return scheduledCompletionTriggersTurn(origin, child.outcome);
379
+ }
380
+
381
+ export function formatIncrementalChildCompletion(child: IncrementalChildCompletion): string {
382
+ const statusText = child.outcome === "completed" ? "completed"
383
+ : child.outcome === "failed" ? "failed"
384
+ : child.outcome === "paused" ? "paused (needs attention)"
385
+ : "stopped";
386
+ const workflowStatus = child.workflowRunning ? "workflow still running" : "workflow finished";
387
+ return [
388
+ `Workflow child ${statusText}: **${child.childKey}**`,
389
+ `Workflow run: ${child.workflowRunId}`,
390
+ ...(child.childRunId ? [`Child run: ${child.childRunId}`] : []),
391
+ ...(child.outputReference ? [`Output: ${child.outputReference}`] : []),
392
+ ...(child.error ? [`Error: ${child.error}`] : []),
393
+ `Status: ${workflowStatus}`,
394
+ ].join("\n");
395
+ }
396
+
301
397
  export function parseSubagentNotifyContent(content: string): SubagentNotifyDetails | undefined {
302
398
  const lines = content.split("\n");
303
399
  const match = (lines[0] ?? "").match(/^(Background task|Detached foreground task) (completed|failed|paused|stopped): \*\*(.+?)\*\*(?:\s+(\([^)]*\)))?$/);
304
400
  if (!match) return undefined;
305
- let body = lines.slice(2);
401
+ // Only the header slot before the blank separator can carry a receipt.
402
+ // Identical lines anywhere in model output remain preview text.
403
+ const receiptHeader = lines[1]?.startsWith("Workflow receipt: ") && lines[2] === "";
404
+ const workflowReceiptPath = receiptHeader ? lines[1]!.slice("Workflow receipt: ".length) : undefined;
405
+ let body = lines.slice(receiptHeader ? 3 : 2);
306
406
  // Restore the schedule origin so a re-rendered notice keeps its attribution and
307
407
  // does not fold the line into the result preview.
308
408
  const scheduleMatch = (body[0] ?? "").match(/^Scheduled run from \*\*(.+?)\*\* \(schedule (.+?)\)\.$/);
@@ -358,6 +458,7 @@ export function parseSubagentNotifyContent(content: string): SubagentNotifyDetai
358
458
  ...(match[1] === "Detached foreground task" ? { source: "foreground" as const } : {}),
359
459
  ...(match[4] ? { taskInfo: match[4] } : {}),
360
460
  ...(parsedScheduleOrigin ? { scheduleOrigin: parsedScheduleOrigin } : {}),
461
+ ...(workflowReceiptPath ? { workflowReceiptPath } : {}),
361
462
  resultPreview,
362
463
  ...(handoffPath ? { handoffPath } : {}),
363
464
  ...(workflowRunId ? { workflowRunId } : {}),
@@ -376,6 +477,7 @@ export function formatGroupedCompletion(details: SubagentNotifyDetails[]): strin
376
477
  if (!detail) continue;
377
478
  const sessionLine = formatSessionLine(detail);
378
479
  blocks.push(`${index + 1}. ${detail.agent}${detail.taskInfo ?? ""}${detail.scheduleOrigin ? ` — scheduled run from ${detail.scheduleOrigin.name ?? detail.scheduleOrigin.id} (schedule ${detail.scheduleOrigin.id})` : ""}`);
480
+ if (detail.workflowReceiptPath) blocks.push(`Workflow receipt: ${detail.workflowReceiptPath}`);
379
481
  blocks.push(formatResultPreview(detail));
380
482
  blocks.push(...formatWatchdogBlockerLines(detail));
381
483
  if (detail.handoffPath) blocks.push(`Parallel handoff: ${detail.handoffPath}`);
@@ -386,7 +488,31 @@ export function formatGroupedCompletion(details: SubagentNotifyDetails[]): strin
386
488
  return blocks.join("\n").trimEnd();
387
489
  }
388
490
 
491
+ const notificationDebug = debuglog("pi-subagents-notify");
492
+ type TraceIdentity = Pick<CompletionNotification, "id" | "runId" | "source">;
493
+ type NotificationReason = "disposed" | "missing_session" | "foreground_session_mismatch" | "not_owned"
494
+ | "intercom_delivered" | "deduped_ttl" | "deduped_pending" | "batch_deferred"
495
+ | "emit_foreground_session_mismatch" | "emit_not_owned" | "send_accepted" | "send_failed" | "dispose_pending";
496
+
497
+ // Slice before sanitizing: diagnostic work and each identity are bounded even for
498
+ // malformed result metadata. Never include task/output, paths, or error bodies.
499
+ function traceIdentity(result: TraceIdentity): TraceIdentity {
500
+ const identity = (value: unknown) => typeof value === "string"
501
+ ? value.slice(0, 128).replace(/[^a-zA-Z0-9_.:-]/g, "_") : undefined;
502
+ return { id: identity(result.id), runId: identity(result.runId), source: result.source === "foreground" ? "foreground" : "async" };
503
+ }
504
+
505
+ function traceNotification(reason: NotificationReason, result?: TraceIdentity): void {
506
+ if (!notificationDebug.enabled) return;
507
+ try {
508
+ notificationDebug("%s", JSON.stringify({ reason, ...(result ? traceIdentity(result) : {}) }));
509
+ } catch {
510
+ // Diagnostics must never change delivery acknowledgement.
511
+ }
512
+ }
513
+
389
514
  interface PendingCompletion {
515
+ trace?: TraceIdentity;
390
516
  key: string;
391
517
  details: SubagentNotifyDetails;
392
518
  sessionId: string;
@@ -447,6 +573,10 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
447
573
  ? result.parallelHandoff as { path?: unknown }
448
574
  : undefined;
449
575
  const handoffPath = typeof parallelHandoff?.path === "string" ? parallelHandoff.path : undefined;
576
+ const receipt = result.workflowReceipt;
577
+ const receiptPath = receipt && typeof receipt === "object" && !Array.isArray(receipt)
578
+ ? (receipt as Record<string, unknown>).path : undefined;
579
+ const workflowReceiptPath = typeof receiptPath === "string" && receiptPath ? receiptPath : undefined;
450
580
  const rawRunId = typeof result.runId === "string" ? result.runId : typeof result.id === "string" ? result.id : undefined;
451
581
  const workflowRunId = (result.mode === "workflow" || agent === "workflow") && rawRunId ? rawRunId : undefined;
452
582
  const directChild = !workflowRunId && result.results?.length === 1 ? result.results[0]! : undefined;
@@ -455,10 +585,17 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
455
585
  : undefined;
456
586
  const directSummary = summary.trim();
457
587
  const directAgent = typeof directChild?.agent === "string" ? directChild.agent : agent;
588
+ const directSummaryBody = directAgent && summary.trimStart().startsWith(`${directAgent}:\n`)
589
+ ? summary.trimStart().slice(directAgent.length + 2)
590
+ : directSummary;
591
+ const directDegenerateSummary = directChild
592
+ && isDegenerateOutput(typeof directChild.output === "string" ? directChild.output : "")
593
+ && isDegenerateOutput(directSummaryBody)
594
+ && structuredOutputText(directChild.structuredOutput) !== undefined;
458
595
  const directNoOutputSummary = directChild && (!directSummary
459
596
  || directSummary === "(no output)"
460
597
  || (directAgent && directSummary === `${directAgent}:\n(no output)`));
461
- const resultPreview = directStructuredPreview && directNoOutputSummary
598
+ const resultPreview = directStructuredPreview && (directNoOutputSummary || directDegenerateSummary)
462
599
  ? `Structured output:\n${directStructuredPreview}`
463
600
  : summary;
464
601
  const childRuns = result.results?.flatMap((child) => {
@@ -478,12 +615,20 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
478
615
  const workflowKey = typeof child.workflowKey === "string" && child.workflowKey.trim() ? child.workflowKey.trim() : undefined;
479
616
  const runId = typeof child.runId === "string" && child.runId.trim() ? child.runId.trim() : undefined;
480
617
  const savedOutputPath = childSavedOutputPath(child);
618
+ const outputArtifact = child.artifactOutputSaveFailed === true ? { status: "unavailable" as const } : retainedChildPath(child.artifactPaths?.outputPath);
619
+ const structuredOutput = child.stopped === true || child.timedOut === true
620
+ ? { status: "unavailable" as const }
621
+ : retainedChildPath(child.structuredOutputPath, child.structuredOutput !== undefined);
481
622
  return {
482
623
  ...(workflowKey ? { workflowKey } : {}),
483
624
  ...(runId ? { runId } : {}),
484
625
  ...(typeof child.agent === "string" ? { agent: child.agent } : {}),
485
626
  status: childStatus(child, result.state),
486
627
  ...(savedOutputPath ? { savedOutputPath } : {}),
628
+ ...(outputArtifact.status === "verified" ? { outputArtifactPath: outputArtifact.path } : {}),
629
+ ...(structuredOutput.status === "verified" ? { structuredOutputPath: structuredOutput.path } : {}),
630
+ ...(outputArtifact.status === "error" ? { outputArtifactError: outputArtifact.error } : {}),
631
+ ...(structuredOutput.status === "error" ? { structuredOutputError: structuredOutput.error } : {}),
487
632
  ...(inline.preview ? { preview: inline.preview } : { preview: "" }),
488
633
  ...(inline.truncated ? { previewTruncated: true } : {}),
489
634
  ...(inline.unavailableReason ? { previewUnavailableReason: inline.unavailableReason } : {}),
@@ -491,15 +636,18 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
491
636
  })
492
637
  : undefined;
493
638
  const reconciledFromDetachedChild = typeof result.reconciledFromDetachedChild === "string" ? result.reconciledFromDetachedChild : undefined;
639
+ const asyncDir = nonemptyPath(result.asyncDir);
494
640
  const watchdogBlockers: SubagentNotifyWatchdogBlocker[] = [];
495
- const collectWatchdogBlockers = (owner: string, progress: ChildWatchdogProgress | undefined) => {
641
+ const watchdogConcerns: string[] = [];
642
+ const collectWatchdogFindings = (owner: string, progress: ChildWatchdogProgress | undefined) => {
496
643
  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 });
644
+ if (warning.importance !== "high") continue;
645
+ if (warning.severity === "blocker") watchdogBlockers.push({ agent: owner, summary: warning.summary, addressed: warning.addressed, stalemate: warning.stalemate });
646
+ else watchdogConcerns.push(`${owner}: ${warning.summary}\nEvidence: ${warning.evidence}\nRecommended action: ${warning.recommendedAction}`);
499
647
  }
500
648
  };
501
- collectWatchdogBlockers(agent, result.watchdog);
502
- for (const child of result.results ?? []) collectWatchdogBlockers(typeof child.agent === "string" ? child.agent : agent, child.watchdog);
649
+ collectWatchdogFindings(agent, result.watchdog);
650
+ for (const child of result.results ?? []) collectWatchdogFindings(typeof child.agent === "string" ? child.agent : agent, child.watchdog);
503
651
  const session =
504
652
  result.shareUrl
505
653
  ? { label: "Session", value: result.shareUrl }
@@ -516,9 +664,11 @@ export function buildCompletionDetails(result: CompletionNotification): Subagent
516
664
  agent,
517
665
  status,
518
666
  ...(scheduleOrigin ? { scheduleOrigin } : {}),
667
+ ...(workflowReceiptPath ? { workflowReceiptPath } : {}),
668
+ ...(asyncDir ? { asyncDir } : {}),
519
669
  ...(result.source ? { source: result.source } : {}),
520
670
  ...(taskInfo ? { taskInfo } : {}),
521
- resultPreview,
671
+ resultPreview: watchdogConcerns.length ? `${resultPreview}\n\nHigh-importance watchdog concerns:\n${watchdogConcerns.map((warning) => `- ${warning}`).join("\n")}` : resultPreview,
522
672
  ...(typeof result.durationMs === "number" ? { durationMs: result.durationMs } : {}),
523
673
  ...(handoffPath ? { handoffPath } : {}),
524
674
  ...(workflowRunId ? { workflowRunId } : {}),
@@ -547,8 +697,9 @@ export default function registerSubagentNotify(
547
697
  && typeof completionOwnerId === "string"
548
698
  && completionOwnerId === state.completionOwnerId);
549
699
 
550
- const settle = (items: PendingCompletion[], accepted: boolean) => {
700
+ const settle = (items: PendingCompletion[], accepted: boolean, reason?: NotificationReason) => {
551
701
  for (const item of items) {
702
+ if (reason) traceNotification(reason, item.trace);
552
703
  pending.delete(item.key);
553
704
  if (accepted) markSeenWithTtl(seen, item.key, now(), ttlMs);
554
705
  item.resolve(accepted);
@@ -561,10 +712,12 @@ export default function registerSubagentNotify(
561
712
  const owned = item.details.source === "foreground"
562
713
  ? item.sessionId === state.currentSessionId
563
714
  : ownsResult(item.sessionId, item.completionOwnerId);
715
+ if (!owned) traceNotification(item.details.source === "foreground" ? "emit_foreground_session_mismatch" : "emit_not_owned", item.trace);
564
716
  (owned ? accepted : rejected).push(item);
565
717
  }
566
718
  settle(rejected, false);
567
- settle(accepted, sendCompletion(pi, accepted));
719
+ const sent = sendCompletion(pi, accepted);
720
+ settle(accepted, sent, sent ? "send_accepted" : "send_failed");
568
721
  };
569
722
  const getBatcher = (result: CompletionNotification) => {
570
723
  const key = completionBatchKey(result);
@@ -582,17 +735,35 @@ export default function registerSubagentNotify(
582
735
  };
583
736
 
584
737
  const deliver = (result: CompletionNotification): Promise<boolean> => {
585
- if (disposed || typeof result.sessionId !== "string") return Promise.resolve(false);
738
+ if (disposed || typeof result.sessionId !== "string") {
739
+ traceNotification(disposed ? "disposed" : "missing_session", result);
740
+ return Promise.resolve(false);
741
+ }
586
742
  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);
589
- if (result.intercomDelivered === true) return Promise.resolve(true);
743
+ if (result.sessionId !== state.currentSessionId) {
744
+ traceNotification("foreground_session_mismatch", result);
745
+ return Promise.resolve(false);
746
+ }
747
+ } else if (!ownsResult(result.sessionId, result.completionOwnerId)) {
748
+ traceNotification("not_owned", result);
749
+ return Promise.resolve(false);
750
+ }
751
+ if (result.intercomDelivered === true) {
752
+ traceNotification("intercom_delivered", result);
753
+ return Promise.resolve(true);
754
+ }
590
755
  const key = buildCompletionKey(result, "notify");
591
756
  const seenAt = seen.get(key);
592
- if (seenAt !== undefined && now() - seenAt <= ttlMs) return Promise.resolve(true);
757
+ if (seenAt !== undefined && now() - seenAt <= ttlMs) {
758
+ traceNotification("deduped_ttl", result);
759
+ return Promise.resolve(true);
760
+ }
593
761
  if (seenAt !== undefined) seen.delete(key);
594
762
  const inFlight = pending.get(key);
595
- if (inFlight) return inFlight;
763
+ if (inFlight) {
764
+ traceNotification("deduped_pending", result);
765
+ return inFlight;
766
+ }
596
767
  const details = buildCompletionDetails(result);
597
768
  let resolve!: (accepted: boolean) => void;
598
769
  const completion = new Promise<boolean>((settleCompletion) => { resolve = settleCompletion; });
@@ -602,9 +773,10 @@ export default function registerSubagentNotify(
602
773
  details,
603
774
  sessionId: result.sessionId,
604
775
  completionOwnerId: result.completionOwnerId,
605
- triggerTurn: result.triggerTurn !== false,
776
+ triggerTurn: result.triggerTurn !== false && scheduledCompletionTriggersTurn(result.scheduleOrigin, details.status),
606
777
  resolve,
607
778
  };
779
+ if (notificationDebug.enabled) item.trace = traceIdentity(result);
608
780
  if (details.source === "foreground") {
609
781
  emit([item]);
610
782
  return completion;
@@ -615,6 +787,7 @@ export default function registerSubagentNotify(
615
787
  emit([item]);
616
788
  return completion;
617
789
  }
790
+ if (batchConfig.enabled) traceNotification("batch_deferred", item.trace);
618
791
  batcher.push(item);
619
792
  return completion;
620
793
  };
@@ -628,10 +801,11 @@ export default function registerSubagentNotify(
628
801
 
629
802
  return {
630
803
  deliver,
804
+ hasPendingDelivery: () => pending.size > 0,
631
805
  dispose() {
632
806
  if (disposed) return;
633
807
  disposed = true;
634
- for (const batcher of batchers.values()) settle(batcher.dispose(), false);
808
+ for (const batcher of batchers.values()) settle(batcher.dispose(), false, "dispose_pending");
635
809
  batchers.clear();
636
810
  for (const unsubscribe of [unsubscribeAsync, unsubscribeForeground]) {
637
811
  try {
@@ -1,5 +1,5 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import type { ProcessTreeTerminalV1 } from "../../shared/types.ts";
2
+ import type { ProcessTreeTerminal } from "../../shared/types.ts";
3
3
 
4
4
  const DEFAULT_TERM_GRACE_MS = 3000;
5
5
  const DEFAULT_KILL_VERIFY_MS = 1000;
@@ -35,6 +35,23 @@ function activeProcessGroupMembers(processGroupId: number): number[] | { diagnos
35
35
  return members;
36
36
  }
37
37
 
38
+ function knownDetachedDescendants(processGroupId: number): number[] {
39
+ const result = spawnSync("ps", ["-axo", "pid=,ppid=,pgid=,stat="], { encoding: "utf-8" });
40
+ if (result.error || result.status !== 0) return [];
41
+ const owned = new Set<number>();
42
+ const outside: { pid: number; ppid: number }[] = [];
43
+ for (const line of result.stdout.split("\n")) {
44
+ const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)/.exec(line);
45
+ if (!match || match[4]!.startsWith("Z")) continue;
46
+ const pid = Number(match[1]);
47
+ const ppid = Number(match[2]);
48
+ const pgid = Number(match[3]);
49
+ if (pgid === processGroupId) owned.add(pid);
50
+ else outside.push({ pid, ppid });
51
+ }
52
+ return outside.filter((row) => owned.has(row.ppid)).map((row) => row.pid);
53
+ }
54
+
38
55
  async function waitUntilGroupTerminal(
39
56
  processGroupId: number,
40
57
  timeoutMs: number,
@@ -52,37 +69,47 @@ async function waitUntilGroupTerminal(
52
69
  }
53
70
  }
54
71
 
55
- function observed(processGroupId: number): ProcessTreeTerminalV1 {
72
+ function observed(processGroupId: number): ProcessTreeTerminal {
56
73
  return { state: "observed", mechanism: "posix-process-group", processGroupId, verifiedAt: Date.now() };
57
74
  }
58
75
 
76
+ function observedUnlessLiveDetached(processGroupId: number, detached: readonly number[]): ProcessTreeTerminal {
77
+ const live = detached.filter((pid) => {
78
+ const result = spawnSync("ps", ["-o", "stat=", "-p", String(pid)], { encoding: "utf-8" });
79
+ return result.status === 0 && Boolean(result.stdout.trim()) && !result.stdout.trim().startsWith("Z");
80
+ });
81
+ if (live.length === 0) return observed(processGroupId);
82
+ return { state: "unknown", reason: "verification-failed", diagnostic: `Owned detached descendant(s) still active: ${live.join(", ")}.` };
83
+ }
84
+
59
85
  /** Owns one writer process group and arbitrates its cleanup exactly once. */
60
86
  export interface OwnedProcessTreeController {
61
- terminate(): Promise<ProcessTreeTerminalV1>;
62
- finishAfterWriterClose(): Promise<ProcessTreeTerminalV1>;
87
+ terminate(): Promise<ProcessTreeTerminal>;
88
+ finishAfterWriterClose(): Promise<ProcessTreeTerminal>;
63
89
  }
64
90
 
65
91
  export function createOwnedProcessTreeController(
66
92
  pid: number,
67
93
  options: { termGraceMs?: number; killVerifyMs?: number } = {},
68
94
  ): OwnedProcessTreeController {
69
- let termination: Promise<ProcessTreeTerminalV1> | undefined;
95
+ let termination: Promise<ProcessTreeTerminal> | undefined;
70
96
  const posixGroupOwned = process.platform !== "win32";
71
97
  const target = posixGroupOwned ? -pid : pid;
72
98
 
73
- const terminate = (): Promise<ProcessTreeTerminalV1> => {
99
+ const terminate = (): Promise<ProcessTreeTerminal> => {
74
100
  if (termination) return termination;
75
101
  termination = (async () => {
76
102
  if (!posixGroupOwned) {
77
103
  signalProcess(target, "SIGTERM");
78
104
  return { state: "unknown", reason: "unsupported-platform" };
79
105
  }
106
+ const detached = knownDetachedDescendants(pid);
80
107
  const term = signalProcess(target, "SIGTERM");
81
108
  if (term !== "sent" && term !== "absent") {
82
109
  return { state: "unknown", reason: "signal-failed", diagnostic: term.diagnostic };
83
110
  }
84
111
  const termExit = await waitUntilGroupTerminal(pid, options.termGraceMs ?? DEFAULT_TERM_GRACE_MS);
85
- if (termExit === false) return observed(pid);
112
+ if (termExit === false) return observedUnlessLiveDetached(pid, detached);
86
113
 
87
114
  const kill = signalProcess(target, "SIGKILL");
88
115
  if (kill !== "sent" && kill !== "absent") {
@@ -95,7 +122,7 @@ export function createOwnedProcessTreeController(
95
122
  if (killExit !== false) {
96
123
  return { state: "unknown", reason: "verification-failed", diagnostic: killExit.diagnostic };
97
124
  }
98
- return observed(pid);
125
+ return observedUnlessLiveDetached(pid, detached);
99
126
  })();
100
127
  return termination;
101
128
  };