@ferris1225/pi-subagents 6.0.3 → 6.0.5

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 (39) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +83 -200
  3. package/index.ts +8 -13
  4. package/package.json +1 -1
  5. package/src/configuration/config.ts +2 -6
  6. package/src/configuration/role-migration.ts +3 -14
  7. package/src/configuration/setup.ts +66 -57
  8. package/src/configuration/ui.ts +335 -64
  9. package/src/delegation/agents.ts +5 -6
  10. package/src/delegation/builtin-agents.ts +10 -31
  11. package/src/delegation/dispatch.ts +52 -165
  12. package/src/delegation/prompt.ts +29 -82
  13. package/src/execution/background.ts +2 -2
  14. package/src/execution/run-control.ts +1 -1
  15. package/src/execution/spawn.ts +2 -30
  16. package/src/isolation/worktree.ts +0 -14
  17. package/src/lifecycle/cancellation.ts +4 -8
  18. package/src/lifecycle/completion.ts +9 -21
  19. package/src/lifecycle/dispatch-core.ts +7 -7
  20. package/src/lifecycle/durable.ts +5 -29
  21. package/src/lifecycle/runtime.ts +11 -63
  22. package/src/lifecycle/stop.ts +1 -2
  23. package/src/lifecycle/thread-lifecycle.ts +38 -83
  24. package/src/lifecycle/thread-restore.ts +1 -3
  25. package/src/lifecycle/thread-shared.ts +10 -27
  26. package/src/lifecycle/tools.ts +24 -114
  27. package/src/presentation/announcements.ts +8 -6
  28. package/src/presentation/format.ts +39 -14
  29. package/src/presentation/monitor.ts +697 -758
  30. package/src/presentation/widget.ts +34 -142
  31. package/src/delegation/ownership.ts +0 -98
  32. package/src/delegation/phase-scope.ts +0 -186
  33. package/src/workflow/acceptance.ts +0 -67
  34. package/src/workflow/durable.ts +0 -228
  35. package/src/workflow/engine.ts +0 -816
  36. package/src/workflow/plan.ts +0 -409
  37. package/src/workflow/state.ts +0 -55
  38. package/src/workflow/templates.ts +0 -156
  39. package/src/workflow/tool.ts +0 -254
@@ -1,816 +0,0 @@
1
- /**
2
- * Workflow runner: a dependency-ordered graph of ordinary managed sub-agent runs.
3
- *
4
- * The rule this module exists for is "dispatch the next node the moment its
5
- * prerequisites settle, without waking the parent model". Each node is started
6
- * through the same dispatcher a `subagent` call uses — same lifecycle ownership, same
7
- * admission, same isolation, same durable checkpoint — and is `quiet`, meaning
8
- * it reports into this graph instead of sending its own completion message.
9
- * The parent receives the graph's summary once, through its chosen delivery route.
10
- *
11
- * Failure is contained by the graph, not the session: a failed node blocks only
12
- * its dependents, independent branches keep running, and the summary states
13
- * what completed, what failed, and what never ran. Nodes do not retry and do not
14
- * resume — main finishes incomplete work from their retained evidence, exactly
15
- * as for a failed one-shot run.
16
- */
17
-
18
- import { randomUUID } from "node:crypto";
19
- import { isFailedResult, getResultError, getResultOutput, truncateResultOutput, writeResultArtifact, type SingleResult } from "../execution/spawn.ts";
20
- import { formatDuration, formatTaskSummary, monitor, runWaitLabel } from "../presentation/monitor.ts";
21
- import { perModelTotals, type CompletionMessageItem } from "../lifecycle/completion.ts";
22
- import { findPendingWorkflowPhase, type SubagentRuntime } from "../lifecycle/runtime.ts";
23
- import type { StartBackgroundInternal } from "../lifecycle/thread-shared.ts";
24
- import { stopThreads } from "../lifecycle/stop.ts";
25
- import { findDuplicateDispatch } from "../delegation/prompt.ts";
26
- import { defaultPhaseId, renderNodeTask, UPSTREAM_OUTPUT_MAX_CHARS, type CompiledWorkflow, type UpstreamOutput } from "./plan.ts";
27
- import {
28
- readWorkflowRecords,
29
- removeWorkflowRecord,
30
- upsertWorkflowRecord,
31
- workflowRecordIdentity,
32
- type RecordedNodeState,
33
- type WorkflowRecord,
34
- } from "./durable.ts";
35
- import type { WorkflowNodeRun, WorkflowRun, WorkflowRunState } from "./state.ts";
36
- import type { PhaseScope } from "../delegation/phase-scope.ts";
37
- import { buildAcceptanceBrief, parseAcceptanceVerdict, WORKFLOW_ACCEPTANCE_AGENT, WORKFLOW_ACCEPTANCE_ID } from "./acceptance.ts";
38
-
39
- /** Lines of one node's answer inlined into the graph summary. The complete text
40
- * of every node is always written to a single workflow artifact, so nothing is
41
- * lost and nothing is delivered twice. */
42
- export const NODE_SUMMARY_LINES = 12;
43
-
44
- export interface WorkflowRunDeps {
45
- runtime: SubagentRuntime;
46
- startBackground: StartBackgroundInternal;
47
- /** Isolation the graph wants for a node, resolved against the live catalog. */
48
- resolveIsolation: (agentName: string) => "shared" | "worktree";
49
- /** Awaited graphs return their summary in the tool result instead of waking the parent. */
50
- deliveryRoute?: "background" | "await";
51
- /** Project-scoped results directory for the full workflow report. */
52
- resultsRoot: string;
53
- notify: (message: string, kind: "info" | "warning" | "error") => void;
54
- }
55
-
56
- export interface WorkflowHandle {
57
- run: WorkflowRun;
58
- /** Resolves after the graph settles and background delivery, when requested. */
59
- done: Promise<WorkflowRun>;
60
- }
61
-
62
- interface RunContext extends WorkflowRunDeps {
63
- run: WorkflowRun;
64
- wake: () => void;
65
- waitForWake: () => Promise<void>;
66
- }
67
-
68
- function nodeById(run: WorkflowRun, id: string): WorkflowNodeRun | undefined {
69
- return run.nodes.find((node) => node.id === id);
70
- }
71
-
72
- function terminalFailure(state: WorkflowNodeStateUnion): boolean {
73
- return state === "failed" || state === "blocked" || state === "stopped";
74
- }
75
-
76
- type WorkflowNodeStateUnion = WorkflowNodeRun["state"];
77
-
78
- function describeError(result: SingleResult): string | undefined {
79
- return getResultError(result)?.trim() || undefined;
80
- }
81
-
82
- /** Upstream fact view passed to a dependent node's brief. */
83
- function upstreamView(node: WorkflowNodeRun): UpstreamOutput {
84
- const result = node.result;
85
- const output = result ? getResultOutput(result) : "";
86
- return {
87
- status: node.state === "completed" ? "completed" : node.state === "failed" ? "failed" : node.state === "blocked" ? "blocked" : "stopped",
88
- output,
89
- ...(node.runId !== undefined ? { runId: node.runId } : {}),
90
- ...(node.error ? { error: node.error } : {}),
91
- ...(result?.resultFile ? { resultFile: result.resultFile } : {}),
92
- };
93
- }
94
-
95
- /** Resolve once the run reports a terminal result, or once it stops existing. */
96
- function waitForNodeSettlement(
97
- runtime: SubagentRuntime,
98
- runId: number,
99
- signal: AbortSignal,
100
- ): Promise<SingleResult | undefined> {
101
- const already = runtime.settledRuns.get(runId);
102
- if (already) return Promise.resolve(already);
103
- return new Promise((resolve) => {
104
- let done = false;
105
- let unsubscribe: (() => void) | undefined;
106
- const cleanup = (): void => {
107
- unsubscribe?.();
108
- signal.removeEventListener("abort", onAbort);
109
- runtime.settledListeners.get(runId)?.delete(onSettled);
110
- };
111
- const finish = (result: SingleResult | undefined): void => {
112
- if (done) return;
113
- done = true;
114
- cleanup();
115
- resolve(result);
116
- };
117
- const onSettled = (result: SingleResult): void => finish(result);
118
- const onAbort = (): void => finish(undefined);
119
- const listeners = runtime.settledListeners.get(runId) ?? new Set<(result: SingleResult) => void>();
120
- runtime.settledListeners.set(runId, listeners);
121
- listeners.add(onSettled);
122
- unsubscribe = monitor.subscribe(() => {
123
- const settled = runtime.settledRuns.get(runId);
124
- if (settled) {
125
- finish(settled);
126
- return;
127
- }
128
- if (monitor.findRun(runId)) return;
129
- // Removal is followed synchronously by registerRunResult on the normal
130
- // path; a cancelled run never registers one, so fall back to whatever
131
- // the thread recorded before giving up on this node.
132
- setTimeout(() => {
133
- finish(runtime.settledRuns.get(runId) ?? runtime.threads.get(runId)?.lastResult);
134
- }, 0);
135
- });
136
- if (signal.aborted) finish(undefined);
137
- else signal.addEventListener("abort", onAbort, { once: true });
138
- });
139
- }
140
-
141
- function canDispatch(ctx: RunContext): boolean {
142
- return ctx.run.state === "running" && !ctx.run.controller.signal.aborted && ctx.runtime.sessionActive;
143
- }
144
-
145
- async function dispatchNode(ctx: RunContext, node: WorkflowNodeRun): Promise<void> {
146
- const { run } = ctx;
147
- if (!canDispatch(ctx)) return;
148
- node.state = "running";
149
- node.startedAt = Date.now();
150
- let task: string;
151
- if (node.kind === "acceptance") {
152
- node.evidenceFile = writeResultArtifact(formatWorkflowReport(run), `workflow-${run.slug}-acceptance-evidence`, ctx.resultsRoot);
153
- task = buildAcceptanceBrief(run, node.evidenceFile);
154
- } else {
155
- const upstream = new Map<string, UpstreamOutput>();
156
- for (const dependency of node.ancestors) {
157
- const upstreamNode = nodeById(run, dependency);
158
- if (upstreamNode) upstream.set(dependency, upstreamView(upstreamNode));
159
- }
160
- task = renderNodeTask(node.task, upstream);
161
- }
162
- let started: SingleResult;
163
- try {
164
- started = await ctx.startBackground(node.agent, task, node.cwd, node.isolation ?? ctx.resolveIsolation(node.agent), {
165
- phaseId: node.phaseId,
166
- scope: node.scope,
167
- automaticIsolation: node.isolation === undefined,
168
- deliveryRoute: "background",
169
- quiet: true,
170
- workflow: { workflowId: run.id, name: run.name, nodeId: node.id },
171
- });
172
- } catch (error) {
173
- node.state = "failed";
174
- node.error = `dispatch crashed: ${error instanceof Error ? error.message : String(error)}`;
175
- node.endedAt = Date.now();
176
- return;
177
- }
178
- if (started.runId === undefined || started.exitCode !== -1) {
179
- // A rejected start (unknown agent, duplicate phase, overlapping scope,
180
- // worktree admission) never allocated a run; its text is the reason.
181
- node.state = "failed";
182
- node.error = getResultOutput(started).trim() || getResultError(started) || "the node could not start";
183
- node.result = started;
184
- node.endedAt = Date.now();
185
- return;
186
- }
187
- node.runId = started.runId;
188
- node.durableRunId = ctx.runtime.threads.get(started.runId)?.durableId;
189
- await checkpoint(ctx);
190
- if (run.state === "stopped") await stopThreads(ctx.runtime, [started.runId], run.stopReason);
191
- const result = await waitForNodeSettlement(ctx.runtime, started.runId, run.controller.signal);
192
- node.endedAt = Date.now();
193
- node.result = result;
194
- if (result && (node.kind === "acceptance" || getResultOutput(result).length > UPSTREAM_OUTPUT_MAX_CHARS) && !result.resultFile) {
195
- try {
196
- result.resultFile = writeResultArtifact(getResultOutput(result), `workflow-${run.slug}-${node.id}`, ctx.resultsRoot);
197
- } catch {
198
- /* The dependent brief explicitly reports an unavailable full answer. */
199
- }
200
- }
201
- if (run.state !== "running" || run.controller.signal.aborted || !ctx.runtime.sessionActive) {
202
- if (node.kind !== "acceptance" && result && !isFailedResult(result)) { node.state = "completed"; return; }
203
- node.state = "stopped";
204
- node.error ??= run.stopReason ?? "workflow stopped";
205
- return;
206
- }
207
- if (!result) {
208
- node.state = "stopped";
209
- node.error = "the run ended without reporting a result";
210
- return;
211
- }
212
- if (isFailedResult(result)) {
213
- node.state = "failed";
214
- node.error = describeError(result) ?? "the run failed";
215
- ctx.notify(
216
- `✗ workflow ${run.name} · node ${node.id} (${node.agent}) failed: ${formatTaskSummary(node.error, 200, false)}`,
217
- "error",
218
- );
219
- return;
220
- }
221
- if (node.kind === "acceptance") {
222
- const review = parseAcceptanceVerdict(getResultOutput(result));
223
- if (review.verdict !== "PASS") {
224
- node.state = "failed";
225
- node.error = review.error ?? "Required acceptance rejected the integrated outcome (WORKFLOW_ACCEPTANCE: FAIL). Read the review result for blockers and limitations.";
226
- ctx.notify(`✗ workflow ${run.name} · required acceptance rejected: ${formatTaskSummary(node.error, 200, false)}`, "error");
227
- return;
228
- }
229
- }
230
- node.state = "completed";
231
- }
232
-
233
- /** Blocked nodes are reported, not silently skipped: a graph that never ran a
234
- * node must say why. */
235
- function blockDependents(run: WorkflowRun): boolean {
236
- let changed = false;
237
- for (const node of run.nodes) {
238
- if (node.state !== "pending" || node.kind === "acceptance") continue;
239
- const broken = node.dependsOn.find((dependency) => {
240
- const state = nodeById(run, dependency)?.state;
241
- return state !== undefined && terminalFailure(state);
242
- });
243
- if (!broken) continue;
244
- node.state = "blocked";
245
- node.error = `dependency "${broken}" did not complete; this node never ran`;
246
- changed = true;
247
- }
248
- return changed;
249
- }
250
-
251
- async function checkpoint(ctx: RunContext): Promise<void> {
252
- if (ctx.runtime.sessionActive) monitor.updateWorkflow(ctx.run);
253
- if (ctx.run.state !== "running") return;
254
- await upsertWorkflowRecord(ctx.runtime.configPath, workflowRecord(ctx.run, "running")).catch(() => undefined);
255
- }
256
-
257
- async function drive(ctx: RunContext): Promise<void> {
258
- const { run } = ctx;
259
- const inFlight = new Set<Promise<void>>();
260
- await checkpoint(ctx);
261
- while (run.state === "running") {
262
- if (!ctx.runtime.sessionActive) {
263
- await persistInterruptedWorkflows(ctx.runtime);
264
- break;
265
- }
266
- while (blockDependents(run)) { /* Propagate through any author order. */ }
267
- const ready = run.nodes.filter(
268
- (node) =>
269
- node.state === "pending" &&
270
- node.dependsOn.every((dependency) => {
271
- const state = nodeById(run, dependency)?.state;
272
- return node.kind === "acceptance"
273
- ? state !== undefined && state !== "pending" && state !== "running"
274
- : state === "completed";
275
- }),
276
- );
277
- for (const node of ready) {
278
- if (!canDispatch(ctx)) break;
279
- // dispatchNode marks the node running synchronously, so the next pass
280
- // cannot start it twice.
281
- const task = dispatchNode(ctx, node).catch((error: unknown) => {
282
- node.state = "failed";
283
- node.error = error instanceof Error ? error.message : String(error);
284
- node.endedAt = Date.now();
285
- }).finally(async () => {
286
- await checkpoint(ctx);
287
- inFlight.delete(task);
288
- ctx.wake();
289
- });
290
- inFlight.add(task);
291
- }
292
- if (run.state !== "running") break;
293
- const running = run.nodes.some((node) => node.state === "running");
294
- if (!running && run.nodes.every((node) => node.state !== "pending")) break;
295
- // Nothing can start until a running node settles (or a node that was just
296
- // marked blocked frees the pass); wait for one wake-up instead of polling.
297
- await ctx.waitForWake();
298
- }
299
- await Promise.all(inFlight);
300
- }
301
-
302
- function stateLabel(state: WorkflowRunState): string {
303
- switch (state) {
304
- case "completed":
305
- return "completed";
306
- case "failed":
307
- return "finished with failures";
308
- case "stopped":
309
- return "stopped";
310
- case "interrupted":
311
- return "interrupted";
312
- default:
313
- return "running";
314
- }
315
- }
316
-
317
- function nodeStateWord(node: Pick<WorkflowNodeRun, "kind" | "state">): string {
318
- if (node.kind === "acceptance") {
319
- return `required acceptance ${node.state === "completed" ? "accepted" : node.state === "failed" ? "rejected" : node.state}`;
320
- }
321
- return node.state === "blocked" ? "never ran (blocked)" : node.state;
322
- }
323
-
324
- /** One line per node: what ran, what it cost in wall-clock, and why it failed. */
325
- export function formatNodeLine(node: WorkflowNodeRun): string {
326
- const parts = [`${node.id} (${node.agent}) ${nodeStateWord(node)}`];
327
- if (node.runId !== undefined) parts.push(`run #${node.runId}`);
328
- if (node.startedAt !== undefined) {
329
- parts.push(formatDuration((node.endedAt ?? Date.now()) - node.startedAt));
330
- }
331
- if (node.error && node.state !== "completed") {
332
- parts.push(`error: ${formatTaskSummary(node.error, 220, false)}`);
333
- }
334
- if (node.state === "pending" && node.dependsOn.length > 0) {
335
- parts.push(`waiting for ${node.dependsOn.join(", ")}`);
336
- }
337
- return `- ${parts.join(" · ")}`;
338
- }
339
-
340
- function completedCount(run: WorkflowRun): number {
341
- return run.nodes.filter((node) => node.state === "completed").length;
342
- }
343
-
344
- /** Full markdown report: every node's line and every node's complete answer. */
345
- export function formatWorkflowReport(run: WorkflowRun): string {
346
- const lines = [
347
- `# Workflow ${run.name} — ${stateLabel(run.state)}`,
348
- "",
349
- ...(run.description ? [run.description, ""] : []),
350
- `Nodes: ${completedCount(run)} of ${run.nodes.length} completed`,
351
- ...(run.stopReason ? [`Stop reason: ${run.stopReason}`] : []),
352
- "",
353
- ...run.nodes.map(formatNodeLine),
354
- ];
355
- for (const node of run.nodes) {
356
- const output = node.result ? getResultOutput(node.result).trim() : "";
357
- lines.push("", `## ${node.id} (${node.agent}) — ${nodeStateWord(node)}`, "");
358
- lines.push(`Phase: ${node.phaseId}`, `Working directory: ${node.cwd}`, `Dependencies: ${node.dependsOn.join(", ") || "none"}`);
359
- if (node.scope) lines.push(`Declared scope: ${JSON.stringify(node.scope)}`);
360
- if (node.result?.integrationStatus) lines.push(`Integration: ${node.result.integrationStatus}`);
361
- lines.push(`Task / done condition:\n${node.task}`, "");
362
- lines.push(output || "(no answer recorded)");
363
- if (node.error) lines.push("", `Error: ${node.error}`);
364
- for (const [label, path] of [["Acceptance evidence report", node.evidenceFile], ["Full result", node.result?.resultFile], ["Retained worktree", node.result?.integrationWorktreePath], ["Retained patch", node.result?.integrationPatchPath]]) {
365
- if (path) lines.push(`${label}: ${path}`);
366
- }
367
- }
368
- return lines.join("\n");
369
- }
370
-
371
- /** Lines of one node's answer inlined into the completion message. */
372
- function inlineNodeAnswer(node: WorkflowNodeRun): { text: string; truncated: boolean } {
373
- const output = node.result ? getResultOutput(node.result) : "";
374
- if (!output.trim()) return { text: "", truncated: false };
375
- const clipped = truncateResultOutput(output, NODE_SUMMARY_LINES);
376
- return { text: clipped.text.trim(), truncated: clipped.truncated };
377
- }
378
-
379
- /** The parent's one handoff for the whole graph. */
380
- export function formatWorkflowSummary(run: WorkflowRun, resultsRoot?: string): string {
381
- const completed = completedCount(run);
382
- const failed = run.nodes.filter((node) => node.state === "failed").length;
383
- const blocked = run.nodes.filter((node) => node.state === "blocked").length;
384
- const stopped = run.nodes.filter((node) => node.state === "stopped").length;
385
- const counts = [
386
- `${completed}/${run.nodes.length} completed`,
387
- ...(failed > 0 ? [`${failed} failed`] : []),
388
- ...(blocked > 0 ? [`${blocked} never ran`] : []),
389
- ...(stopped > 0 ? [`${stopped} stopped`] : []),
390
- ].join(", ");
391
- const lines = [
392
- `### workflow ${run.name} ${stateLabel(run.state)} (${counts})`,
393
- ...(run.description ? [run.description] : []),
394
- ...(run.stopReason ? [`Stop reason: ${run.stopReason}`] : []),
395
- "",
396
- ...run.nodes.map(formatNodeLine),
397
- ];
398
-
399
- const answers: string[] = [];
400
- let anyTruncated = false;
401
- for (const node of run.nodes) {
402
- const inline = inlineNodeAnswer(node);
403
- if (!inline.text) continue;
404
- if (inline.truncated) anyTruncated = true;
405
- answers.push(`#### ${node.id} (${node.agent})${node.kind === "acceptance" ? " — required acceptance review" : ""}`, inline.text, "");
406
- if (node.kind === "acceptance" && node.result?.resultFile) answers.push(`Full acceptance review: ${node.result.resultFile}`, "");
407
- }
408
- if (answers.length > 0) {
409
- lines.push("", "Node answers:", "", ...answers);
410
- }
411
- if (anyTruncated && resultsRoot) {
412
- try {
413
- const reportPath = writeResultArtifact(formatWorkflowReport(run), `workflow-${run.slug}`, resultsRoot);
414
- lines.push(`⚠ Some node answers are clipped here. Read the complete report, including every node's full answer: ${reportPath}`);
415
- } catch (error) {
416
- 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.`);
417
- }
418
- }
419
- const totals = perModelTotals(
420
- run.nodes
421
- .filter((node): node is WorkflowNodeRun & { result: SingleResult } => node.result !== undefined)
422
- .map((node) => ({ agent: node.agent, block: "", usage: node.result.usage, model: node.result.model })),
423
- );
424
- if (totals) lines.push("", `Totals: ${run.nodes.length} nodes · ${totals}`);
425
- if (failed > 0 || blocked > 0 || stopped > 0) {
426
- lines.push(
427
- "",
428
- "Main owns the rest: inspect what failed or never ran, reuse the partial edits and artifacts those runs retained, then finish the work and run the project's own gate. Do not re-dispatch a phase this graph already owns.",
429
- );
430
- }
431
- return lines.join("\n");
432
- }
433
-
434
- function workflowRecord(run: WorkflowRun, state: WorkflowRecord["state"]): WorkflowRecord {
435
- run.durableId ??= randomUUID();
436
- return {
437
- durableId: run.durableId,
438
- workflowId: run.id,
439
- name: run.name,
440
- ...(run.description ? { description: run.description } : {}),
441
- cwd: run.cwd,
442
- state,
443
- startedAt: run.startedAt,
444
- updatedAt: Date.now(),
445
- ...(run.stopReason ? { stopReason: run.stopReason } : {}),
446
- nodes: run.nodes.map((node) => ({
447
- id: node.id,
448
- agent: node.agent,
449
- task: node.task,
450
- dependsOn: [...node.dependsOn],
451
- ...(node.kind ? { kind: node.kind } : {}),
452
- ...(node.evidenceFile ? { evidenceFile: node.evidenceFile } : {}),
453
- ...(node.result?.resultFile ? { resultFile: node.result.resultFile } : {}),
454
- state: node.state as RecordedNodeState,
455
- ...(node.runId !== undefined ? { runId: node.runId } : {}),
456
- ...(node.durableRunId ? { durableRunId: node.durableRunId } : {}),
457
- ...(node.error ? { error: node.error } : {}),
458
- })),
459
- };
460
- }
461
-
462
- async function settle(ctx: RunContext): Promise<void> {
463
- const { run, runtime } = ctx;
464
- // A graph interrupted by session teardown keeps the record the teardown wrote:
465
- // it is the evidence the next session explains, not a settled run.
466
- const interrupted = run.state === "interrupted";
467
- if (run.state === "running") {
468
- const accepted = run.nodes.some((node) => node.kind === "acceptance" && node.state === "completed");
469
- run.state = !accepted || run.nodes.some((node) => node.state !== "completed") ? "failed" : "completed";
470
- }
471
- run.endedAt ??= Date.now();
472
- if (runtime.sessionActive) monitor.updateWorkflow(run);
473
- if (!interrupted && run.durableId) await removeWorkflowRecord(runtime.configPath, run.durableId, run.cwd).catch(() => undefined);
474
- }
475
-
476
- /** A phase a live or retained thread already owns. */
477
- export interface OwnedPhase {
478
- nodeId: string;
479
- phaseId: string;
480
- runId?: number;
481
- workflowId?: number;
482
- ownerNodeId?: string;
483
- agent: string;
484
- state: string;
485
- }
486
-
487
- /**
488
- * Phases this session already owns, checked before the graph starts.
489
- *
490
- * A phase is owned by the parent session, not by one graph: an interrupted or
491
- * settled owner keeps its claim until it is retired. Checking every node up
492
- * front turns "the first node failed and the rest never ran" into one message
493
- * that names the owners and the way out, at the cost of no child process.
494
- */
495
- export function findOwnedPhases(runtime: SubagentRuntime, workflow: CompiledWorkflow): OwnedPhase[] {
496
- const owned: OwnedPhase[] = [];
497
- for (const node of workflow.nodes) {
498
- const phaseId = node.phaseId ?? defaultPhaseId(workflow, node);
499
- const duplicate = findDuplicateDispatch(runtime.threads.values(), node.task, node.cwd, phaseId);
500
- if (!duplicate) {
501
- const pending = findPendingWorkflowPhase(runtime, node.task, node.cwd, phaseId);
502
- if (pending) owned.push({ nodeId: node.id, phaseId, workflowId: pending.workflowId, ownerNodeId: pending.nodeId, agent: pending.agent, state: "pending" });
503
- continue;
504
- }
505
- owned.push({
506
- nodeId: node.id,
507
- phaseId,
508
- runId: duplicate.source.id,
509
- agent: duplicate.source.agentName,
510
- state: duplicate.source.lifecycleOperation === "settle" ? "settling" : duplicate.source.state,
511
- });
512
- }
513
- return owned;
514
- }
515
-
516
- /** Start a compiled graph. Nodes dispatch as their prerequisites settle. */
517
- export function startWorkflow(deps: WorkflowRunDeps, workflow: CompiledWorkflow): WorkflowHandle {
518
- const work = workflow.nodes.filter((node) => node.kind !== "acceptance");
519
- const reviews = workflow.nodes.filter((node) => node.kind === "acceptance");
520
- const review = reviews[0];
521
- if (reviews.length !== 1 || !review || review.id !== WORKFLOW_ACCEPTANCE_ID || review.agent !== WORKFLOW_ACCEPTANCE_AGENT ||
522
- review.cwd !== workflow.cwd || review.isolation !== "shared" || review.scope ||
523
- review.dependsOn.length !== work.length || work.some((node) => !review.dependsOn.includes(node.id))) {
524
- throw new Error("A workflow requires exactly one compiler-owned independent acceptance node covering all authored work.");
525
- }
526
- const runtime = deps.runtime;
527
- const durableId = randomUUID();
528
- const run: WorkflowRun = {
529
- durableId,
530
- id: runtime.reserveWorkflowId(),
531
- name: workflow.name,
532
- slug: workflow.slug,
533
- ...(workflow.description ? { description: workflow.description } : {}),
534
- cwd: workflow.cwd,
535
- state: "running",
536
- startedAt: Date.now(),
537
- controller: new AbortController(),
538
- nodes: workflow.nodes.map((node) => ({
539
- id: node.id,
540
- ...(node.kind ? { kind: node.kind } : {}),
541
- agent: node.agent,
542
- task: node.task,
543
- dependsOn: [...node.dependsOn],
544
- ancestors: [...node.ancestors],
545
- ...(node.isolation ? { isolation: node.isolation } : {}),
546
- phaseId: node.phaseId ?? defaultPhaseId(workflow, node),
547
- ...(node.scope ? { scope: node.scope } : {}),
548
- cwd: node.cwd,
549
- state: "pending",
550
- })),
551
- };
552
- runtime.workflows.set(run.id, run);
553
- runtime.workflowRecordIds.set(durableId, run.id);
554
-
555
- let wakeRequested = false;
556
- let wakeResolver: (() => void) | undefined;
557
- const ctx: RunContext = {
558
- ...deps,
559
- run,
560
- wake: () => {
561
- if (wakeResolver) {
562
- const resolve = wakeResolver;
563
- wakeResolver = undefined;
564
- resolve();
565
- } else {
566
- wakeRequested = true;
567
- }
568
- },
569
- waitForWake: async () => {
570
- if (wakeRequested) {
571
- wakeRequested = false;
572
- return;
573
- }
574
- await new Promise<void>((resolve) => {
575
- wakeResolver = resolve;
576
- });
577
- },
578
- };
579
-
580
- // Declared writer overlap inside the graph was rejected at compile time; the
581
- // dispatcher still runs its own admission per node, so a node that conflicts
582
- // with unrelated live work fails alone instead of poisoning the graph.
583
- const recordFailure = (error: unknown): void => {
584
- run.state = "failed";
585
- run.endedAt = Date.now();
586
- run.stopReason = error instanceof Error ? error.message : String(error);
587
- };
588
- const done = (async () => {
589
- let crashed = false;
590
- try {
591
- await drive(ctx);
592
- await settle(ctx);
593
- } catch (error) {
594
- crashed = true;
595
- recordFailure(error);
596
- await removeWorkflowRecord(runtime.configPath, durableId, run.cwd).catch(() => undefined);
597
- }
598
- // Both normal and unexpected failure paths use this sole delivery point.
599
- // Never retry delivery when the sender itself throws: it may have sent.
600
- try {
601
- if (runtime.sessionActive && deps.deliveryRoute !== "await") {
602
- const item: CompletionMessageItem = {
603
- agent: `workflow:${run.name}`,
604
- block: formatWorkflowSummary(run, ctx.resultsRoot),
605
- };
606
- // The summary carries its own per-model tally; a group total would
607
- // merge different models' spend into one number.
608
- runtime.sendCompletionGroup([item]);
609
- }
610
- } catch (error) {
611
- crashed = true;
612
- recordFailure(error);
613
- }
614
- if (crashed) {
615
- try {
616
- deps.notify(`✗ workflow ${run.name} crashed: ${run.stopReason}`, "error");
617
- } catch {
618
- /* Notification failure must not strand callers waiting on done. */
619
- }
620
- }
621
- return run;
622
- })();
623
- run.done = done;
624
- return { run, done };
625
- }
626
-
627
- /** Stop a graph: no new node starts, running nodes are cancelled, and the
628
- * summary still reports what had already completed. */
629
- export async function stopWorkflow(
630
- runtime: SubagentRuntime,
631
- run: WorkflowRun,
632
- reason = "Stopped by subagent_stop.",
633
- ): Promise<number[]> {
634
- if (run.state !== "running" && run.state !== "interrupted") return [];
635
- run.state = "stopped";
636
- run.stopReason = reason;
637
- for (const node of run.nodes) {
638
- if (node.state !== "pending") continue;
639
- node.state = "stopped";
640
- node.error = "stopped before it started";
641
- }
642
- monitor.updateWorkflow(run);
643
- const cancelled = run.nodes.flatMap((node) => node.state === "running" && node.runId !== undefined ? [node.runId] : []);
644
- // The same stop owner as the control tool finalizes worktrees before the
645
- // graph publishes its summary. A late dispatch stops itself on allocation.
646
- await stopThreads(runtime, cancelled, reason);
647
- run.controller.abort();
648
- return cancelled;
649
- }
650
-
651
- /** Persist the shape of every graph still running when the session ends, so the
652
- * next session explains what was in flight instead of showing loose threads. */
653
- export async function persistInterruptedWorkflows(runtime: SubagentRuntime): Promise<void> {
654
- const live = [...runtime.workflows.values()].filter((run) => run.state === "running");
655
- await Promise.all(
656
- live.map(async (run) => {
657
- run.state = "interrupted";
658
- run.endedAt = Date.now();
659
- run.stopReason ??= "the parent session ended before this workflow settled";
660
- monitor.updateWorkflow(run);
661
- await upsertWorkflowRecord(runtime.configPath, workflowRecord(run, "interrupted")).catch(() => undefined);
662
- // Wake the runner's waiters so the graph unwinds instead of holding a
663
- // promise past shutdown; settle() keeps the record and skips delivery.
664
- run.controller.abort();
665
- }),
666
- );
667
- }
668
-
669
- export interface RetainedWorkflow {
670
- id: number;
671
- durableId: string;
672
- name: string;
673
- state: WorkflowRecord["state"];
674
- stopReason?: string;
675
- updatedAt: number;
676
- nodes: Array<WorkflowRecord["nodes"][number] & { originalRunId?: number }>;
677
- }
678
-
679
- /** Reconcile persisted identities with this window's ids. Never attach an old
680
- * node to an unrelated run merely because their display numbers match. */
681
- export async function readRetainedWorkflows(runtime: SubagentRuntime, cwd: string): Promise<RetainedWorkflow[]> {
682
- const records = await readWorkflowRecords(runtime.configPath, cwd);
683
- for (const record of records) runtime.ensureWorkflowIdAbove(record.workflowId);
684
- const threadsByIdentity = new Map([...runtime.threads.values()].filter((thread) => thread.durableId)
685
- .map((thread) => [thread.durableId!, thread.id]));
686
- const allocated = new Set([...runtime.workflowRecordIds.values(), ...runtime.workflows.keys()]);
687
- return records.map((record) => {
688
- const durableId = workflowRecordIdentity(record);
689
- let id = runtime.workflowRecordIds.get(durableId);
690
- if (id === undefined) {
691
- id = allocated.has(record.workflowId) ? runtime.reserveWorkflowId() : record.workflowId;
692
- runtime.workflowRecordIds.set(durableId, id);
693
- allocated.add(id);
694
- }
695
- return {
696
- id, durableId, name: record.name,
697
- state: record.state === "running" ? "interrupted" : record.state,
698
- ...(record.stopReason ? { stopReason: record.stopReason } : {}),
699
- updatedAt: record.updatedAt,
700
- nodes: record.nodes.map((node) => {
701
- const { runId: originalRunId, ...facts } = node;
702
- const runId = node.durableRunId ? threadsByIdentity.get(node.durableRunId) : undefined;
703
- return { ...facts, ...(runId === undefined
704
- ? originalRunId === undefined ? {} : { originalRunId }
705
- : { runId }) };
706
- }),
707
- };
708
- });
709
- }
710
-
711
- /** Status-facing projection of a live or settled graph. */
712
- export interface WorkflowStatusView {
713
- id: number;
714
- name: string;
715
- state: WorkflowRunState;
716
- description?: string;
717
- stopReason?: string;
718
- cwd: string;
719
- startedAt: number;
720
- endedAt?: number;
721
- nodes: Array<{
722
- id: string;
723
- kind?: "acceptance";
724
- evidenceFile?: string;
725
- resultFile?: string;
726
- agent: string;
727
- state: WorkflowNodeRun["state"];
728
- task: string;
729
- phaseId: string;
730
- scope?: PhaseScope;
731
- cwd: string;
732
- runId?: number;
733
- waitingFor?: string[];
734
- error?: string;
735
- activity?: string;
736
- elapsedMs?: number;
737
- }>;
738
- }
739
-
740
- export function workflowStatus(run: WorkflowRun): WorkflowStatusView {
741
- return {
742
- id: run.id,
743
- name: run.name,
744
- state: run.state,
745
- ...(run.description ? { description: run.description } : {}),
746
- ...(run.stopReason ? { stopReason: run.stopReason } : {}),
747
- cwd: run.cwd,
748
- startedAt: run.startedAt,
749
- ...(run.endedAt !== undefined ? { endedAt: run.endedAt } : {}),
750
- nodes: run.nodes.map((node) => {
751
- const live = node.runId === undefined ? undefined : monitor.findRun(node.runId);
752
- return {
753
- id: node.id,
754
- ...(node.kind ? { kind: node.kind } : {}),
755
- ...(node.evidenceFile ? { evidenceFile: node.evidenceFile } : {}),
756
- ...(node.result?.resultFile ? { resultFile: node.result.resultFile } : {}),
757
- agent: node.agent,
758
- state: node.state,
759
- task: formatTaskSummary(node.task, 160, false),
760
- phaseId: node.phaseId,
761
- scope: node.scope,
762
- cwd: node.cwd,
763
- ...(node.runId !== undefined ? { runId: node.runId } : {}),
764
- ...(node.state === "pending" && node.dependsOn.length > 0 ? { waitingFor: [...node.dependsOn] } : {}),
765
- ...(node.error ? { error: node.error } : {}),
766
- ...(live?.status === "queued" ? { activity: runWaitLabel(live) } : live?.integrationStatus === "finalizing" ? { activity: "integrating worktree" } : live?.activity ? { activity: live.activity } : {}),
767
- ...(node.startedAt !== undefined ? { elapsedMs: (node.endedAt ?? Date.now()) - node.startedAt } : {}),
768
- };
769
- }),
770
- };
771
- }
772
-
773
- /** Multi-line text view used by `subagent_status`. */
774
- export function formatWorkflowStatus(run: WorkflowRun): string[] {
775
- const view = workflowStatus(run);
776
- const lines = [
777
- `workflow #${view.id} ${view.name} · ${stateLabel(view.state)} · ${completedCount(run)}/${run.nodes.length} completed · ${formatDuration((view.endedAt ?? Date.now()) - view.startedAt)}`,
778
- ];
779
- if (view.description) lines.push(` ${view.description}`);
780
- if (view.stopReason) lines.push(` stop reason: ${formatTaskSummary(view.stopReason, 200, false)}`);
781
- for (const node of view.nodes) {
782
- const parts = [`${node.id} (${node.agent}) ${nodeStateWord(node)}`];
783
- if (node.runId !== undefined) parts.push(`run #${node.runId}`);
784
- if (node.waitingFor) parts.push(`waiting for ${node.waitingFor.join(", ")}`);
785
- if (node.elapsedMs !== undefined) parts.push(formatDuration(node.elapsedMs));
786
- if (node.activity) parts.push(node.activity);
787
- if (node.error) parts.push(`error: ${formatTaskSummary(node.error, 200, false)}`);
788
- lines.push(` - ${parts.join(" · ")}`);
789
- lines.push(` phase: ${node.phaseId} · task: ${node.task}`);
790
- if (node.scope) lines.push(` scope: ${JSON.stringify(node.scope)}`);
791
- }
792
- return lines;
793
- }
794
-
795
- /** Multi-line view of a graph retained from a previous session. */
796
- export function formatRetainedWorkflow(record: RetainedWorkflow): string[] {
797
- const done = record.nodes.filter((node) => node.state === "completed").length;
798
- const age = formatDuration(Date.now() - record.updatedAt);
799
- const lines = [
800
- "workflow #" + record.id + " " + record.name + " · " + record.state + " (retained) · " +
801
- done + "/" + record.nodes.length + " completed · updated " + age + " ago",
802
- ];
803
- if (record.stopReason) lines.push(" stop reason: " + formatTaskSummary(record.stopReason, 200, false));
804
- for (const node of record.nodes) {
805
- const parts = [node.id + " (" + node.agent + ") " + nodeStateWord(node)];
806
- if (node.runId !== undefined) parts.push("run #" + node.runId);
807
- else if (node.originalRunId !== undefined) parts.push("original run #" + node.originalRunId + " (not restored in this window)");
808
- if (node.dependsOn.length > 0) parts.push("after " + node.dependsOn.join(", "));
809
- if (node.error) parts.push("error: " + formatTaskSummary(node.error, 160, false));
810
- if (node.evidenceFile) parts.push("acceptance evidence: " + node.evidenceFile);
811
- if (node.resultFile) parts.push("full result: " + node.resultFile);
812
- lines.push(" - " + parts.join(" · "));
813
- }
814
- lines.push(" A retained graph is not resumed automatically: main finishes the unfinished nodes from their run evidence.");
815
- return lines;
816
- }