@ferris1225/pi-subagents 5.0.2 → 5.0.4

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.
@@ -7,19 +7,22 @@ import { stopThreads } from "./stop.ts";
7
7
 
8
8
  const cancellations = new WeakMap<SubagentRuntime, Promise<void>>();
9
9
 
10
- export function cancelActiveWork(runtime: SubagentRuntime, reason: string): Promise<void> {
10
+ export function cancelActiveWork(runtime: SubagentRuntime, reason: string, notifyParent = true): Promise<void> {
11
11
  const existing = cancellations.get(runtime);
12
12
  if (existing) return existing;
13
13
  runtime.suppressCompletions = true;
14
14
  runtime.discardCompletions();
15
- // Start every interruption before awaiting cleanup: a worktree's integration
16
- // may need a repository lane held by a different shared writer.
15
+ // Interrupt every child before awaiting any integration cleanup.
17
16
  const graphs = [...runtime.workflows.values()].filter((graph) => graph.state === "running");
17
+ const activeThreads = [...runtime.threads.values()]
18
+ .filter((thread) => !thread.retired && (thread.lifecycleOperation !== undefined || ["queued", "running", "interrupting"].includes(thread.state)));
19
+ const threadIds = activeThreads.filter((thread) => !thread.workflow).map((thread) => thread.id);
18
20
  const graphStops = graphs.map(async (graph) => { await stopWorkflow(runtime, graph, reason); await graph.done; });
19
- const threadIds = [...runtime.threads.values()]
20
- .filter((thread) => !thread.workflow && (thread.lifecycleOperation !== undefined || ["queued", "running", "interrupting"].includes(thread.state)))
21
- .map((thread) => thread.id);
22
- const done = Promise.all([...graphStops, stopThreads(runtime, threadIds, reason)]).then(() => undefined).finally(() => {
21
+ const done = Promise.all([...graphStops, stopThreads(runtime, threadIds, reason)]).then(() => {
22
+ if (notifyParent && runtime.sessionActive && (activeThreads.length || graphs.length)) {
23
+ runtime.recordCancellation(activeThreads.map((thread) => thread.id), graphs.map((graph) => graph.id));
24
+ }
25
+ }).finally(() => {
23
26
  runtime.discardCompletions();
24
27
  runtime.suppressCompletions = false;
25
28
  cancellations.delete(runtime);
@@ -30,7 +33,7 @@ export function cancelActiveWork(runtime: SubagentRuntime, reason: string): Prom
30
33
 
31
34
  export function registerCancellationHooks(pi: ExtensionAPI, runtime: SubagentRuntime): void {
32
35
  pi.on("agent_settled", (event) => event.aborted ? cancelActiveWork(runtime, "Parent run was cancelled.") : undefined);
33
- pi.on("session_before_tree", () => cancelActiveWork(runtime, "Parent navigated to another conversation branch."));
36
+ pi.on("session_before_tree", () => cancelActiveWork(runtime, "Parent navigated to another conversation branch.", false));
34
37
  // Pi emits session_shutdown for new/resume/fork/reload. The runtime's
35
38
  // shutdown path stops children, retains recovery evidence, and disables delivery.
36
39
  }
@@ -143,22 +143,12 @@ export interface ActiveRunFoot {
143
143
  agent: string;
144
144
  /** Optional content label (task-derived) shown next to the agent name. */
145
145
  label?: string;
146
- /** Why a not-yet-executing run is waiting. Stated precisely so a repository
147
- * lane wait or a starting child is never mistaken for an exhausted pool. */
146
+ /** Startup state before a child emits activity. */
148
147
  wait?: RunWaitReason;
149
148
  }
150
149
 
151
150
  function activeRunWaitTag(wait: RunWaitReason | undefined): string {
152
- switch (wait) {
153
- case "process-slot":
154
- return " (queued, starts when a process slot frees)";
155
- case "repository-lane":
156
- return " (waiting for the repository write lane, not for a slot)";
157
- case "starting":
158
- return " (starting)";
159
- default:
160
- return "";
161
- }
151
+ return wait ? " (starting)" : "";
162
152
  }
163
153
 
164
154
  /**
@@ -4,7 +4,7 @@
4
4
  * The `subagent` tool and the workflow runner start children through the same
5
5
  * dispatcher, live-activity projection, terminal-notification path, and tool-card
6
6
  * details builder. Keeping them here means a workflow node is an ordinary
7
- * managed run: same queue pacing, isolation, admission, durable checkpointing,
7
+ * managed run: same lifecycle ownership, isolation, admission, durable checkpointing,
8
8
  * and completion accounting.
9
9
  */
10
10
 
@@ -23,7 +23,7 @@ export interface DispatchCore {
23
23
  /** Stamp a terminal monitor state and toast the result once. */
24
24
  finishRun: (runId: number, status: "done" | "failed", opts?: { silent?: boolean }) => void;
25
25
  makeLiveHandler: (runId: number, generation?: number) => (event: SubagentLiveEvent) => void;
26
- makeDetails: (mode: "single" | "parallel", background?: boolean) => (results: SingleResult[]) => SubagentDetails;
26
+ makeDetails: (mode: "single" | "parallel") => (results: SingleResult[]) => SubagentDetails;
27
27
  }
28
28
 
29
29
  export function createDispatchCore(runtime: SubagentRuntime): DispatchCore {
@@ -118,8 +118,8 @@ export function createDispatchCore(runtime: SubagentRuntime): DispatchCore {
118
118
  };
119
119
 
120
120
  const makeDetails =
121
- (mode: "single" | "parallel", background = false) =>
122
- (results: SingleResult[]): SubagentDetails => ({ mode, results, background });
121
+ (mode: "single" | "parallel") =>
122
+ (results: SingleResult[]): SubagentDetails => ({ mode, results });
123
123
 
124
124
  const startBackground = createBackgroundDispatcher({
125
125
  runtime,
@@ -12,7 +12,7 @@ import type { ExtensionAPI, ToolInfo } from "@earendil-works/pi-coding-agent";
12
12
  import { findDuplicateDispatch } from "../delegation/prompt.ts";
13
13
  import type { PhaseScope } from "../delegation/phase-scope.ts";
14
14
  import { rmSync } from "node:fs";
15
- import { resolveSubagentConcurrency, BackgroundTaskQueue } from "../execution/background.ts";
15
+ import { BackgroundTaskQueue } from "../execution/background.ts";
16
16
  import {
17
17
  createCompletionBatcher,
18
18
  formatActiveRunsFooter,
@@ -89,6 +89,8 @@ export interface SubagentRuntime {
89
89
  /** Cancelling a parent must not wake it again with old child results. */
90
90
  suppressCompletions: boolean;
91
91
  discardCompletions: () => void;
92
+ /** Record cancellation for the next user turn without waking the parent. */
93
+ recordCancellation: (runIds: number[], workflowIds: number[]) => void;
92
94
  /** Resolves when the load-time durable restore pass has finished. Everything
93
95
  * that answers "which threads exist" awaits it — the lookup tools, a fresh
94
96
  * dispatch before it allocates a run id, and the restored-thread notice — so
@@ -158,7 +160,7 @@ export function findPendingWorkflowPhase(
158
160
  }
159
161
 
160
162
  export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRuntime {
161
- const backgroundQueue = new BackgroundTaskQueue(resolveSubagentConcurrency());
163
+ const backgroundQueue = new BackgroundTaskQueue();
162
164
  let nextWorkflowId = 1;
163
165
  // Compaction reads the whole history, summarizes it, and replaces it. A
164
166
  // completion injected into that window can be swallowed by the summary,
@@ -175,6 +177,18 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
175
177
  getToolInfos: () => pi.getAllTools(),
176
178
  sessionActive: true,
177
179
  suppressCompletions: false,
180
+ recordCancellation: (runIds, workflowIds) => {
181
+ const targets = [
182
+ ...(runIds.length ? ["runs " + runIds.map((id) => `#${id}`).join(", ")] : []),
183
+ ...(workflowIds.length ? ["workflows " + workflowIds.map((id) => `#${id}`).join(", ")] : []),
184
+ ].join("; ");
185
+ pi.sendMessage({
186
+ customType: "subagent-cancelled",
187
+ content: `Parent cancellation stopped ${targets}. These runs are already cancelled; no further subagent_stop is needed. Do not restart cancelled work unless the user requests it. Partial edits and retained integration artifacts may remain; inspect them only if continuing the task.`,
188
+ display: true,
189
+ details: { runIds, workflowIds },
190
+ }, { deliverAs: "nextTurn", triggerTurn: false });
191
+ },
178
192
  discardCompletions: () => {
179
193
  runtime.completionBatcher.dispose();
180
194
  heldCompletions = [];
@@ -22,6 +22,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
22
22
  generation: number;
23
23
  controller: AbortController | undefined;
24
24
  completion: Promise<void>;
25
+ releaseQuiescence: () => void;
25
26
  stopVersion: number;
26
27
  stopMessage: string;
27
28
  }> = [];
@@ -36,6 +37,12 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
36
37
  thread.retired = true;
37
38
  thread.retireOnSettle = true;
38
39
  thread.state = "stopped";
40
+ const completion = thread.generationCompletion;
41
+ let releaseQuiescence!: () => void;
42
+ const stopCompletion = new Promise<void>((resolve) => { releaseQuiescence = resolve; });
43
+ // A repeated stop must also wait for this owner's finalization, even if
44
+ // the bounded control call has already returned a partial result.
45
+ thread.generationCompletion = Promise.allSettled([completion, stopCompletion]).then(() => undefined);
39
46
  const stopMessage = reason ?? (wasQueued
40
47
  ? "Stopped by subagent_stop before the run started."
41
48
  : wasActive ? "Stopped by subagent_stop."
@@ -45,7 +52,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
45
52
  runId, thread, run: monitor.findRun(runId), previousState, wasQueued, wasActive,
46
53
  generation: thread.generation,
47
54
  controller: thread.queueController,
48
- completion: thread.generationCompletion,
55
+ completion, releaseQuiescence,
49
56
  stopVersion, stopMessage,
50
57
  });
51
58
  }
@@ -74,6 +81,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
74
81
  generation,
75
82
  controller,
76
83
  completion,
84
+ releaseQuiescence,
77
85
  stopVersion,
78
86
  stopMessage,
79
87
  } = claim;
@@ -91,6 +99,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
91
99
  // lifecycle. Synthesize and publish the one aborted result here only when
92
100
  // this stop actually interrupted unfinished work.
93
101
  let stoppedResult: SingleResult | undefined;
102
+ let finalizationCompletion: Promise<WorktreeFinalization | undefined> = Promise.resolve(undefined);
94
103
  if (
95
104
  wasQueued ||
96
105
  previousState === "parked" ||
@@ -123,8 +132,9 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
123
132
  const worktree = thread.worktree;
124
133
  let finalization: WorktreeFinalization | undefined;
125
134
  try {
135
+ finalizationCompletion = thread.finalizeIsolation(generation, stoppedResult);
126
136
  finalization = await Promise.race([
127
- thread.finalizeIsolation(generation, stoppedResult),
137
+ finalizationCompletion,
128
138
  new Promise<undefined>((resolve) => {
129
139
  const timer = setTimeout(() => resolve(undefined), CONTROL_QUIESCE_TIMEOUT_MS);
130
140
  if (typeof timer.unref === "function") timer.unref();
@@ -167,9 +177,14 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
167
177
  // The destructive retire removes the durable record with the session;
168
178
  // an id never resurrects after subagent_stop.
169
179
  await removeThreadRecord(runtime.configPath, runId, thread.cwd).catch(() => undefined);
170
- if (thread.lifecycleVersion === stopVersion && thread.lifecycleOperation === "stop") {
171
- thread.lifecycleOperation = undefined;
172
- }
180
+ // Returning from a bounded stop retires context, but cannot release a
181
+ // writer or phase lease while a child or Git tail can still change files.
182
+ void Promise.allSettled([interruptionPromises[claimIndex]!, completion, finalizationCompletion]).then(() => {
183
+ if (thread.lifecycleVersion === stopVersion && thread.lifecycleOperation === "stop") {
184
+ thread.lifecycleOperation = undefined;
185
+ }
186
+ releaseQuiescence();
187
+ });
173
188
  stopped.push(`#${runId} ${thread.agentName}${wasQueued ? " (queued)" : wasActive ? "" : ` (${previousState})`}`);
174
189
  }
175
190
  return { stopped, retainedIntegration, pendingIntegration, completionResults };
@@ -213,11 +213,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
213
213
  if (isolation === "shared" || worktree) installCurrentLifecycle();
214
214
 
215
215
  const onLive = makeLiveHandler(runId, generation);
216
- // Shared write-capable runs serialize on the repository lane so their
217
- // edits cannot race; the lane wait releases the process slot because it
218
- // is write serialization, not pool pacing.
219
- const reserveManagedLane = isolation === "shared" && writeCapable;
220
- const runGeneration = async (backgroundSignal: AbortSignal, controller: AbortController): Promise<void> => {
216
+ const runGeneration = async (backgroundSignal: AbortSignal): Promise<void> => {
221
217
  if (runtime.threads.get(runId)?.generation !== generation) return;
222
218
  if (isolation === "worktree" && !worktree) {
223
219
  const prepared = await createWorktreeIsolation(originalCwd, { tempBaseDir: worktreesRoot });
@@ -233,14 +229,9 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
233
229
  monitor.setIsolation(runId, "worktree", "pending", worktreeGroup);
234
230
  installCurrentLifecycle();
235
231
  }
236
- // The generation body owns a process slot from here (a lane wait, if
237
- // any, was granted above). Recording the transition synchronously keeps
238
- // every "queued" surface truthful: only runs still pending in the pool
239
- // or behind the lane report a wait.
232
+ // Independent runs start immediately; only worktree integration serializes.
240
233
  monitor.setWaitReason(runId, "starting");
241
- // Model/thinking config may have changed while this generation sat
242
- // queued behind the concurrency limit. Re-resolve the route at actual
243
- // start so /subagents-setup edits apply to not-yet-started runs.
234
+ // Re-read model preferences after asynchronous worktree preparation.
244
235
  let activeRoute = route;
245
236
  const activeIdleTimeoutMs = DEFAULT_IDLE_TIMEOUT_SEC * 1000;
246
237
  try {
@@ -332,9 +323,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
332
323
  thread.lifecycleOperation === "settle" &&
333
324
  !thread.retired;
334
325
  try {
335
- // The child process has exited. Isolated Git finalization remains
336
- // lifecycle-owned and awaited, but no longer consumes a process slot.
337
- if (isolation === "worktree") runtime.backgroundQueue.suspend(controller);
326
+ // Keep ownership until isolated Git finalization finishes.
338
327
  await thread.finalizeIsolation(generation, result);
339
328
  if (!ownsSettlement()) return;
340
329
 
@@ -382,26 +371,8 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
382
371
  if (ownsSettlement()) thread.lifecycleOperation = undefined;
383
372
  }
384
373
  };
385
- const queuedGeneration = reserveManagedLane
386
- ? async (backgroundSignal: AbortSignal, controller: AbortController): Promise<void> => {
387
- // Waiting for repository serialization must not consume a process
388
- // slot. Once the lane is granted, reacquire through the same FIFO
389
- // scheduler before any child process can spawn.
390
- runtime.backgroundQueue.suspend(controller);
391
- monitor.setWaitReason(runId, "repository-lane");
392
- await runInManagedRepositoryLane(
393
- originalCwd,
394
- async () => {
395
- monitor.setWaitReason(runId, "process-slot");
396
- if (!(await runtime.backgroundQueue.acquire(controller))) return;
397
- await runGeneration(backgroundSignal, controller);
398
- },
399
- backgroundSignal,
400
- );
401
- }
402
- : runGeneration;
403
374
  const queueController = runtime.backgroundQueue.enqueue(
404
- queuedGeneration,
375
+ runGeneration,
405
376
  () => {
406
377
  if (runtime.threads.get(runId)?.generation !== generation) return;
407
378
  // A destructive stop owns publication and may still be finalizing an
@@ -455,7 +426,6 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
455
426
  };
456
427
  thread.lastResult = crashed;
457
428
  runtime.retainSession(crashed);
458
- if (isolation === "worktree" && thread.worktree) runtime.backgroundQueue.suspend(thread.queueController);
459
429
  await thread.finalizeIsolation(generation, crashed);
460
430
  if (!ownsSettlement()) return;
461
431
  thread.state = "failed";
@@ -54,28 +54,11 @@ async function canonicalManagedRepositoryRoot(cwd: string): Promise<string> {
54
54
  }
55
55
  }
56
56
 
57
- /** Run one operation under the canonical original-repository lane.
58
- *
59
- * Shared write-capable generations use the abortable overload for their whole
60
- * run. Isolated generations use the non-abortable overload only for their
61
- * final worktree apply, so model work remains parallel while the original
62
- * checkout mutation cannot race a shared writer.
63
- */
57
+ /** Serialize only worktree integration into the original checkout. */
64
58
  export async function runInManagedRepositoryLane<T>(
65
59
  cwd: string,
66
60
  task: () => Promise<T>,
67
- ): Promise<T>;
68
- export async function runInManagedRepositoryLane<T>(
69
- cwd: string,
70
- task: () => Promise<T>,
71
- signal: AbortSignal,
72
- ): Promise<T | undefined>;
73
- export async function runInManagedRepositoryLane<T>(
74
- cwd: string,
75
- task: () => Promise<T>,
76
- signal?: AbortSignal,
77
- ): Promise<T | undefined> {
78
- if (signal?.aborted) return undefined;
61
+ ): Promise<T> {
79
62
  const root = await canonicalManagedRepositoryRoot(cwd);
80
63
  const key = process.platform === "win32" ? root.toLowerCase() : root;
81
64
  const previous = managedRepositoryRootTails.get(key) ?? Promise.resolve();
@@ -85,30 +68,11 @@ export async function runInManagedRepositoryLane<T>(
85
68
  });
86
69
  const tail = previous.catch(() => undefined).then(() => gate);
87
70
  managedRepositoryRootTails.set(key, tail);
88
- let onAbort: (() => void) | undefined;
89
71
  try {
90
- if (signal) {
91
- await Promise.race([
92
- previous.catch(() => undefined),
93
- new Promise<void>((resolveAborted) => {
94
- if (signal.aborted) resolveAborted();
95
- else {
96
- onAbort = resolveAborted;
97
- signal.addEventListener("abort", onAbort, { once: true });
98
- }
99
- }),
100
- ]);
101
- } else {
102
- await previous.catch(() => undefined);
103
- }
104
- if (signal?.aborted) return undefined;
72
+ await previous.catch(() => undefined);
105
73
  return await task();
106
74
  } finally {
107
- if (signal && onAbort) signal.removeEventListener("abort", onAbort);
108
75
  release();
109
- // An aborted waiter may finish before the prior owner. Keep its chained
110
- // tail installed until that owner also settles, otherwise a newcomer could
111
- // observe an empty map and race the still-running workflow.
112
76
  void tail.then(() => {
113
77
  if (managedRepositoryRootTails.get(key) === tail) managedRepositoryRootTails.delete(key);
114
78
  });
@@ -22,15 +22,8 @@ import type { IsolationMode, WorktreeFinalizationStatus } from "../isolation/wor
22
22
 
23
23
  export type RunStatus = "queued" | "running" | "interrupting" | "parked" | "done" | "failed";
24
24
 
25
- /** Why a queued run has produced no output yet. Three genuinely different
26
- * situations used to be reported as one "queued": waiting for a free process
27
- * slot (real pool pacing), serialized behind the shared-checkout repository
28
- * write lane (a slot is free — the wait is write serialization), and already
29
- * starting its child process (a slot is held; output is seconds away).
30
- * Conflating them taught the parent model that the pool was exhausted when it
31
- * was not, so it stopped dispatching. Meaningful only while status is
32
- * "queued"; cleared on every transition out of it. */
33
- export type RunWaitReason = "process-slot" | "repository-lane" | "starting";
25
+ /** A queued run is preparing its child process; execution has no capacity wait. */
26
+ export type RunWaitReason = "starting";
34
27
 
35
28
  export function isRunActiveStatus(status: RunStatus): boolean {
36
29
  return status === "queued" || status === "running" || status === "interrupting";
@@ -91,9 +84,7 @@ export interface RunChainMeta {
91
84
  worktreeId?: string;
92
85
  /** Set for nodes the workflow runner dispatches. */
93
86
  workflow?: RunWorkflowTag;
94
- /** Initial wait reason; defaults to "process-slot" (a fresh dispatch enters
95
- * the process queue). Children spawned outside the queue pass "starting"
96
- * because they never wait for a slot. */
87
+ /** Initial startup state before the child emits activity. */
97
88
  waitReason?: RunWaitReason;
98
89
  }
99
90
 
@@ -527,7 +518,7 @@ export class MonitorStore {
527
518
  model,
528
519
  thinking,
529
520
  status: "queued",
530
- waitReason: meta?.waitReason ?? "process-slot",
521
+ waitReason: meta?.waitReason ?? "starting",
531
522
  usage: emptyUsage(),
532
523
  elapsedMs: 0,
533
524
  ...(meta?.isolation ? { isolation: meta.isolation, integrationStatus: meta.isolation === "worktree" ? "pending" : undefined, ...(meta.worktreeId ? { worktreeId: meta.worktreeId } : {}) } : {}),
@@ -741,9 +732,7 @@ export function statusIcon(status: RunStatus, theme: Theme): string {
741
732
  }
742
733
  }
743
734
 
744
- /** User-facing status label used by tool/status rendering. Queued runs say
745
- * so: anything vaguer ("ready") reads like an unexplained cap and made models
746
- * stop dispatching while slots were merely pacing. */
735
+ /** User-facing lifecycle label used by tool/status rendering. */
747
736
  export function statusLabel(status: RunStatus): string {
748
737
  switch (status) {
749
738
  case "queued":
@@ -761,17 +750,7 @@ export function statusLabel(status: RunStatus): string {
761
750
  }
762
751
  }
763
752
 
764
- /** Truthful description of why a queued run has produced no output yet, so a
765
- * repository-lane wait or a starting child is never mistaken for an exhausted
766
- * process pool. Undefined for runs that are not queued. */
753
+ /** Startup label for runs that have not emitted activity yet. */
767
754
  export function runWaitLabel(run: Pick<RunView, "status" | "waitReason">): string | undefined {
768
- if (run.status !== "queued") return undefined;
769
- switch (run.waitReason) {
770
- case "repository-lane":
771
- return "waiting for the repository write lane";
772
- case "starting":
773
- return "starting";
774
- default:
775
- return "queued for a free process slot";
776
- }
755
+ return run.status === "queued" ? "starting" : undefined;
777
756
  }
@@ -13,7 +13,7 @@ const MAX_WIDGET_LINES = 10;
13
13
  const SEPARATOR = " · ";
14
14
 
15
15
  function waitWord(run: Pick<RunView, "waitReason">): string {
16
- return run.waitReason === "repository-lane" ? "repo lane" : run.waitReason === "starting" ? "starting" : "queued";
16
+ return run.waitReason === "starting" ? "starting" : "queued";
17
17
  }
18
18
 
19
19
  function worktreeBadge(run: RunView): string | undefined {
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * The rule this module exists for is "dispatch the next node the moment its
5
5
  * prerequisites settle, without waking the parent model". Each node is started
6
- * through the same dispatcher a `subagent` call uses — same queue pacing, same
6
+ * through the same dispatcher a `subagent` call uses — same lifecycle ownership, same
7
7
  * admission, same isolation, same durable checkpoint — and is `quiet`, meaning
8
8
  * it reports into this graph instead of sending its own completion message.
9
9
  * The parent is woken exactly once, with the graph's summary.
@@ -13,7 +13,6 @@ import { Type } from "typebox";
13
13
  import { isWriteCapableAgent, loadBuiltinAgents } from "../delegation/agents.ts";
14
14
  import { defaultIsolationMode, IsolationSchema, PhaseIdSchema, ScopeSchema } from "../delegation/dispatch.ts";
15
15
  import { loadConfig } from "../configuration/config.ts";
16
- import { resolveSubagentConcurrency } from "../execution/background.ts";
17
16
  import type { SubagentRuntime } from "../lifecycle/runtime.ts";
18
17
  import type { DispatchCore } from "../lifecycle/dispatch-core.ts";
19
18
  import { projectResultsRoot } from "../lifecycle/thread-shared.ts";
@@ -76,7 +75,6 @@ const WorkflowParams = Type.Object({
76
75
 
77
76
  export interface WorkflowToolDetails {
78
77
  workflow: WorkflowStatusView;
79
- runIds: number[];
80
78
  }
81
79
 
82
80
  function launchReceipt(status: WorkflowStatusView): string {
@@ -96,7 +94,7 @@ function launchReceipt(status: WorkflowStatusView): string {
96
94
  return parts.join(" · ");
97
95
  }),
98
96
  "",
99
- "The graph dispatches each dependent the moment its prerequisites settle, with no further dispatch from you. One summary arrives when the whole graph settles; continue disjoint work or end your turn, and do not poll. The automatic process limit paces nodes, so a wide graph queues instead of refusing.",
97
+ "The graph dispatches each dependent the moment its prerequisites settle, with no further dispatch from you. One summary arrives when the whole graph settles; continue disjoint work or end your turn, and do not poll. Ready independent nodes start together without a process-count limit.",
100
98
  ];
101
99
  return lines.join("\n");
102
100
  }
@@ -136,9 +134,9 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
136
134
  name: "subagent_workflow",
137
135
  label: "Subagent Workflow",
138
136
  description:
139
- "Run a dependency graph of sub-agent phases: declare nodes with dependsOn, and the runtime dispatches each dependent as soon as its prerequisites settle and a process slot frees. Choose this proactively for two or more substantial phases with known dependencies and writer scopes, when scheduling saves coordination. Use subagent tasks for independent work with no dependency edges; keep small or tightly coupled work in main. If a result must decide the next task or its scope, dispatch that phase alone, decide in main, then reassess whether a graph fits. Never add research, review, or gate nodes by habit. A graph saves dispatch turns; it does not plan or judge success beyond process results. One summary arrives when the graph settles. Nodes are ordinary one-shot runs; main still owns integration, the final gate, and release.",
137
+ "Run a dependency graph of sub-agent phases: declare nodes with dependsOn, and the runtime dispatches each dependent as soon as its prerequisites settle. Choose this proactively for two or more substantial phases with known dependencies and writer scopes, when scheduling saves coordination. Use subagent tasks for independent work with no dependency edges; keep small or tightly coupled work in main. If a result must decide the next task or its scope, dispatch that phase alone, decide in main, then reassess whether a graph fits. Never add research, review, or gate nodes by habit. A graph saves dispatch turns; it does not plan or judge success beyond process results. One summary arrives when the graph settles. Nodes are ordinary one-shot runs; main still owns integration, the final gate, and release.",
140
138
  exposure: "model-only",
141
- executionMode: "sequential",
139
+ executionMode: "parallel",
142
140
  annotations: {
143
141
  readOnlyHint: false,
144
142
  destructiveHint: true,
@@ -151,8 +149,7 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
151
149
  await runtime.durableRestore;
152
150
  monitor.beginTurn();
153
151
  const config = await loadConfig(runtime.configPath);
154
- runtime.backgroundQueue.setConcurrency(resolveSubagentConcurrency());
155
- // Both built-in roles are always available; the live tool metadata decides
152
+ // All built-in roles are always available; the live tool metadata decides
156
153
  // which of them is write-capable in this session.
157
154
  const agents = loadBuiltinAgents();
158
155
  const toolInfos = runtime.getToolInfos();
@@ -248,10 +245,7 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
248
245
  const status = workflowStatus(handle.run);
249
246
  return {
250
247
  content: [{ type: "text", text: launchReceipt(status) }],
251
- details: {
252
- workflow: status,
253
- runIds: status.nodes.flatMap((node) => (node.runId === undefined ? [] : [node.runId])),
254
- } satisfies WorkflowToolDetails,
248
+ details: { workflow: status } satisfies WorkflowToolDetails,
255
249
  };
256
250
  },
257
251
 
@@ -1,14 +1,14 @@
1
1
  ---
2
2
  name: code-review
3
- description: Review a change with independent eyes, confirm each finding, and report what was verified.
3
+ description: Review a change from independent angles and return evidence-checked findings.
4
4
  ---
5
5
 
6
6
  # Code review workflow
7
7
 
8
- Two reviewers read the same change from different angles, a third agent then
9
- tries to *disprove* every finding against the code, and the last node writes the
10
- report the user keeps. This saved template chooses a thorough adversarial review;
11
- for a small diff, combine the map with a reviewer and let main write the report.
8
+ A mapping node establishes the target, two reviewers inspect it from different
9
+ angles, and a critic checks their findings and returns the final review. Use this
10
+ four-node template for a broad change that warrants independent review lenses;
11
+ for a small diff, use one reviewer and let main assess the findings.
12
12
 
13
13
  Copy this file to `.pi/workflows/code-review.md` in the repository you are
14
14
  reviewing. Two things are yours to set before you run it:
@@ -48,14 +48,8 @@ Run it with `subagent_workflow({ "workflow": "code-review" })`, or by path with
48
48
  "id": "confirm",
49
49
  "agent": "critic",
50
50
  "isolation": "shared",
51
- "task": "Two reviewers reported findings. Your job is to try to disprove them, not to agree.\n\nCorrectness findings:\n{{correctness}}\n\nRisk findings:\n{{risk}}\n\nFor each finding, look for a counterexample in callers, invariants, and tests. Run a safe focused reproduction when needed and available. Do not edit files, install dependencies, or change Git state. Classify it as reproduced (command and result), source-supported (code evidence, not executed), disproved (counterevidence), or unverified (missing evidence). Return surviving findings with severity and the evidence that would falsify them.",
51
+ "task": "Two reviewers reported findings. Try to disprove each one against callers, invariants, and tests. A review with no surviving findings is valid.\n\nCorrectness findings:\n{{correctness}}\n\nRisk findings:\n{{risk}}\n\nRun a safe focused reproduction when needed and available. Do not edit files, install dependencies, or change Git state. Classify each finding as reproduced (command and result), source-supported (code evidence, not executed), disproved (counterevidence), or unverified (missing evidence). Return the final review: a concise verdict, surviving actionable findings ordered by severity with path:line, trigger, consequence, evidence and smallest fix, then checks performed and material gaps. Keep rejected findings brief; do not promote unverified concerns to confirmed defects.",
52
52
  "dependsOn": ["correctness", "risk"]
53
- },
54
- {
55
- "id": "report",
56
- "agent": "scout",
57
- "task": "Write the review the user acts on, from the surviving findings and evidence:\n\n{{confirm}}\n\nStructure it as: a two-sentence verdict, then each surviving finding as where / what / evidence / severity, then what was checked and how, then what the review did not cover. Say plainly which findings were confirmed and which stayed unverified. Do not edit code; this node produces the report only.",
58
- "dependsOn": ["confirm"]
59
53
  }
60
54
  ]
61
55
  }
@@ -8,7 +8,9 @@ description: Apply two already planned migration slices, then challenge the inte
8
8
  Use this template after main has established the target, interface contract,
9
9
  and disjoint writer scopes. If discovery determines those boundaries, run that
10
10
  discovery first and decide in main; a static graph cannot rewrite its own nodes.
11
- Replace <TARGET>, both slice briefs, and the example paths before running.
11
+ Replace <TARGET>, <CONTRACT> (the shared interface contract or its file path),
12
+ both slice briefs, and every example scope before running. Each child needs the
13
+ contract in its own brief because it cannot see main's conversation.
12
14
  Each slice owns its implementation and regression tests. Keep coupled changes
13
15
  with one owner. Add a separate adversarial reviewer for risk that the gate cannot
14
16
  cover; main still owns final integration and release.
@@ -19,21 +21,22 @@ cover; main still owns final integration and release.
19
21
  {
20
22
  "id": "apply-core",
21
23
  "agent": "artisan",
22
- "task": "Migrate the core slice to <TARGET>. <CORE_CHANGE>. Follow the interface contract and paths main established. Implement the change and its regression tests together; run the relevant checks. Report changed paths, command results, and blockers. If the plan conflicts with the code or requires another slice's files, stop and report evidence rather than inventing a new scope.",
24
+ "task": "Migrate the core slice to <TARGET>. <CORE_CHANGE>. Interface contract: <CONTRACT>. Follow the declared write scope. Implement the change and its regression tests together; run the relevant checks. Report changed paths, command results, and blockers. If the plan conflicts with the code or requires another slice's files, stop and report evidence rather than inventing a new scope.",
23
25
  "scope": { "paths": ["src/core", "test/core"] }
24
26
  },
25
27
  {
26
28
  "id": "apply-adapters",
27
29
  "agent": "artisan",
28
- "task": "Migrate the adapter slice to <TARGET>. <ADAPTER_CHANGE>. Follow the interface contract and paths main established. Implement the change and its regression tests together; run the relevant checks. Report changed paths, command results, and blockers. If the plan conflicts with the code or requires another slice's files, stop and report evidence rather than inventing a new scope.",
30
+ "task": "Migrate the adapter slice to <TARGET>. <ADAPTER_CHANGE>. Interface contract: <CONTRACT>. Follow the declared write scope. Implement the change and its regression tests together; run the relevant checks. Report changed paths, command results, and blockers. If the plan conflicts with the code or requires another slice's files, stop and report evidence rather than inventing a new scope.",
29
31
  "scope": { "paths": ["src/adapters", "test/adapters"] }
30
32
  },
31
33
  {
32
34
  "id": "gate",
33
35
  "agent": "artisan",
34
36
  "isolation": "shared",
35
- "task": "Challenge the integrated migration using the project's documented required checks and the interface contract. Run the required commands; inspect cross-slice call sites for mismatches. Fix failures caused by this migration within its authorized scope. Report commands, results, and unverified risks.\n\nCore:\n{{apply-core}}\n\nAdapters:\n{{apply-adapters}}",
36
- "dependsOn": ["apply-core", "apply-adapters"]
37
+ "task": "Challenge the integrated migration using the project's documented required checks. Interface contract: <CONTRACT>. Verify both slices meet their done conditions before proceeding; report missing prerequisites instead of guessing. Run the required commands; inspect cross-slice call sites for mismatches. Fix failures caused by this migration within its authorized scope. Report commands, results, and unverified risks.\n\nCore:\n{{apply-core}}\n\nAdapters:\n{{apply-adapters}}",
38
+ "dependsOn": ["apply-core", "apply-adapters"],
39
+ "scope": { "paths": ["src/core", "test/core", "src/adapters", "test/adapters"] }
37
40
  }
38
41
  ]
39
42
  }