@ferris1225/pi-subagents 4.3.31 → 4.3.33

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 (41) hide show
  1. package/CHANGELOG.md +80 -0
  2. package/LICENSE +1 -1
  3. package/README.md +215 -273
  4. package/index.ts +15 -14
  5. package/package.json +10 -10
  6. package/skills/workflow/SKILL.md +226 -0
  7. package/src/configuration/config.ts +17 -121
  8. package/src/configuration/models.ts +1 -1
  9. package/src/configuration/setup.ts +80 -176
  10. package/src/configuration/ui.ts +28 -66
  11. package/src/delegation/agents.ts +79 -209
  12. package/src/delegation/builtin-agents.ts +60 -0
  13. package/src/delegation/dispatch.ts +32 -149
  14. package/src/delegation/prompt.ts +7 -5
  15. package/src/execution/rpc-control.ts +6 -2
  16. package/src/execution/rpc-run.ts +60 -20
  17. package/src/execution/spawn.ts +17 -28
  18. package/src/isolation/git-command.ts +1 -2
  19. package/src/isolation/recovery.ts +1 -1
  20. package/src/isolation/temp-hygiene.ts +2 -2
  21. package/src/isolation/worktree.ts +31 -17
  22. package/src/lifecycle/completion.ts +1 -1
  23. package/src/lifecycle/dispatch-core.ts +142 -0
  24. package/src/lifecycle/durable.ts +3 -3
  25. package/src/lifecycle/runtime.ts +34 -1
  26. package/src/lifecycle/thread-lifecycle.ts +36 -25
  27. package/src/lifecycle/thread-shared.ts +11 -4
  28. package/src/lifecycle/tools.ts +84 -11
  29. package/src/presentation/monitor.ts +39 -17
  30. package/src/presentation/widget.ts +2 -2
  31. package/src/workflow/durable.ts +195 -0
  32. package/src/workflow/engine.ts +625 -0
  33. package/src/workflow/files.ts +217 -0
  34. package/src/workflow/plan.ts +340 -0
  35. package/src/workflow/state.ts +48 -0
  36. package/src/workflow/tool.ts +269 -0
  37. package/workflows/code-review.md +57 -0
  38. package/workflows/migration.md +52 -0
  39. package/workflows/research.md +47 -0
  40. package/agents/artisan.md +0 -18
  41. package/agents/scout.md +0 -19
@@ -3,7 +3,7 @@
3
3
  import { realpath } from "node:fs/promises";
4
4
  import { join, resolve } from "node:path";
5
5
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
6
- import { isWriteCapableAgent, type AgentConfig } from "../delegation/agents.ts";
6
+ import { isWriteCapableAgent, type AgentConfig, type ToolMetadata } from "../delegation/agents.ts";
7
7
  import type { PhaseScope } from "../delegation/phase-scope.ts";
8
8
  import { roleThinkingLevel, type SubagentsConfig, type ThinkingLevel } from "../configuration/config.ts";
9
9
  import { removeThreadRecord, threadRecordFromThread, upsertThreadRecord } from "./durable.ts";
@@ -15,6 +15,7 @@ import {
15
15
  resolveAgentModelRoute,
16
16
  resolveThinkingLevel,
17
17
  } from "../configuration/models.ts";
18
+ import type { RunWorkflowTag } from "../presentation/monitor.ts";
18
19
  import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
19
20
  import { getProjectRoot, type SingleResult } from "../execution/spawn.ts";
20
21
  import { resolveRepositoryRoot, type IsolationMode } from "../isolation/worktree.ts";
@@ -138,8 +139,8 @@ export function withWorktreeSystemPrompt(agent: AgentConfig): AgentConfig {
138
139
  }
139
140
 
140
141
  /** Only write-capable agents can run in an isolated worktree. */
141
- export function isWorktreeCapableAgent(agent: AgentConfig): boolean {
142
- return isWriteCapableAgent(agent);
142
+ export function isWorktreeCapableAgent(agent: AgentConfig, toolInfos?: readonly ToolMetadata[]): boolean {
143
+ return isWriteCapableAgent(agent, toolInfos);
143
144
  }
144
145
 
145
146
  export interface DispatchEnvironment {
@@ -156,6 +157,12 @@ export interface StartBackgroundOptions {
156
157
  writeCapable?: boolean;
157
158
  /** Chosen by the tool call before the queue can start a fast child. */
158
159
  deliveryRoute?: "background" | "await";
160
+ /** A workflow node reports through its graph's single summary: no per-run
161
+ * completion message and no per-run toast, so a wide graph cannot flood the
162
+ * parent with one wake-up per node. */
163
+ quiet?: boolean;
164
+ /** Graph membership rendered by the widget and node status rows. */
165
+ workflow?: RunWorkflowTag;
159
166
  }
160
167
 
161
168
  export type StartBackgroundInternal = (
@@ -191,7 +198,7 @@ export function resolveDispatchModelRoute(
191
198
  availableRefs: availableModels.map(modelRef),
192
199
  });
193
200
  // A `/subagents-setup` override wins; otherwise the role default. No
194
- // per-call or frontmatter thinking.
201
+ // per-call thinking.
195
202
  const preferred =
196
203
  config.agentThinkingLevels[agent.name] ?? roleThinkingLevel(agent.name);
197
204
  const thinkingLevelForModel = (ref?: string): ThinkingLevel => {
@@ -4,7 +4,7 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
4
4
  import { Text } from "@earendil-works/pi-tui";
5
5
  import { existsSync } from "node:fs";
6
6
  import { Type } from "typebox";
7
- import { DEFAULT_MAX_RESULT_LINES, loadConfig } from "../configuration/config.ts";
7
+ import { DEFAULT_MAX_RESULT_LINES } from "../configuration/config.ts";
8
8
  import { removeThreadRecord } from "./durable.ts";
9
9
  import { formatCompletionBlock, matchRunIds } from "../presentation/format.ts";
10
10
  import { emptyUsage } from "../execution/rpc-control.ts";
@@ -13,6 +13,13 @@ import { persistRecoveryRecords, recoveryRecordFromFinalization } from "../isola
13
13
  import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
14
14
  import { CONTROL_QUIESCE_TIMEOUT_MS, projectResultsRoot, quiesced } from "./thread-shared.ts";
15
15
  import { getResultError, type SingleResult } from "../execution/spawn.ts";
16
+ import {
17
+ formatRetainedWorkflow,
18
+ formatWorkflowStatus,
19
+ readRetainedWorkflows,
20
+ stopWorkflow,
21
+ workflowStatus,
22
+ } from "../workflow/engine.ts";
16
23
  import type { WorktreeFinalization } from "../isolation/worktree.ts";
17
24
 
18
25
  function renderFirstLine(result: { content?: unknown }, label: string, theme: any): Text {
@@ -40,8 +47,9 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
40
47
  },
41
48
  parameters: Type.Object({
42
49
  id: Type.Optional(Type.Integer({ minimum: 1, description: "Exact run id; omit to list all runs in this parent session." })),
50
+ workflow: Type.Optional(Type.Integer({ minimum: 1, description: "Workflow graph id; omit to list every graph in this parent session." })),
43
51
  }),
44
- async execute(_toolCallId, params) {
52
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
45
53
  await runtime.durableRestore;
46
54
  const threads = [...runtime.threads.values()]
47
55
  .filter((thread) => params.id === undefined || thread.id === params.id)
@@ -103,10 +111,34 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
103
111
  if (paths.length > 0) lines.push(` ${paths.join("\n ")}`);
104
112
  return lines.join("\n");
105
113
  }).join("\n");
114
+ // Workflow graphs are reported beside individual runs: which nodes have
115
+ // started, which one is waiting on a dependency, and what a graph that
116
+ // outlived its session left behind.
117
+ const workflowRuns = [...runtime.workflows.values()]
118
+ .filter((run) => params.workflow === undefined || run.id === params.workflow)
119
+ .sort((left, right) => left.id - right.id);
120
+ const retainedWorkflows = (await readRetainedWorkflows(runtime, ctx?.cwd ?? process.cwd()).catch(() => []))
121
+ .filter((record) => params.workflow === undefined || record.id === params.workflow)
122
+ .filter((record) => !workflowRuns.some((run) => run.id === record.id));
123
+ const workflowSections = [
124
+ ...workflowRuns.map((run) => formatWorkflowStatus(run).join("\n")),
125
+ ...retainedWorkflows.map((record) => formatRetainedWorkflow(record).join("\n")),
126
+ ];
127
+ const sections = [text, ...workflowSections].filter((section) => section.trim().length > 0);
128
+ const unknownWorkflow = params.workflow !== undefined && workflowRuns.length === 0 && retainedWorkflows.length === 0;
106
129
  return {
107
- content: [{ type: "text", text }],
108
- details: { runs },
109
- ...(params.id !== undefined && runs.length === 0 ? { isError: true } : {}),
130
+ content: [{
131
+ type: "text",
132
+ text: unknownWorkflow
133
+ ? `No workflow graph matches #${params.workflow} in this parent session.`
134
+ : sections.join("\n\n"),
135
+ }],
136
+ details: {
137
+ runs,
138
+ workflows: workflowRuns.map(workflowStatus),
139
+ retainedWorkflows,
140
+ },
141
+ ...((params.id !== undefined && runs.length === 0) || unknownWorkflow ? { isError: true } : {}),
110
142
  };
111
143
  },
112
144
  renderCall(args, theme) {
@@ -127,7 +159,11 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
127
159
  description: "Run id or prefix to stop (see subagent dispatch output).",
128
160
  }),
129
161
  ),
130
- all: Type.Optional(Type.Boolean({ description: "Stop every active run (default false)." })),
162
+ all: Type.Optional(Type.Boolean({ description: "Stop every active run and every running workflow (default false)." })),
163
+ workflow: Type.Optional(Type.Integer({
164
+ minimum: 1,
165
+ description: "Stop this workflow graph: no dependent node starts and running nodes are cancelled.",
166
+ })),
131
167
  });
132
168
 
133
169
  pi.registerTool({
@@ -146,8 +182,40 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
146
182
 
147
183
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
148
184
  await runtime.durableRestore;
149
- // Claim every target before awaiting process cleanup or configuration I/O.
150
- const configPromise = loadConfig(runtime.configPath).catch(() => undefined);
185
+ // A graph stop owns its own lifecycle: dependents must not start, and the
186
+ // graph's own summary reports what had already completed. Stopping the
187
+ // nodes one by one first would let the runner dispatch the next layer.
188
+ if (params.workflow !== undefined) {
189
+ const graph = runtime.workflows.get(params.workflow);
190
+ if (!graph) {
191
+ const known = [...runtime.workflows.keys()].map((id) => `#${id}`).join(", ");
192
+ return {
193
+ content: [{
194
+ type: "text",
195
+ text: `No workflow graph matches #${params.workflow}.${known ? ` Known graphs: ${known}.` : ""}`,
196
+ }],
197
+ details: {},
198
+ };
199
+ }
200
+ const cancelled = await stopWorkflow(runtime, graph, "Stopped by subagent_stop.");
201
+ return {
202
+ content: [{
203
+ type: "text",
204
+ text: `Stopped workflow #${graph.id} ${graph.name}${cancelled.length > 0 ? `; cancelled ${cancelled.map((id) => `#${id}`).join(", ")}` : "; no node had started"}. Its summary reports the completed work, and each node keeps its own run evidence.`,
205
+ }],
206
+ details: {},
207
+ };
208
+ }
209
+ const graphStops: string[] = [];
210
+ if (params.all === true) {
211
+ for (const graph of [...runtime.workflows.values()]) {
212
+ if (graph.state !== "running") continue;
213
+ const cancelled = await stopWorkflow(runtime, graph, "Stopped by subagent_stop.");
214
+ graphStops.push(
215
+ `workflow #${graph.id} ${graph.name}${cancelled.length > 0 ? ` (${cancelled.length} node${cancelled.length === 1 ? "" : "s"} cancelled)` : ""}`,
216
+ );
217
+ }
218
+ }
151
219
  const completionResults: SingleResult[] = [];
152
220
  const candidateIds = params.all === true
153
221
  ? [...new Set([
@@ -163,6 +231,12 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
163
231
 
164
232
  if (targets.length === 0) {
165
233
  const available = [...runtime.threads.keys()].map((id) => `#${id}`).join(", ");
234
+ if (graphStops.length > 0) {
235
+ return {
236
+ content: [{ type: "text", text: `Stopped ${graphStops.length} workflow${graphStops.length === 1 ? "" : "s"}: ${graphStops.join(", ")}.` }],
237
+ details: {},
238
+ };
239
+ }
166
240
  return {
167
241
  content: [{ type: "text", text: params.all === true
168
242
  ? "No active subagent runs to stop."
@@ -331,10 +405,9 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
331
405
  stopped.push(`#${runId} ${thread.agentName}${wasQueued ? " (queued)" : wasActive ? "" : ` (${previousState})`}`);
332
406
  }
333
407
  if (completionResults.length > 0) {
334
- const maxResultLines = (await configPromise)?.maxResultLines ?? DEFAULT_MAX_RESULT_LINES;
335
408
  runtime.sendCompletionGroup(completionResults.map((result) => ({
336
409
  agent: result.agent,
337
- block: formatCompletionBlock(result, maxResultLines, { resultRoot: projectResultsRoot(runtime.configPath, result.projectCwd ?? ctx.cwd) }),
410
+ block: formatCompletionBlock(result, DEFAULT_MAX_RESULT_LINES, { resultRoot: projectResultsRoot(runtime.configPath, result.projectCwd ?? ctx.cwd) }),
338
411
  triggerTurn: true,
339
412
  usage: result.usage,
340
413
  })));
@@ -343,7 +416,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
343
416
  return {
344
417
  content: [{
345
418
  type: "text",
346
- text: `Stopped ${stopped.length} thread${stopped.length === 1 ? "" : "s"}: ${stopped.join(", ")}. Retained sessions were retired; worktree changes are integrated on settlement.${retainedIntegration.length > 0 ? ` Integration failed for ${retainedIntegration.join(", ")}; inspect its result for retained recovery paths.` : ""}${pendingIntegration.length > 0 ? ` Integration is still settling in the background for ${pendingIntegration.join(", ")}; a recovery record was persisted in case it fails.` : ""}`,
419
+ text: `${graphStops.length > 0 ? `Stopped ${graphStops.length} workflow${graphStops.length === 1 ? "" : "s"}: ${graphStops.join(", ")}. ` : ""}Stopped ${stopped.length} thread${stopped.length === 1 ? "" : "s"}: ${stopped.join(", ")}. Retained sessions were retired; worktree changes are integrated on settlement.${retainedIntegration.length > 0 ? ` Integration failed for ${retainedIntegration.join(", ")}; inspect its result for retained recovery paths.` : ""}${pendingIntegration.length > 0 ? ` Integration is still settling in the background for ${pendingIntegration.join(", ")}; a recovery record was persisted in case it fails.` : ""}`,
347
420
  }],
348
421
  details: {},
349
422
  };
@@ -40,6 +40,14 @@ export function isRunActiveStatus(status: RunStatus): boolean {
40
40
  * terminal WorktreeFinalizationStatus. */
41
41
  export type RunIntegrationStatus = "pending" | "finalizing" | WorktreeFinalizationStatus;
42
42
 
43
+ /** Workflow membership of a run: which graph, and which node of it. Rendered so
44
+ * a workflow's nodes read as one group in the widget and the status view. */
45
+ export interface RunWorkflowTag {
46
+ workflowId: number;
47
+ name: string;
48
+ nodeId: string;
49
+ }
50
+
43
51
  export interface RunView {
44
52
  id: number;
45
53
  agent: string;
@@ -73,11 +81,15 @@ export interface RunView {
73
81
  elapsedMs: number;
74
82
  /** Epoch ms when the latest active segment stopped. */
75
83
  endedAt?: number;
84
+ /** Workflow membership, when this run is a node of a `subagent_workflow` graph. */
85
+ workflow?: RunWorkflowTag;
76
86
  }
77
87
 
78
88
  export interface RunChainMeta {
79
89
  isolation?: IsolationMode;
80
90
  worktreeId?: string;
91
+ /** Set for nodes the workflow runner dispatches. */
92
+ workflow?: RunWorkflowTag;
81
93
  /** Initial wait reason; defaults to "process-slot" (a fresh dispatch enters
82
94
  * the process queue). Children spawned outside the queue pass "starting"
83
95
  * because they never wait for a slot. */
@@ -120,7 +132,7 @@ interface KeyFragment {
120
132
  * first occurrence and deduped (a path covers its own sub-fragments). These
121
133
  * are what make parallel tasks of the same agent look different.
122
134
  */
123
- export function extractKeyFragments(text: string): string[] {
135
+ function extractKeyFragments(text: string): string[] {
124
136
  const fragments: KeyFragment[] = [];
125
137
  const add = (re: RegExp, group = 0): void => {
126
138
  for (const m of text.matchAll(re)) {
@@ -232,7 +244,7 @@ export function formatTaskSummary(task: string, maxWidth: number = TASK_SUMMARY_
232
244
  }
233
245
 
234
246
  /** Max display width of a run's content label. */
235
- export const RUN_LABEL_MAX = 32;
247
+ const RUN_LABEL_MAX = 32;
236
248
 
237
249
  /**
238
250
  * Short content label for a run, derived from its task: the single most
@@ -267,7 +279,7 @@ export function shrinkRunLabel(text: string, maxWidth: number): string {
267
279
  return `${TASK_SUMMARY_ELLIPSIS}${tailGraphemes(chars, maxWidth - 1)}`;
268
280
  }
269
281
 
270
- export function formatTokens(count: number): string {
282
+ function formatTokens(count: number): string {
271
283
  if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M`;
272
284
  if (count >= 1_000) return `${(count / 1_000).toFixed(1)}k`;
273
285
  return String(count);
@@ -291,7 +303,7 @@ export function formatUsageCompact(usage: UsageStats): string {
291
303
  }
292
304
 
293
305
  /** Cost as its own droppable part: `$0.0421`, undefined when nothing accrued. */
294
- export function usageCostPart(usage: UsageStats | undefined): string | undefined {
306
+ function usageCostPart(usage: UsageStats | undefined): string | undefined {
295
307
  return usage?.cost ? `$${usage.cost.toFixed(4)}` : undefined;
296
308
  }
297
309
 
@@ -322,7 +334,7 @@ export function formatDuration(ms: number): string {
322
334
  return `${hours}h${String(minutes % 60).padStart(2, "0")}m${String(seconds).padStart(2, "0")}s`;
323
335
  }
324
336
 
325
- export function elapsedMilliseconds(run: RunView, now: number = Date.now()): number {
337
+ function elapsedMilliseconds(run: RunView, now: number = Date.now()): number {
326
338
  let elapsed = run.elapsedMs ?? 0;
327
339
  if (run.activeSince !== undefined) elapsed += Math.max(0, now - run.activeSince);
328
340
  // Keep formatting tolerant of older/synthetic RunView values that predate
@@ -339,7 +351,7 @@ export function formatElapsed(run: RunView, now: number = Date.now()): string {
339
351
  }
340
352
 
341
353
  /** Max length of the argument target inside a formatted activity line. */
342
- export const ACTIVITY_TARGET_MAX = 60;
354
+ const ACTIVITY_TARGET_MAX = 60;
343
355
 
344
356
  const REDACTED = "<redacted>";
345
357
 
@@ -383,9 +395,20 @@ function shortTarget(value: unknown): string {
383
395
  return chars.length > ACTIVITY_TARGET_MAX ? `${chars.slice(0, ACTIVITY_TARGET_MAX - 1).join("")}…` : oneLine;
384
396
  }
385
397
 
398
+ /** A code-mode script's first meaningful line: the earliest line that is not
399
+ * blank and not a `//` comment, shortened like any other activity target. */
400
+ function scriptLine(value: unknown): string {
401
+ if (typeof value !== "string") return "";
402
+ const line = value
403
+ .split("\n")
404
+ .map((part) => part.trim())
405
+ .find((part) => part.length > 0 && !part.startsWith("//"));
406
+ return line ? shortTarget(line) : "";
407
+ }
408
+
386
409
  /** Newest-last rolling window of what a run has been doing, surfaced to the
387
410
  * parent model as a progress trail. */
388
- export const RECENT_ACTIVITY_MAX = 6;
411
+ const RECENT_ACTIVITY_MAX = 6;
389
412
 
390
413
  /** Concise "what is it doing" text for a tool call: the tool name plus its single
391
414
  * most telling argument (path, command, pattern, ...) — never a raw JSON blob. */
@@ -416,17 +439,12 @@ export function formatToolActivity(toolName: string, args: unknown): string {
416
439
  break;
417
440
  case "grep":
418
441
  case "find":
419
- case "glob":
420
442
  target = pick("pattern", "query", "path");
421
443
  break;
422
- case "web_search":
423
- case "search":
424
- target = pick("query");
425
- break;
426
- case "fetch":
427
- case "web_fetch":
428
- case "fetch_content":
429
- target = pick("url");
444
+ case "codemode":
445
+ // A script is source, not a target: name its first meaningful line so the
446
+ // trail shows what the child is doing instead of a code blob.
447
+ target = scriptLine(a.code);
430
448
  break;
431
449
  case "subagent":
432
450
  target = pick("agent", "task");
@@ -488,7 +506,10 @@ export class MonitorStore {
488
506
  id,
489
507
  agent,
490
508
  task,
491
- label: runLabel(task),
509
+ // A graph node is identified by its graph and node id: the task text it
510
+ // actually runs is interpolated with upstream answers, which makes a
511
+ // fragment-extracted label read like noise.
512
+ label: meta?.workflow ? `${meta.workflow.name}/${meta.workflow.nodeId}` : runLabel(task),
492
513
  model,
493
514
  thinking,
494
515
  status: "queued",
@@ -496,6 +517,7 @@ export class MonitorStore {
496
517
  usage: emptyUsage(),
497
518
  elapsedMs: 0,
498
519
  ...(meta?.isolation ? { isolation: meta.isolation, integrationStatus: meta.isolation === "worktree" ? "pending" : undefined, ...(meta.worktreeId ? { worktreeId: meta.worktreeId } : {}) } : {}),
520
+ ...(meta?.workflow ? { workflow: meta.workflow } : {}),
499
521
  });
500
522
  this.notify();
501
523
  return id;
@@ -29,7 +29,7 @@ import {
29
29
  type RunView,
30
30
  } from "./monitor.ts";
31
31
 
32
- export const SUBAGENTS_WIDGET_ID = "pi-subagents";
32
+ const SUBAGENTS_WIDGET_ID = "pi-subagents";
33
33
 
34
34
  /** The TUI caps string-array widgets at this many lines; a factory widget owns
35
35
  * the same bound itself, or a wide parallel dispatch floods the editor area. */
@@ -65,7 +65,7 @@ function composeLine(left: string, tail: string, theme: Theme, width: number): s
65
65
  /** Short truthful wait word for a queued row — shown in the widget telemetry
66
66
  * column and aggregated into the footer status line, so both surfaces name a
67
67
  * wait the same way. */
68
- export function waitWord(run: Pick<RunView, "waitReason">): string {
68
+ function waitWord(run: Pick<RunView, "waitReason">): string {
69
69
  switch (run.waitReason) {
70
70
  case "repository-lane":
71
71
  return "repo lane";
@@ -0,0 +1,195 @@
1
+ /**
2
+ * Durable workflow records: what a graph had completed, what it was still
3
+ * running, and the plan itself, so a crashed or reloaded session can still
4
+ * explain what was in flight.
5
+ *
6
+ * The graph is not resumed automatically — each node is an ordinary sub-agent
7
+ * thread with its own durable record and retained session, and main finishes
8
+ * that work with its own tools. This manifest keeps the *shape* of the run
9
+ * (which nodes settled, which were pending, which were blocked) queryable
10
+ * instead of leaving a pile of unrelated parked threads.
11
+ *
12
+ * One manifest per project, written atomically, like the thread manifest; a
13
+ * settled workflow removes its record, so the file exists exactly while
14
+ * unfinished work needs explaining.
15
+ */
16
+
17
+ import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
18
+ import { readdirSync } from "node:fs";
19
+ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
20
+ import { dirname, isAbsolute, join, resolve } from "node:path";
21
+ import { getProjectRoot, getSubagentsRoot } from "../execution/spawn.ts";
22
+ import { PARKED_RECORD_MAX_AGE_MS } from "../lifecycle/durable.ts";
23
+
24
+ export const WORKFLOWS_MANIFEST_FILE_NAME = "pi-subagents-workflows.json";
25
+ const WORKFLOWS_MANIFEST_VERSION = 1;
26
+
27
+ export type RecordedNodeState = "pending" | "running" | "completed" | "failed" | "blocked" | "stopped";
28
+
29
+ export interface WorkflowRecordNode {
30
+ id: string;
31
+ agent: string;
32
+ task: string;
33
+ dependsOn: string[];
34
+ state: RecordedNodeState;
35
+ runId?: number;
36
+ error?: string;
37
+ }
38
+
39
+ export interface WorkflowRecord {
40
+ workflowId: number;
41
+ name: string;
42
+ description?: string;
43
+ cwd: string;
44
+ /** How the graph stopped being live. */
45
+ state: "running" | "stopped" | "interrupted";
46
+ startedAt: number;
47
+ updatedAt: number;
48
+ stopReason?: string;
49
+ nodes: WorkflowRecordNode[];
50
+ }
51
+
52
+ interface WorkflowsManifest {
53
+ version: number;
54
+ records: WorkflowRecord[];
55
+ }
56
+
57
+ const NODE_STATES = new Set<RecordedNodeState>([
58
+ "pending",
59
+ "running",
60
+ "completed",
61
+ "failed",
62
+ "blocked",
63
+ "stopped",
64
+ ]);
65
+
66
+ export function getWorkflowsManifestPath(configPath: string, cwd: string): string {
67
+ return join(getProjectRoot(configPath, cwd), WORKFLOWS_MANIFEST_FILE_NAME);
68
+ }
69
+
70
+ function normalizeNode(value: unknown): WorkflowRecordNode | undefined {
71
+ if (!value || typeof value !== "object") return undefined;
72
+ const raw = value as Record<string, unknown>;
73
+ if (typeof raw.id !== "string" || !raw.id) return undefined;
74
+ if (typeof raw.agent !== "string" || !raw.agent) return undefined;
75
+ if (typeof raw.state !== "string" || !NODE_STATES.has(raw.state as RecordedNodeState)) return undefined;
76
+ return {
77
+ id: raw.id,
78
+ agent: raw.agent,
79
+ task: typeof raw.task === "string" ? raw.task : "",
80
+ dependsOn: Array.isArray(raw.dependsOn)
81
+ ? raw.dependsOn.filter((dep): dep is string => typeof dep === "string")
82
+ : [],
83
+ state: raw.state as RecordedNodeState,
84
+ ...(typeof raw.runId === "number" && Number.isInteger(raw.runId) && raw.runId > 0 ? { runId: raw.runId } : {}),
85
+ ...(typeof raw.error === "string" && raw.error ? { error: raw.error } : {}),
86
+ };
87
+ }
88
+
89
+ function normalizeRecord(value: unknown): WorkflowRecord | undefined {
90
+ if (!value || typeof value !== "object") return undefined;
91
+ const raw = value as Record<string, unknown>;
92
+ if (typeof raw.workflowId !== "number" || !Number.isInteger(raw.workflowId) || raw.workflowId < 1) return undefined;
93
+ if (typeof raw.name !== "string" || !raw.name) return undefined;
94
+ if (typeof raw.cwd !== "string" || !raw.cwd || !isAbsolute(raw.cwd)) return undefined;
95
+ if (raw.cwd !== resolve(raw.cwd)) return undefined;
96
+ if (raw.state !== "running" && raw.state !== "stopped" && raw.state !== "interrupted") return undefined;
97
+ if (typeof raw.startedAt !== "number" || typeof raw.updatedAt !== "number") return undefined;
98
+ if (!Array.isArray(raw.nodes)) return undefined;
99
+ const nodes = raw.nodes.map(normalizeNode);
100
+ if (nodes.some((node) => node === undefined)) return undefined;
101
+ return {
102
+ workflowId: raw.workflowId,
103
+ name: raw.name,
104
+ ...(typeof raw.description === "string" && raw.description ? { description: raw.description } : {}),
105
+ cwd: raw.cwd,
106
+ state: raw.state,
107
+ startedAt: raw.startedAt,
108
+ updatedAt: raw.updatedAt,
109
+ ...(typeof raw.stopReason === "string" && raw.stopReason ? { stopReason: raw.stopReason } : {}),
110
+ nodes: nodes as WorkflowRecordNode[],
111
+ };
112
+ }
113
+
114
+ async function readManifestRecords(path: string): Promise<WorkflowRecord[]> {
115
+ try {
116
+ const parsed = JSON.parse(await readFile(path, "utf8")) as { records?: unknown };
117
+ if (!Array.isArray(parsed.records)) return [];
118
+ return parsed.records.flatMap((record) => {
119
+ const normalized = normalizeRecord(record);
120
+ return normalized ? [normalized] : [];
121
+ });
122
+ } catch {
123
+ return [];
124
+ }
125
+ }
126
+
127
+ async function writeManifest(path: string, records: readonly WorkflowRecord[]): Promise<void> {
128
+ if (records.length === 0) {
129
+ await rm(path, { force: true });
130
+ return;
131
+ }
132
+ await mkdir(dirname(path), { recursive: true });
133
+ const temporaryPath = `${path}.${process.pid}.${Date.now()}.tmp`;
134
+ try {
135
+ const manifest: WorkflowsManifest = { version: WORKFLOWS_MANIFEST_VERSION, records: [...records] };
136
+ await writeFile(temporaryPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
137
+ await rename(temporaryPath, path);
138
+ } finally {
139
+ await rm(temporaryPath, { force: true }).catch(() => undefined);
140
+ }
141
+ }
142
+
143
+ export async function upsertWorkflowRecord(configPath: string, record: WorkflowRecord): Promise<void> {
144
+ const path = getWorkflowsManifestPath(configPath, record.cwd);
145
+ await withFileMutationQueue(path, async () => {
146
+ const records = await readManifestRecords(path);
147
+ const index = records.findIndex((candidate) => candidate.workflowId === record.workflowId);
148
+ const merged: WorkflowRecord = index === -1
149
+ ? record
150
+ : { ...record, startedAt: records[index]!.startedAt };
151
+ if (index === -1) records.push(merged);
152
+ else records[index] = merged;
153
+ await writeManifest(path, records);
154
+ });
155
+ }
156
+
157
+ export async function removeWorkflowRecord(configPath: string, workflowId: number, cwd: string): Promise<void> {
158
+ const path = getWorkflowsManifestPath(configPath, cwd);
159
+ await withFileMutationQueue(path, async () => {
160
+ const records = await readManifestRecords(path);
161
+ const next = records.filter((record) => record.workflowId !== workflowId);
162
+ if (next.length === records.length) return;
163
+ await writeManifest(path, next);
164
+ });
165
+ }
166
+
167
+ /** Records for one checkout, newest first. */
168
+ export async function readWorkflowRecords(configPath: string, cwd: string): Promise<WorkflowRecord[]> {
169
+ const path = getWorkflowsManifestPath(configPath, cwd);
170
+ const records = (await readManifestRecords(path)).filter(
171
+ (record) => process.platform === "win32"
172
+ ? record.cwd.toLowerCase() === resolve(cwd).toLowerCase()
173
+ : record.cwd === resolve(cwd),
174
+ );
175
+ return records.sort((left, right) => right.updatedAt - left.updatedAt);
176
+ }
177
+
178
+ /** Drop records no longer worth explaining. Runs at session start. */
179
+ export async function pruneWorkflowRecords(configPath: string, now = Date.now()): Promise<void> {
180
+ let projects: string[];
181
+ try {
182
+ projects = readdirSync(getSubagentsRoot(configPath), { withFileTypes: true })
183
+ .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())
184
+ .map((entry) => join(getSubagentsRoot(configPath), entry.name, WORKFLOWS_MANIFEST_FILE_NAME));
185
+ } catch {
186
+ return;
187
+ }
188
+ for (const path of projects) {
189
+ await withFileMutationQueue(path, async () => {
190
+ const records = await readManifestRecords(path);
191
+ const kept = records.filter((record) => now - record.updatedAt <= PARKED_RECORD_MAX_AGE_MS);
192
+ if (kept.length !== records.length) await writeManifest(path, kept);
193
+ });
194
+ }
195
+ }