@ferris1225/pi-subagents 4.3.33 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +32 -349
  2. package/README.md +130 -549
  3. package/index.ts +4 -2
  4. package/package.json +1 -1
  5. package/skills/workflow/SKILL.md +52 -31
  6. package/src/configuration/config.ts +4 -4
  7. package/src/configuration/setup.ts +88 -229
  8. package/src/configuration/ui.ts +107 -129
  9. package/src/delegation/builtin-agents.ts +9 -9
  10. package/src/delegation/dispatch.ts +9 -6
  11. package/src/delegation/prompt.ts +7 -8
  12. package/src/execution/cli-run.ts +364 -0
  13. package/src/execution/process-tree.ts +1 -1
  14. package/src/execution/{rpc-control.ts → run-control.ts} +15 -33
  15. package/src/execution/spawn.ts +33 -185
  16. package/src/isolation/temp-hygiene.ts +2 -3
  17. package/src/lifecycle/cancellation.ts +36 -0
  18. package/src/lifecycle/completion.ts +1 -1
  19. package/src/lifecycle/dispatch-core.ts +0 -1
  20. package/src/lifecycle/durable.ts +1 -1
  21. package/src/lifecycle/runtime.ts +42 -29
  22. package/src/lifecycle/stop.ts +175 -0
  23. package/src/lifecycle/thread-lifecycle.ts +21 -15
  24. package/src/lifecycle/thread-restore.ts +3 -3
  25. package/src/lifecycle/tools.ts +18 -173
  26. package/src/presentation/format.ts +2 -5
  27. package/src/presentation/monitor.ts +16 -1
  28. package/src/presentation/widget.ts +140 -175
  29. package/src/workflow/engine.ts +101 -32
  30. package/src/workflow/files.ts +10 -32
  31. package/src/workflow/plan.ts +61 -13
  32. package/src/workflow/state.ts +4 -3
  33. package/src/workflow/tool.ts +38 -10
  34. package/workflows/code-review.md +12 -7
  35. package/workflows/migration.md +14 -26
  36. package/workflows/research.md +6 -5
  37. package/src/execution/rpc-run.ts +0 -889
@@ -1,204 +1,169 @@
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 standalone = runs.filter((run) => (!run.workflow || !graphIds.has(run.workflow.workflowId)) && (isRunActiveStatus(run.status) || run.status === "failed"));
154
+ const groups = workflows.map((graph) => workflowGroup(graph, runs, theme, width, now));
155
+ if (standalone.length) {
156
+ const rows = standalone.map((run) => runRow(run, theme, width, now));
157
+ groups.push({ rows, priority: Math.min(...rows.map((row) => row.priority)) });
200
158
  }
201
- return lines;
159
+ if (!groups.length) return [];
160
+ const states = groups.flatMap((group) => group.rows.map((row) => row.state));
161
+ const counts = ["failed", "blocked", "interrupting", "running", "queued", "waiting"]
162
+ .map((state) => ({ state, count: states.filter((value) => value === state).length }))
163
+ .filter(({ count }) => count > 0).map(({ state, count }) => count + " " + state);
164
+ if (workflows.length) counts.push(workflows.length + " workflow" + (workflows.length === 1 ? "" : "s"));
165
+ const overview = theme.fg("accent", theme.bold("Subagents")) + theme.fg("dim", " " + counts.join(SEPARATOR));
166
+ return renderBoard(groups, theme, width, overview);
202
167
  }
203
168
 
204
169
  function hasActiveRun(): boolean {
@@ -217,7 +182,7 @@ export function installActiveRunsWidget(ctx: Pick<ExtensionContext, "mode" | "ui
217
182
 
218
183
  const syncTimer = (): void => {
219
184
  if (disposed) return;
220
- if (hasActiveRun()) {
185
+ if (hasActiveRun() || monitor.getWorkflows().some((graph) => graph.state === "running")) {
221
186
  if (timer) return;
222
187
  timer = setInterval(() => tui.requestRender(), 1_000);
223
188
  timer.unref?.();
@@ -234,7 +199,7 @@ export function installActiveRunsWidget(ctx: Pick<ExtensionContext, "mode" | "ui
234
199
  syncTimer();
235
200
 
236
201
  return {
237
- render: (width: number) => formatActiveRunLines(monitor.getRuns(), theme, width, Date.now()),
202
+ render: (width: number) => formatSubagentWidgetLines(monitor.getRuns(), monitor.getWorkflows(), theme, width, Date.now()),
238
203
  invalidate() {},
239
204
  dispose() {
240
205
  disposed = true;
@@ -16,11 +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 { defaultPhaseId, renderNodeTask, type CompiledWorkflow, type UpstreamOutput } from "./plan.ts";
23
+ import { stopThreads } from "../lifecycle/stop.ts";
24
+ import { findDuplicateDispatch } from "../delegation/prompt.ts";
25
+ import { defaultPhaseId, renderNodeTask, UPSTREAM_OUTPUT_MAX_CHARS, type CompiledWorkflow, type UpstreamOutput } from "./plan.ts";
24
26
  import {
25
27
  readWorkflowRecords,
26
28
  removeWorkflowRecord,
@@ -80,6 +82,7 @@ function upstreamView(node: WorkflowNodeRun): UpstreamOutput {
80
82
  output,
81
83
  ...(node.runId !== undefined ? { runId: node.runId } : {}),
82
84
  ...(node.error ? { error: node.error } : {}),
85
+ ...(result?.resultFile ? { resultFile: result.resultFile } : {}),
83
86
  };
84
87
  }
85
88
 
@@ -132,17 +135,16 @@ function waitForNodeSettlement(
132
135
  async function dispatchNode(ctx: RunContext, node: WorkflowNodeRun): Promise<void> {
133
136
  const { run } = ctx;
134
137
  const upstream = new Map<string, UpstreamOutput>();
135
- for (const dependency of node.dependsOn) {
138
+ for (const dependency of node.ancestors) {
136
139
  const upstreamNode = nodeById(run, dependency);
137
140
  if (upstreamNode) upstream.set(dependency, upstreamView(upstreamNode));
138
141
  }
139
142
  const task = renderNodeTask(node.task, upstream);
140
- node.dispatchedTask = task;
141
143
  node.state = "running";
142
144
  node.startedAt = Date.now();
143
145
  let started: SingleResult;
144
146
  try {
145
- 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), {
146
148
  phaseId: node.phaseId,
147
149
  scope: node.scope,
148
150
  deliveryRoute: "background",
@@ -165,10 +167,20 @@ async function dispatchNode(ctx: RunContext, node: WorkflowNodeRun): Promise<voi
165
167
  return;
166
168
  }
167
169
  node.runId = started.runId;
170
+ await checkpoint(ctx);
171
+ if (run.state === "stopped") await stopThreads(ctx.runtime, [started.runId], run.stopReason);
168
172
  const result = await waitForNodeSettlement(ctx.runtime, started.runId, run.controller.signal);
169
173
  node.endedAt = Date.now();
170
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
+ }
171
182
  if (run.state !== "running") {
183
+ if (result && !isFailedResult(result)) { node.state = "completed"; return; }
172
184
  node.state = "stopped";
173
185
  node.error ??= run.stopReason ?? "workflow stopped";
174
186
  return;
@@ -208,10 +220,18 @@ function blockDependents(run: WorkflowRun): boolean {
208
220
  return changed;
209
221
  }
210
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
+
211
229
  async function drive(ctx: RunContext): Promise<void> {
212
230
  const { run } = ctx;
231
+ const inFlight = new Set<Promise<void>>();
232
+ await checkpoint(ctx);
213
233
  while (run.state === "running") {
214
- blockDependents(run);
234
+ while (blockDependents(run)) { /* Propagate through any author order. */ }
215
235
  const ready = run.nodes.filter(
216
236
  (node) =>
217
237
  node.state === "pending" &&
@@ -220,7 +240,16 @@ async function drive(ctx: RunContext): Promise<void> {
220
240
  for (const node of ready) {
221
241
  // dispatchNode marks the node running synchronously, so the next pass
222
242
  // cannot start it twice.
223
- 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);
224
253
  }
225
254
  if (run.state !== "running") break;
226
255
  const running = run.nodes.some((node) => node.state === "running");
@@ -229,6 +258,7 @@ async function drive(ctx: RunContext): Promise<void> {
229
258
  // marked blocked frees the pass); wait for one wake-up instead of polling.
230
259
  await ctx.waitForWake();
231
260
  }
261
+ await Promise.all(inFlight);
232
262
  await settle(ctx);
233
263
  }
234
264
 
@@ -286,6 +316,10 @@ export function formatWorkflowReport(run: WorkflowRun): string {
286
316
  const output = node.result ? getResultOutput(node.result).trim() : "";
287
317
  lines.push("", `## ${node.id} (${node.agent}) — ${nodeStateWord(node)}`, "");
288
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
+ }
289
323
  }
290
324
  return lines.join("\n");
291
325
  }
@@ -333,8 +367,8 @@ export function formatWorkflowSummary(run: WorkflowRun, resultsRoot?: string): s
333
367
  try {
334
368
  const reportPath = writeResultArtifact(formatWorkflowReport(run), `workflow-${run.slug}`, resultsRoot);
335
369
  lines.push(`⚠ Some node answers are clipped here. Read the complete report, including every node's full answer: ${reportPath}`);
336
- } catch {
337
- /* 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.`);
338
372
  }
339
373
  }
340
374
  const totals = perModelTotals(
@@ -380,9 +414,10 @@ async function settle(ctx: RunContext): Promise<void> {
380
414
  // it is the evidence the next session explains, not a settled run.
381
415
  const interrupted = run.state === "interrupted";
382
416
  if (run.state === "running") {
383
- 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";
384
418
  }
385
419
  run.endedAt ??= Date.now();
420
+ if (runtime.sessionActive) monitor.updateWorkflow(run);
386
421
  if (!interrupted) await removeWorkflowRecord(runtime.configPath, run.id, run.cwd).catch(() => undefined);
387
422
  if (!runtime.sessionActive) return;
388
423
  const item: CompletionMessageItem = {
@@ -394,6 +429,46 @@ async function settle(ctx: RunContext): Promise<void> {
394
429
  runtime.sendCompletionGroup([item]);
395
430
  }
396
431
 
432
+ /** A phase a live or retained thread already owns. */
433
+ export interface OwnedPhase {
434
+ nodeId: string;
435
+ phaseId: string;
436
+ runId?: number;
437
+ workflowId?: number;
438
+ ownerNodeId?: string;
439
+ agent: string;
440
+ state: string;
441
+ }
442
+
443
+ /**
444
+ * Phases this session already owns, checked before the graph starts.
445
+ *
446
+ * A phase is owned by the parent session, not by one graph: an interrupted or
447
+ * settled owner keeps its claim until it is retired. Checking every node up
448
+ * front turns "the first node failed and the rest never ran" into one message
449
+ * that names the owners and the way out, at the cost of no child process.
450
+ */
451
+ export function findOwnedPhases(runtime: SubagentRuntime, workflow: CompiledWorkflow): OwnedPhase[] {
452
+ const owned: OwnedPhase[] = [];
453
+ for (const node of workflow.nodes) {
454
+ const phaseId = node.phaseId ?? defaultPhaseId(workflow, node);
455
+ const duplicate = findDuplicateDispatch(runtime.threads.values(), node.task, node.cwd, phaseId);
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
+ }
461
+ owned.push({
462
+ nodeId: node.id,
463
+ phaseId,
464
+ runId: duplicate.source.id,
465
+ agent: duplicate.source.agentName,
466
+ state: duplicate.source.lifecycleOperation === "settle" ? "settling" : duplicate.source.state,
467
+ });
468
+ }
469
+ return owned;
470
+ }
471
+
397
472
  /** Start a compiled graph. Nodes dispatch as their prerequisites settle. */
398
473
  export function startWorkflow(deps: WorkflowRunDeps, workflow: CompiledWorkflow): WorkflowHandle {
399
474
  const runtime = deps.runtime;
@@ -408,10 +483,11 @@ export function startWorkflow(deps: WorkflowRunDeps, workflow: CompiledWorkflow)
408
483
  controller: new AbortController(),
409
484
  nodes: workflow.nodes.map((node) => ({
410
485
  id: node.id,
411
- index: node.index,
412
486
  agent: node.agent,
413
487
  task: node.task,
414
488
  dependsOn: [...node.dependsOn],
489
+ ancestors: [...node.ancestors],
490
+ ...(node.isolation ? { isolation: node.isolation } : {}),
415
491
  phaseId: node.phaseId ?? defaultPhaseId(workflow, node),
416
492
  ...(node.scope ? { scope: node.scope } : {}),
417
493
  cwd: node.cwd,
@@ -459,6 +535,7 @@ export function startWorkflow(deps: WorkflowRunDeps, workflow: CompiledWorkflow)
459
535
  return run;
460
536
  },
461
537
  );
538
+ run.done = done;
462
539
  return { run, done };
463
540
  }
464
541
 
@@ -472,26 +549,17 @@ export async function stopWorkflow(
472
549
  if (run.state !== "running" && run.state !== "interrupted") return [];
473
550
  run.state = "stopped";
474
551
  run.stopReason = reason;
475
- run.controller.abort();
476
- const cancelled: number[] = [];
477
- const stopping: Array<Promise<void>> = [];
478
552
  for (const node of run.nodes) {
479
- if (node.state === "pending") {
480
- node.state = "stopped";
481
- node.error = "stopped before it started";
482
- continue;
483
- }
484
- if (node.state !== "running") continue;
485
- if (node.runId === undefined) {
486
- node.state = "stopped";
487
- continue;
488
- }
489
- const thread = runtime.threads.get(node.runId);
490
- stopping.push(thread ? thread.control.stop(reason).catch(() => undefined) : Promise.resolve());
491
- runtime.backgroundQueue.cancel(thread?.queueController ?? runtime.runControllers.get(node.runId));
492
- cancelled.push(node.runId);
553
+ if (node.state !== "pending") continue;
554
+ node.state = "stopped";
555
+ node.error = "stopped before it started";
493
556
  }
494
- 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();
495
563
  return cancelled;
496
564
  }
497
565
 
@@ -504,6 +572,7 @@ export async function persistInterruptedWorkflows(runtime: SubagentRuntime): Pro
504
572
  run.state = "interrupted";
505
573
  run.endedAt = Date.now();
506
574
  run.stopReason ??= "the parent session ended before this workflow settled";
575
+ monitor.updateWorkflow(run);
507
576
  await upsertWorkflowRecord(runtime.configPath, workflowRecord(run, "interrupted")).catch(() => undefined);
508
577
  // Wake the runner's waiters so the graph unwinds instead of holding a
509
578
  // promise past shutdown; settle() keeps the record and skips delivery.
@@ -529,7 +598,7 @@ export async function readRetainedWorkflows(runtime: SubagentRuntime, cwd: strin
529
598
  return records.map((record) => ({
530
599
  id: record.workflowId,
531
600
  name: record.name,
532
- state: record.state,
601
+ state: record.state === "running" ? "interrupted" : record.state,
533
602
  ...(record.stopReason ? { stopReason: record.stopReason } : {}),
534
603
  updatedAt: record.updatedAt,
535
604
  nodes: record.nodes,
@@ -577,7 +646,7 @@ export function workflowStatus(run: WorkflowRun): WorkflowStatusView {
577
646
  ...(node.runId !== undefined ? { runId: node.runId } : {}),
578
647
  ...(node.state === "pending" && node.dependsOn.length > 0 ? { waitingFor: [...node.dependsOn] } : {}),
579
648
  ...(node.error ? { error: node.error } : {}),
580
- ...(live?.activity ? { activity: live.activity } : {}),
649
+ ...(live?.status === "queued" ? { activity: runWaitLabel(live) } : live?.integrationStatus === "finalizing" ? { activity: "integrating worktree" } : live?.activity ? { activity: live.activity } : {}),
581
650
  ...(node.startedAt !== undefined ? { elapsedMs: (node.endedAt ?? Date.now()) - node.startedAt } : {}),
582
651
  };
583
652
  }),