@ferris1225/pi-subagents 4.3.34 → 5.0.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 (40) hide show
  1. package/CHANGELOG.md +55 -359
  2. package/README.md +163 -553
  3. package/index.ts +28 -3
  4. package/package.json +2 -2
  5. package/skills/workflow/SKILL.md +46 -29
  6. package/src/configuration/config.ts +15 -5
  7. package/src/configuration/setup.ts +79 -228
  8. package/src/configuration/ui.ts +249 -128
  9. package/src/delegation/agents.ts +4 -3
  10. package/src/delegation/builtin-agents.ts +34 -10
  11. package/src/delegation/dispatch.ts +9 -6
  12. package/src/delegation/prompt.ts +13 -9
  13. package/src/execution/cli-run.ts +404 -0
  14. package/src/execution/process-tree.ts +1 -1
  15. package/src/execution/{rpc-control.ts → run-control.ts} +23 -33
  16. package/src/execution/spawn.ts +33 -185
  17. package/src/isolation/cleanup.ts +174 -0
  18. package/src/isolation/temp-hygiene.ts +2 -26
  19. package/src/lifecycle/cancellation.ts +36 -0
  20. package/src/lifecycle/completion.ts +1 -1
  21. package/src/lifecycle/dispatch-core.ts +0 -1
  22. package/src/lifecycle/durable.ts +5 -1
  23. package/src/lifecycle/runtime.ts +42 -29
  24. package/src/lifecycle/stop.ts +176 -0
  25. package/src/lifecycle/thread-lifecycle.ts +14 -14
  26. package/src/lifecycle/thread-restore.ts +12 -15
  27. package/src/lifecycle/thread-shared.ts +2 -0
  28. package/src/lifecycle/tools.ts +145 -181
  29. package/src/presentation/format.ts +2 -5
  30. package/src/presentation/monitor.ts +16 -1
  31. package/src/presentation/widget.ts +141 -175
  32. package/src/workflow/engine.ts +68 -34
  33. package/src/workflow/files.ts +10 -32
  34. package/src/workflow/plan.ts +61 -13
  35. package/src/workflow/state.ts +4 -3
  36. package/src/workflow/tool.ts +23 -12
  37. package/workflows/code-review.md +15 -10
  38. package/workflows/migration.md +14 -26
  39. package/workflows/research.md +6 -5
  40. package/src/execution/rpc-run.ts +0 -889
@@ -1,204 +1,170 @@
1
- /**
2
- * Compact, glanceable active-run widget for interactive Pi sessions.
3
- *
4
- * Layout contract:
5
- * - Aligned identity columns: `icon #id agent` pad to the widest displayed
6
- * id and agent so every label starts at the same column.
7
- * - A live run owns two lines. Line 1 is what it is: identity, task label,
8
- * then the telemetry flow (worktree, wait state, token flow in the pi-footer
9
- * vocabulary `↑in ↓out R/W cache`, cost, `provider/model`, effective
10
- * `think:<level>`, seconds-precision elapsed). Line 2 is the current activity,
11
- * dim and indented under the label column behind a `↳` marker.
12
- * - Telemetry drops leftmost-first under width pressure (badge, wait, usage,
13
- * model, thinking); the elapsed survives every width.
14
- * - Queued rows say what they actually wait for ("queued" for a process slot,
15
- * "repo lane" for shared-writer serialization, "starting" while the child
16
- * process launches) instead of one catch-all "queued".
17
- */
1
+ /** A compact task board: overview, workflow groups, then actionable run rows. */
18
2
 
3
+ import type { WorkflowRun, WorkflowNodeRun } from "../workflow/state.ts";
19
4
  import type { ExtensionContext, Theme } from "@earendil-works/pi-coding-agent";
20
5
  import { truncateToWidth, visibleWidth } from "@earendil-works/pi-tui";
21
6
  import {
22
- formatElapsed,
23
- formatTaskSummary,
24
- formatUsageCompact,
25
- isRunActiveStatus,
26
- monitor,
27
- shrinkRunLabel,
28
- statusIcon,
29
- type RunView,
7
+ formatElapsed, formatDuration, formatTaskSummary, formatUsageCompact,
8
+ isRunActiveStatus, monitor, statusIcon, type RunView,
30
9
  } from "./monitor.ts";
31
10
 
32
11
  const SUBAGENTS_WIDGET_ID = "pi-subagents";
33
-
34
- /** The TUI caps string-array widgets at this many lines; a factory widget owns
35
- * the same bound itself, or a wide parallel dispatch floods the editor area. */
36
12
  const MAX_WIDGET_LINES = 10;
37
-
38
13
  const SEPARATOR = " · ";
39
- /** Column gap between the identity block and the run's label. */
40
- const IDENTITY_GAP = " ";
41
- /** Marker introducing the live-activity second line of a running row. */
42
- const ACTIVITY_MARKER = "↳ ";
43
- /** Columns kept for left content before right-tail parts are dropped. */
44
- const LEFT_MIN_CONTENT = 8;
45
- /** Minimum useful width for a live-activity fragment. */
46
- const ACTIVITY_MIN_WIDTH = 6;
47
-
48
- /** Shared column widths so every visible row lines up. */
49
- interface ColumnLayout {
50
- /** Display width of the widest `#id` among rendered roots. */
51
- idWidth: number;
52
- /** Display width of the widest agent name among rendered runs. */
53
- agentWidth: number;
54
- }
55
-
56
- /** Join left content and telemetry inline — `left · telemetry` — so a
57
- * multi-line chain reads as one flowing sentence instead of leaving blank
58
- * padding across the width; the whole line truncates as a last resort. */
59
- function composeLine(left: string, tail: string, theme: Theme, width: number): string {
60
- if (!tail) return truncateToWidth(left, width, "…");
61
- const line = `${left}${theme.fg("dim", SEPARATOR)}${theme.fg("dim", tail)}`;
62
- return visibleWidth(line) <= width ? line : truncateToWidth(line, width, "…");
63
- }
64
14
 
65
- /** Short truthful wait word for a queued row — shown in the widget telemetry
66
- * column and aggregated into the footer status line, so both surfaces name a
67
- * wait the same way. */
68
15
  function waitWord(run: Pick<RunView, "waitReason">): string {
69
- switch (run.waitReason) {
70
- case "repository-lane":
71
- return "repo lane";
72
- case "starting":
73
- return "starting";
74
- default:
75
- return "queued";
76
- }
16
+ return run.waitReason === "repository-lane" ? "repo lane" : run.waitReason === "starting" ? "starting" : "queued";
77
17
  }
78
18
 
79
- /** Worktree-group badge shown on the row that owns the isolated worktree: the
80
- * short group identity plus its integration state, so a run visibly moves
81
- * through applying → applied (or retained). */
82
- function worktreeBadge(run: RunView): string {
83
- const id = run.worktreeId ?? "?";
84
- switch (run.integrationStatus) {
85
- case "finalizing":
86
- return `worktree:${id} applying`;
87
- case "integrated":
88
- return `worktree:${id} applied`;
89
- case "no_changes":
90
- return `worktree:${id} clean`;
91
- case "retained":
92
- return `worktree:${id} retained`;
93
- default:
94
- return `worktree:${id}`;
95
- }
19
+ function worktreeBadge(run: RunView): string | undefined {
20
+ if (run.isolation !== "worktree") return undefined;
21
+ const state = run.integrationStatus;
22
+ const suffix = state === "finalizing" ? "applying" : state === "integrated" ? "applied"
23
+ : state === "no_changes" ? "clean" : state === "retained" ? "retained" : undefined;
24
+ return "worktree:" + (run.worktreeId ?? "?") + (suffix ? " " + suffix : "");
96
25
  }
97
26
 
98
- /** Drop lower-priority tail parts (leftmost first) until the tail fits. */
99
- function composeTail(parts: Array<string | undefined>, budget: number): string {
100
- const present = parts.filter((part): part is string => Boolean(part));
101
- while (present.length > 0 && visibleWidth(present.join(SEPARATOR)) > budget) present.shift();
102
- return present.join(SEPARATOR);
27
+ /** Reserve the right edge for progress/time before truncating the task name. */
28
+ function splitLine(left: string, right: string, theme: Theme, width: number): string {
29
+ if (!right) return truncateToWidth(left, width, "…");
30
+ const budget = width - visibleWidth(right) - 2;
31
+ if (budget < 1) return truncateToWidth(theme.fg("dim", right), width, "…");
32
+ const clipped = truncateToWidth(left, budget, "…");
33
+ return clipped + " ".repeat(width - visibleWidth(clipped) - visibleWidth(right)) + theme.fg("dim", right);
103
34
  }
104
35
 
105
- /** Fixed identity columns; labels begin at the same display column. */
106
- function identitySegment(run: RunView, theme: Theme, layout: ColumnLayout): string {
107
- const icon = statusIcon(run.status, theme);
108
- const id = `#${run.id}`.padStart(layout.idWidth);
109
- const name = theme.fg("accent", theme.bold(run.agent));
110
- const pad = " ".repeat(Math.max(0, layout.agentWidth - visibleWidth(run.agent)));
111
- return `${icon} ${theme.fg("dim", id)} ${name}${pad}`;
36
+ interface TaskRow {
37
+ primary: string;
38
+ detail?: string;
39
+ /** Errors first, then active work, queue/dependency waits, then settled. */
40
+ priority: number;
41
+ state: string;
42
+ }
43
+ interface TaskGroup {
44
+ header?: string;
45
+ rows: TaskRow[];
46
+ priority: number;
112
47
  }
113
48
 
114
- /** Telemetry tail parts of a run row: badge and wait word first (dropped first
115
- * under pressure), then usage, model, effective thinking strength, and the
116
- * always-surviving elapsed time. */
117
- function telemetryTailParts(run: RunView, now: number): Array<string | undefined> {
118
- // Queued rows omit model and thinking because the route is re-resolved at actual start.
119
- // The full provider/model ref is kept — "which provider served this run" is
120
- // exactly what a multi-provider session needs to see.
121
- const modelPart = run.status === "queued" || !run.model ? undefined : run.model;
122
- const thinkingPart = run.status === "queued" || !run.thinking ? undefined : `think:${run.thinking}`;
123
- const badge = run.isolation === "worktree" ? worktreeBadge(run) : undefined;
124
- const wait = run.status === "queued" ? waitWord(run) : undefined;
125
- // Drop order under pressure: badge, wait word, usage, model, thinking; elapsed
126
- // survives every width the identity leaves room for.
127
- // Token flow plus accrued cost drop as one unit before the model.
128
- return [badge, wait, formatUsageCompact(run.usage) || undefined, modelPart, thinkingPart, formatElapsed(run, now) || undefined];
49
+ function metadata(run: RunView): string[] {
50
+ return [run.model, run.thinking ? "think:" + run.thinking : undefined,
51
+ formatUsageCompact(run.usage), worktreeBadge(run)].filter((part): part is string => Boolean(part));
129
52
  }
130
53
 
131
- /** Two lines for a live run. Line 1 is what the run is: identity, task label,
132
- * then telemetry (worktree badge, wait state, token flow, cost, provider/model,
133
- * effective thinking, elapsed). Line 2 is the current activity, dim and indented
134
- * under the label column behind a `↳` marker. The
135
- * label takes the full content budget on line 1; the identity and the elapsed
136
- * survive every width. */
137
- function primaryLine(
138
- run: RunView,
139
- theme: Theme,
140
- width: number,
141
- now: number,
142
- layout: ColumnLayout,
143
- ): string[] {
144
- const identity = identitySegment(run, theme, layout);
145
- const tailBudget = Math.max(0, width - visibleWidth(identity) - LEFT_MIN_CONTENT);
146
- const tail = composeTail(telemetryTailParts(run, now), tailBudget);
54
+ function runRow(run: RunView, theme: Theme, width: number, now: number): TaskRow {
55
+ const state = run.status === "queued" ? waitWord(run) : run.integrationStatus === "finalizing" ? "applying" : run.status;
147
56
  const label = run.label ?? formatTaskSummary(run.task, 48);
148
- const contentBudget = width
149
- - visibleWidth(identity)
150
- - (tail ? visibleWidth(tail) + visibleWidth(SEPARATOR) : 0)
151
- - visibleWidth(IDENTITY_GAP);
152
- // The label is already fragment-extracted (runLabel); narrowing it keeps
153
- // its tail so a second squeeze never trades away the recognisable
154
- // filename, and no second head…tail ellipsis stacks on top of it.
155
- const content = label && contentBudget > 0 ? shrinkRunLabel(label, contentBudget) : "";
156
- const left = content ? `${identity}${IDENTITY_GAP}${content}` : identity;
157
- const lines = [composeLine(left, tail, theme, width)];
158
-
159
- const activity = run.status === "running" || run.status === "interrupting"
160
- ? run.activity?.trim()
161
- : undefined;
162
- if (activity) {
163
- const indent = visibleWidth(identity) + visibleWidth(IDENTITY_GAP);
164
- const activityBudget = width - indent - visibleWidth(ACTIVITY_MARKER);
165
- if (activityBudget >= ACTIVITY_MIN_WIDTH) {
166
- lines.push(
167
- `${" ".repeat(indent)}${theme.fg("dim", `${ACTIVITY_MARKER}${formatTaskSummary(activity, activityBudget)}`)}`,
168
- );
57
+ const identity = statusIcon(run.status, theme) + " " + theme.fg("dim", "#" + run.id) + " " + theme.fg("accent", run.agent);
58
+ const primary = splitLine(identity + " " + label, [state, formatElapsed(run, now)].filter(Boolean).join(SEPARATOR), theme, width);
59
+ const activity = run.activity ? truncateToWidth("↳ " + formatTaskSummary(run.activity, Math.max(8, width - 6)), Math.max(0, width - 4), "…") : "";
60
+ const parts = metadata(run);
61
+ // Keep current activity readable; reveal model, reasoning, usage and isolation
62
+ // as space allows, rather than shrinking the task to make telemetry fit.
63
+ const budget = width - 4 - visibleWidth(activity) - (activity ? visibleWidth(SEPARATOR) : 0);
64
+ while (parts.length && visibleWidth(parts.join(SEPARATOR)) > budget) parts.pop();
65
+ const detail = activity || parts.length ? " " + [activity, ...parts].filter(Boolean).join(SEPARATOR) : undefined;
66
+ return { primary, detail: detail ? theme.fg("dim", truncateToWidth(detail, width, "…")) : undefined,
67
+ priority: run.status === "failed" ? 0 : run.status === "interrupting" ? 1 : run.status === "running" ? 2 : 3, state: run.status };
68
+ }
69
+
70
+ /** Budget task identities before optional detail lines, so a busy run cannot
71
+ * hide a sibling. Error groups and error rows win when the board overflows. */
72
+ function renderBoard(groups: TaskGroup[], theme: Theme, width: number, overview?: string): string[] {
73
+ if (width <= 0 || !groups.length) return [];
74
+ const sorted = [...groups].sort((a, b) => a.priority - b.priority);
75
+ const lines: string[] = overview ? [overview] : [];
76
+ const allRows = sorted.flatMap((group) => group.rows);
77
+ const headers = sorted.filter((group) => group.header).length;
78
+ const needsOverflow = lines.length + headers + allRows.length > MAX_WIDGET_LINES;
79
+ const capacity = MAX_WIDGET_LINES - lines.length - (needsOverflow ? 1 : 0);
80
+ // Select across groups before rendering, reserving one header per visible graph.
81
+ const selected = new Set<TaskRow>();
82
+ const included = new Set<TaskGroup>();
83
+ let used = 0;
84
+ const candidates = sorted.flatMap((group) => [...group.rows].sort((a, b) => a.priority - b.priority)
85
+ .map((row, index) => ({ group, row, index })));
86
+ candidates.sort((a, b) => a.row.priority - b.row.priority || a.index - b.index);
87
+ for (const { group, row } of candidates) {
88
+ const cost = 1 + (!included.has(group) && group.header ? 1 : 0);
89
+ if (used + cost > capacity) continue;
90
+ included.add(group);
91
+ selected.add(row);
92
+ used += cost;
93
+ }
94
+ // Completed graphs still report their progress without listing every completed node.
95
+ for (const group of sorted) {
96
+ if (!group.rows.length && group.header && used < capacity) { included.add(group); used++; }
97
+ }
98
+ let detailBudget = capacity - used;
99
+ for (const group of sorted) {
100
+ if (!included.has(group)) continue;
101
+ if (group.header) lines.push(group.header);
102
+ for (const row of [...group.rows].sort((a, b) => a.priority - b.priority)) {
103
+ if (!selected.has(row)) continue;
104
+ lines.push(row.primary);
105
+ if (row.detail && detailBudget > 0) { lines.push(row.detail); detailBudget--; }
169
106
  }
170
107
  }
171
- return lines;
108
+ const hiddenTasks = allRows.length - selected.size;
109
+ const hiddenGroups = sorted.filter((group) => !included.has(group)).length;
110
+ if (hiddenTasks || hiddenGroups) lines.push(theme.fg("dim", "… +" + hiddenTasks + " tasks" + (hiddenGroups ? " · " + hiddenGroups + " groups hidden" : "")));
111
+ return lines.slice(0, MAX_WIDGET_LINES).map((line) => truncateToWidth(line, width, "…"));
172
112
  }
173
113
 
174
- /** Render active runs as compact per-run line groups: one two-line group per
175
- * run. All rows share one column layout. */
176
- export function formatActiveRunLines(
177
- runs: readonly RunView[],
178
- theme: Theme,
179
- width: number,
180
- now: number = Date.now(),
114
+ export function formatActiveRunLines(runs: readonly RunView[], theme: Theme, width: number, now = Date.now()): string[] {
115
+ const rows = runs.filter((run) => isRunActiveStatus(run.status)).map((run) => runRow(run, theme, width, now));
116
+ return rows.length ? renderBoard([{ rows, priority: 2 }], theme, width) : [];
117
+ }
118
+
119
+ function workflowGroup(graph: WorkflowRun, runs: readonly RunView[], theme: Theme, width: number, now: number): TaskGroup {
120
+ const count = (state: WorkflowNodeRun["state"]) => graph.nodes.filter((node) => node.state === state).length;
121
+ const completed = count("completed");
122
+ const progress = completed + "/" + graph.nodes.length + " completed";
123
+ const color = graph.state === "failed" ? "error" : graph.state === "completed" ? "success" : "accent";
124
+ const name = theme.fg(color, theme.bold("Workflow #" + graph.id + " · " + graph.name));
125
+ const parts = [progress, ...(["failed", "blocked", "pending"] as const).filter((state) => count(state))
126
+ .map((state) => count(state) + " " + (state === "pending" ? "waiting" : state))];
127
+ const tail = width >= 100 ? parts.join(SEPARATOR) : progress + SEPARATOR + graph.state;
128
+ const rows = graph.nodes.filter((node) => node.state !== "completed" && node.state !== "stopped").map((node): TaskRow => {
129
+ const live = runs.find((run) => run.id === node.runId);
130
+ const waitingOn = node.dependsOn.filter((id) => graph.nodes.find((dependency) => dependency.id === id)?.state !== "completed");
131
+ const state = node.state === "pending" ? "waiting" : node.state === "running" && live?.status === "queued" ? "queued" : node.state;
132
+ const detail = node.state === "pending" ? waitingOn.length ? "waits for " + waitingOn.join(", ") : "ready"
133
+ : node.error ? node.state + ": " + formatTaskSummary(node.error, 100, false)
134
+ : live?.status === "queued" ? waitWord(live)
135
+ : live?.integrationStatus === "finalizing" ? "integrating worktree"
136
+ : live?.activity ?? node.state;
137
+ const iconState = node.state === "pending" ? "queued" : node.state === "failed" || node.state === "blocked" ? "failed" : live?.status ?? "running";
138
+ const identity = " " + statusIcon(iconState, theme) + " " + theme.fg("accent", node.id) + theme.fg("dim", " · " + node.agent + (node.runId === undefined ? "" : " #" + node.runId));
139
+ const elapsed = node.startedAt === undefined ? "" : formatDuration((node.endedAt ?? now) - node.startedAt);
140
+ const primary = splitLine(identity + " · " + theme.fg(node.error ? "error" : "dim", detail), elapsed, theme, width);
141
+ const meta = live ? metadata(live).join(SEPARATOR) : "";
142
+ return { primary, detail: meta ? theme.fg("dim", " " + meta) : undefined,
143
+ priority: node.state === "failed" ? 0 : node.state === "blocked" ? 1 : node.state === "running" ? 2 : 3, state };
144
+ });
145
+ return { header: splitLine(name, tail, theme, width), rows, priority: rows.length ? Math.min(...rows.map((row) => row.priority)) : 4 };
146
+ }
147
+
148
+ export function formatSubagentWidgetLines(
149
+ runs: readonly RunView[], workflows: readonly WorkflowRun[], theme: Theme, width: number, now = Date.now(),
181
150
  ): string[] {
182
- const active = runs.filter((run) => isRunActiveStatus(run.status));
183
- const layout: ColumnLayout = {
184
- idWidth: Math.max(...active.map((run) => visibleWidth(`#${run.id}`)), 0),
185
- agentWidth: Math.max(...active.map((run) => visibleWidth(run.agent)), 0),
186
- };
187
- const lines: string[] = [];
188
- let shown = 0;
189
- for (const run of active) {
190
- // Reserve one line so a cut is always announced by the overflow marker.
191
- const remaining = MAX_WIDGET_LINES - 1 - lines.length;
192
- if (remaining <= 0) break;
193
- const group = primaryLine(run, theme, width, now, layout);
194
- lines.push(...group.slice(0, remaining));
195
- shown++;
196
- }
197
- const hidden = active.length - shown;
198
- if (hidden > 0) {
199
- lines.push(theme.fg("dim", `… +${hidden} more`));
151
+ if (width <= 0) return [];
152
+ const graphIds = new Set(workflows.map((graph) => graph.id));
153
+ const visibleWorkflows = workflows.filter((graph) => graph.state !== "stopped");
154
+ const standalone = runs.filter((run) => (!run.workflow || !graphIds.has(run.workflow.workflowId)) && (isRunActiveStatus(run.status) || run.status === "failed"));
155
+ const groups = visibleWorkflows.map((graph) => workflowGroup(graph, runs, theme, width, now));
156
+ if (standalone.length) {
157
+ const rows = standalone.map((run) => runRow(run, theme, width, now));
158
+ groups.push({ rows, priority: Math.min(...rows.map((row) => row.priority)) });
200
159
  }
201
- return lines;
160
+ if (!groups.length) return [];
161
+ const states = groups.flatMap((group) => group.rows.map((row) => row.state));
162
+ const counts = ["failed", "blocked", "interrupting", "running", "queued", "waiting"]
163
+ .map((state) => ({ state, count: states.filter((value) => value === state).length }))
164
+ .filter(({ count }) => count > 0).map(({ state, count }) => count + " " + state);
165
+ if (visibleWorkflows.length) counts.push(visibleWorkflows.length + " workflow" + (visibleWorkflows.length === 1 ? "" : "s"));
166
+ const overview = theme.fg("accent", theme.bold("Subagents")) + theme.fg("dim", " " + counts.join(SEPARATOR));
167
+ return renderBoard(groups, theme, width, overview);
202
168
  }
203
169
 
204
170
  function hasActiveRun(): boolean {
@@ -217,7 +183,7 @@ export function installActiveRunsWidget(ctx: Pick<ExtensionContext, "mode" | "ui
217
183
 
218
184
  const syncTimer = (): void => {
219
185
  if (disposed) return;
220
- if (hasActiveRun()) {
186
+ if (hasActiveRun() || monitor.getWorkflows().some((graph) => graph.state === "running")) {
221
187
  if (timer) return;
222
188
  timer = setInterval(() => tui.requestRender(), 1_000);
223
189
  timer.unref?.();
@@ -234,7 +200,7 @@ export function installActiveRunsWidget(ctx: Pick<ExtensionContext, "mode" | "ui
234
200
  syncTimer();
235
201
 
236
202
  return {
237
- render: (width: number) => formatActiveRunLines(monitor.getRuns(), theme, width, Date.now()),
203
+ render: (width: number) => formatSubagentWidgetLines(monitor.getRuns(), monitor.getWorkflows(), theme, width, Date.now()),
238
204
  invalidate() {},
239
205
  dispose() {
240
206
  disposed = true;
@@ -16,12 +16,13 @@
16
16
  */
17
17
 
18
18
  import { isFailedResult, getResultError, getResultOutput, truncateResultOutput, writeResultArtifact, type SingleResult } from "../execution/spawn.ts";
19
- import { formatDuration, formatTaskSummary, monitor } from "../presentation/monitor.ts";
19
+ import { formatDuration, formatTaskSummary, monitor, runWaitLabel } from "../presentation/monitor.ts";
20
20
  import { perModelTotals, type CompletionMessageItem } from "../lifecycle/completion.ts";
21
- import type { SubagentRuntime } from "../lifecycle/runtime.ts";
21
+ import { findPendingWorkflowPhase, type SubagentRuntime } from "../lifecycle/runtime.ts";
22
22
  import type { StartBackgroundInternal } from "../lifecycle/thread-shared.ts";
23
+ import { stopThreads } from "../lifecycle/stop.ts";
23
24
  import { findDuplicateDispatch } from "../delegation/prompt.ts";
24
- import { defaultPhaseId, renderNodeTask, type CompiledWorkflow, type UpstreamOutput } from "./plan.ts";
25
+ import { defaultPhaseId, renderNodeTask, UPSTREAM_OUTPUT_MAX_CHARS, type CompiledWorkflow, type UpstreamOutput } from "./plan.ts";
25
26
  import {
26
27
  readWorkflowRecords,
27
28
  removeWorkflowRecord,
@@ -81,6 +82,7 @@ function upstreamView(node: WorkflowNodeRun): UpstreamOutput {
81
82
  output,
82
83
  ...(node.runId !== undefined ? { runId: node.runId } : {}),
83
84
  ...(node.error ? { error: node.error } : {}),
85
+ ...(result?.resultFile ? { resultFile: result.resultFile } : {}),
84
86
  };
85
87
  }
86
88
 
@@ -133,17 +135,16 @@ function waitForNodeSettlement(
133
135
  async function dispatchNode(ctx: RunContext, node: WorkflowNodeRun): Promise<void> {
134
136
  const { run } = ctx;
135
137
  const upstream = new Map<string, UpstreamOutput>();
136
- for (const dependency of node.dependsOn) {
138
+ for (const dependency of node.ancestors) {
137
139
  const upstreamNode = nodeById(run, dependency);
138
140
  if (upstreamNode) upstream.set(dependency, upstreamView(upstreamNode));
139
141
  }
140
142
  const task = renderNodeTask(node.task, upstream);
141
- node.dispatchedTask = task;
142
143
  node.state = "running";
143
144
  node.startedAt = Date.now();
144
145
  let started: SingleResult;
145
146
  try {
146
- started = await ctx.startBackground(node.agent, task, node.cwd, ctx.resolveIsolation(node.agent), {
147
+ started = await ctx.startBackground(node.agent, task, node.cwd, node.isolation ?? ctx.resolveIsolation(node.agent), {
147
148
  phaseId: node.phaseId,
148
149
  scope: node.scope,
149
150
  deliveryRoute: "background",
@@ -166,10 +167,20 @@ async function dispatchNode(ctx: RunContext, node: WorkflowNodeRun): Promise<voi
166
167
  return;
167
168
  }
168
169
  node.runId = started.runId;
170
+ await checkpoint(ctx);
171
+ if (run.state === "stopped") await stopThreads(ctx.runtime, [started.runId], run.stopReason);
169
172
  const result = await waitForNodeSettlement(ctx.runtime, started.runId, run.controller.signal);
170
173
  node.endedAt = Date.now();
171
174
  node.result = result;
175
+ if (result && getResultOutput(result).length > UPSTREAM_OUTPUT_MAX_CHARS && !result.resultFile) {
176
+ try {
177
+ result.resultFile = writeResultArtifact(getResultOutput(result), `workflow-${run.slug}-${node.id}`, ctx.resultsRoot);
178
+ } catch {
179
+ /* The dependent brief explicitly reports an unavailable full answer. */
180
+ }
181
+ }
172
182
  if (run.state !== "running") {
183
+ if (result && !isFailedResult(result)) { node.state = "completed"; return; }
173
184
  node.state = "stopped";
174
185
  node.error ??= run.stopReason ?? "workflow stopped";
175
186
  return;
@@ -209,10 +220,18 @@ function blockDependents(run: WorkflowRun): boolean {
209
220
  return changed;
210
221
  }
211
222
 
223
+ async function checkpoint(ctx: RunContext): Promise<void> {
224
+ if (ctx.runtime.sessionActive) monitor.updateWorkflow(ctx.run);
225
+ if (ctx.run.state !== "running") return;
226
+ await upsertWorkflowRecord(ctx.runtime.configPath, workflowRecord(ctx.run, "running")).catch(() => undefined);
227
+ }
228
+
212
229
  async function drive(ctx: RunContext): Promise<void> {
213
230
  const { run } = ctx;
231
+ const inFlight = new Set<Promise<void>>();
232
+ await checkpoint(ctx);
214
233
  while (run.state === "running") {
215
- blockDependents(run);
234
+ while (blockDependents(run)) { /* Propagate through any author order. */ }
216
235
  const ready = run.nodes.filter(
217
236
  (node) =>
218
237
  node.state === "pending" &&
@@ -221,7 +240,16 @@ async function drive(ctx: RunContext): Promise<void> {
221
240
  for (const node of ready) {
222
241
  // dispatchNode marks the node running synchronously, so the next pass
223
242
  // cannot start it twice.
224
- void dispatchNode(ctx, node).finally(ctx.wake);
243
+ const task = dispatchNode(ctx, node).catch((error: unknown) => {
244
+ node.state = "failed";
245
+ node.error = error instanceof Error ? error.message : String(error);
246
+ node.endedAt = Date.now();
247
+ }).finally(async () => {
248
+ await checkpoint(ctx);
249
+ inFlight.delete(task);
250
+ ctx.wake();
251
+ });
252
+ inFlight.add(task);
225
253
  }
226
254
  if (run.state !== "running") break;
227
255
  const running = run.nodes.some((node) => node.state === "running");
@@ -230,6 +258,7 @@ async function drive(ctx: RunContext): Promise<void> {
230
258
  // marked blocked frees the pass); wait for one wake-up instead of polling.
231
259
  await ctx.waitForWake();
232
260
  }
261
+ await Promise.all(inFlight);
233
262
  await settle(ctx);
234
263
  }
235
264
 
@@ -287,6 +316,10 @@ export function formatWorkflowReport(run: WorkflowRun): string {
287
316
  const output = node.result ? getResultOutput(node.result).trim() : "";
288
317
  lines.push("", `## ${node.id} (${node.agent}) — ${nodeStateWord(node)}`, "");
289
318
  lines.push(output || "(no answer recorded)");
319
+ if (node.error) lines.push("", `Error: ${node.error}`);
320
+ for (const [label, path] of [["Full result", node.result?.resultFile], ["Retained worktree", node.result?.integrationWorktreePath], ["Retained patch", node.result?.integrationPatchPath]]) {
321
+ if (path) lines.push(`${label}: ${path}`);
322
+ }
290
323
  }
291
324
  return lines.join("\n");
292
325
  }
@@ -334,8 +367,8 @@ export function formatWorkflowSummary(run: WorkflowRun, resultsRoot?: string): s
334
367
  try {
335
368
  const reportPath = writeResultArtifact(formatWorkflowReport(run), `workflow-${run.slug}`, resultsRoot);
336
369
  lines.push(`⚠ Some node answers are clipped here. Read the complete report, including every node's full answer: ${reportPath}`);
337
- } catch {
338
- /* the summary is still useful without the artifact pointer */
370
+ } catch (error) {
371
+ lines.push(`⚠ The full report could not be written: ${error instanceof Error ? error.message : String(error)}. Inspect retained run evidence before relying on clipped answers.`);
339
372
  }
340
373
  }
341
374
  const totals = perModelTotals(
@@ -381,9 +414,10 @@ async function settle(ctx: RunContext): Promise<void> {
381
414
  // it is the evidence the next session explains, not a settled run.
382
415
  const interrupted = run.state === "interrupted";
383
416
  if (run.state === "running") {
384
- run.state = run.nodes.some((node) => node.state === "failed" || node.state === "blocked") ? "failed" : "completed";
417
+ run.state = run.nodes.some((node) => node.state !== "completed") ? "failed" : "completed";
385
418
  }
386
419
  run.endedAt ??= Date.now();
420
+ if (runtime.sessionActive) monitor.updateWorkflow(run);
387
421
  if (!interrupted) await removeWorkflowRecord(runtime.configPath, run.id, run.cwd).catch(() => undefined);
388
422
  if (!runtime.sessionActive) return;
389
423
  const item: CompletionMessageItem = {
@@ -399,7 +433,9 @@ async function settle(ctx: RunContext): Promise<void> {
399
433
  export interface OwnedPhase {
400
434
  nodeId: string;
401
435
  phaseId: string;
402
- runId: number;
436
+ runId?: number;
437
+ workflowId?: number;
438
+ ownerNodeId?: string;
403
439
  agent: string;
404
440
  state: string;
405
441
  }
@@ -417,7 +453,11 @@ export function findOwnedPhases(runtime: SubagentRuntime, workflow: CompiledWork
417
453
  for (const node of workflow.nodes) {
418
454
  const phaseId = node.phaseId ?? defaultPhaseId(workflow, node);
419
455
  const duplicate = findDuplicateDispatch(runtime.threads.values(), node.task, node.cwd, phaseId);
420
- if (!duplicate) continue;
456
+ if (!duplicate) {
457
+ const pending = findPendingWorkflowPhase(runtime, node.task, node.cwd, phaseId);
458
+ if (pending) owned.push({ nodeId: node.id, phaseId, workflowId: pending.workflowId, ownerNodeId: pending.nodeId, agent: pending.agent, state: "pending" });
459
+ continue;
460
+ }
421
461
  owned.push({
422
462
  nodeId: node.id,
423
463
  phaseId,
@@ -443,10 +483,11 @@ export function startWorkflow(deps: WorkflowRunDeps, workflow: CompiledWorkflow)
443
483
  controller: new AbortController(),
444
484
  nodes: workflow.nodes.map((node) => ({
445
485
  id: node.id,
446
- index: node.index,
447
486
  agent: node.agent,
448
487
  task: node.task,
449
488
  dependsOn: [...node.dependsOn],
489
+ ancestors: [...node.ancestors],
490
+ ...(node.isolation ? { isolation: node.isolation } : {}),
450
491
  phaseId: node.phaseId ?? defaultPhaseId(workflow, node),
451
492
  ...(node.scope ? { scope: node.scope } : {}),
452
493
  cwd: node.cwd,
@@ -494,6 +535,7 @@ export function startWorkflow(deps: WorkflowRunDeps, workflow: CompiledWorkflow)
494
535
  return run;
495
536
  },
496
537
  );
538
+ run.done = done;
497
539
  return { run, done };
498
540
  }
499
541
 
@@ -507,26 +549,17 @@ export async function stopWorkflow(
507
549
  if (run.state !== "running" && run.state !== "interrupted") return [];
508
550
  run.state = "stopped";
509
551
  run.stopReason = reason;
510
- run.controller.abort();
511
- const cancelled: number[] = [];
512
- const stopping: Array<Promise<void>> = [];
513
552
  for (const node of run.nodes) {
514
- if (node.state === "pending") {
515
- node.state = "stopped";
516
- node.error = "stopped before it started";
517
- continue;
518
- }
519
- if (node.state !== "running") continue;
520
- if (node.runId === undefined) {
521
- node.state = "stopped";
522
- continue;
523
- }
524
- const thread = runtime.threads.get(node.runId);
525
- stopping.push(thread ? thread.control.stop(reason).catch(() => undefined) : Promise.resolve());
526
- runtime.backgroundQueue.cancel(thread?.queueController ?? runtime.runControllers.get(node.runId));
527
- cancelled.push(node.runId);
553
+ if (node.state !== "pending") continue;
554
+ node.state = "stopped";
555
+ node.error = "stopped before it started";
528
556
  }
529
- await Promise.all(stopping);
557
+ monitor.updateWorkflow(run);
558
+ const cancelled = run.nodes.flatMap((node) => node.state === "running" && node.runId !== undefined ? [node.runId] : []);
559
+ // The same stop owner as the control tool finalizes worktrees before the
560
+ // graph publishes its summary. A late dispatch stops itself on allocation.
561
+ await stopThreads(runtime, cancelled, reason);
562
+ run.controller.abort();
530
563
  return cancelled;
531
564
  }
532
565
 
@@ -539,6 +572,7 @@ export async function persistInterruptedWorkflows(runtime: SubagentRuntime): Pro
539
572
  run.state = "interrupted";
540
573
  run.endedAt = Date.now();
541
574
  run.stopReason ??= "the parent session ended before this workflow settled";
575
+ monitor.updateWorkflow(run);
542
576
  await upsertWorkflowRecord(runtime.configPath, workflowRecord(run, "interrupted")).catch(() => undefined);
543
577
  // Wake the runner's waiters so the graph unwinds instead of holding a
544
578
  // promise past shutdown; settle() keeps the record and skips delivery.
@@ -564,7 +598,7 @@ export async function readRetainedWorkflows(runtime: SubagentRuntime, cwd: strin
564
598
  return records.map((record) => ({
565
599
  id: record.workflowId,
566
600
  name: record.name,
567
- state: record.state,
601
+ state: record.state === "running" ? "interrupted" : record.state,
568
602
  ...(record.stopReason ? { stopReason: record.stopReason } : {}),
569
603
  updatedAt: record.updatedAt,
570
604
  nodes: record.nodes,
@@ -612,7 +646,7 @@ export function workflowStatus(run: WorkflowRun): WorkflowStatusView {
612
646
  ...(node.runId !== undefined ? { runId: node.runId } : {}),
613
647
  ...(node.state === "pending" && node.dependsOn.length > 0 ? { waitingFor: [...node.dependsOn] } : {}),
614
648
  ...(node.error ? { error: node.error } : {}),
615
- ...(live?.activity ? { activity: live.activity } : {}),
649
+ ...(live?.status === "queued" ? { activity: runWaitLabel(live) } : live?.integrationStatus === "finalizing" ? { activity: "integrating worktree" } : live?.activity ? { activity: live.activity } : {}),
616
650
  ...(node.startedAt !== undefined ? { elapsedMs: (node.endedAt ?? Date.now()) - node.startedAt } : {}),
617
651
  };
618
652
  }),