@ferris1225/pi-subagents 5.0.5 → 6.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.
@@ -15,6 +15,7 @@
15
15
  * as for a failed one-shot run.
16
16
  */
17
17
 
18
+ import { randomUUID } from "node:crypto";
18
19
  import { isFailedResult, getResultError, getResultOutput, truncateResultOutput, writeResultArtifact, type SingleResult } from "../execution/spawn.ts";
19
20
  import { formatDuration, formatTaskSummary, monitor, runWaitLabel } from "../presentation/monitor.ts";
20
21
  import { perModelTotals, type CompletionMessageItem } from "../lifecycle/completion.ts";
@@ -27,11 +28,13 @@ import {
27
28
  readWorkflowRecords,
28
29
  removeWorkflowRecord,
29
30
  upsertWorkflowRecord,
31
+ workflowRecordIdentity,
30
32
  type RecordedNodeState,
31
33
  type WorkflowRecord,
32
34
  } from "./durable.ts";
33
35
  import type { WorkflowNodeRun, WorkflowRun, WorkflowRunState } from "./state.ts";
34
36
  import type { PhaseScope } from "../delegation/phase-scope.ts";
37
+ import { buildAcceptanceBrief, parseAcceptanceVerdict, WORKFLOW_ACCEPTANCE_AGENT, WORKFLOW_ACCEPTANCE_ID } from "./acceptance.ts";
35
38
 
36
39
  /** Lines of one node's answer inlined into the graph summary. The complete text
37
40
  * of every node is always written to a single workflow artifact, so nothing is
@@ -133,16 +136,27 @@ function waitForNodeSettlement(
133
136
  });
134
137
  }
135
138
 
139
+ function canDispatch(ctx: RunContext): boolean {
140
+ return ctx.run.state === "running" && !ctx.run.controller.signal.aborted && ctx.runtime.sessionActive;
141
+ }
142
+
136
143
  async function dispatchNode(ctx: RunContext, node: WorkflowNodeRun): Promise<void> {
137
144
  const { run } = ctx;
138
- const upstream = new Map<string, UpstreamOutput>();
139
- for (const dependency of node.ancestors) {
140
- const upstreamNode = nodeById(run, dependency);
141
- if (upstreamNode) upstream.set(dependency, upstreamView(upstreamNode));
142
- }
143
- const task = renderNodeTask(node.task, upstream);
145
+ if (!canDispatch(ctx)) return;
144
146
  node.state = "running";
145
147
  node.startedAt = Date.now();
148
+ let task: string;
149
+ if (node.kind === "acceptance") {
150
+ node.evidenceFile = writeResultArtifact(formatWorkflowReport(run), `workflow-${run.slug}-acceptance-evidence`, ctx.resultsRoot);
151
+ task = buildAcceptanceBrief(run, node.evidenceFile);
152
+ } else {
153
+ const upstream = new Map<string, UpstreamOutput>();
154
+ for (const dependency of node.ancestors) {
155
+ const upstreamNode = nodeById(run, dependency);
156
+ if (upstreamNode) upstream.set(dependency, upstreamView(upstreamNode));
157
+ }
158
+ task = renderNodeTask(node.task, upstream);
159
+ }
146
160
  let started: SingleResult;
147
161
  try {
148
162
  started = await ctx.startBackground(node.agent, task, node.cwd, node.isolation ?? ctx.resolveIsolation(node.agent), {
@@ -169,20 +183,21 @@ async function dispatchNode(ctx: RunContext, node: WorkflowNodeRun): Promise<voi
169
183
  return;
170
184
  }
171
185
  node.runId = started.runId;
186
+ node.durableRunId = ctx.runtime.threads.get(started.runId)?.durableId;
172
187
  await checkpoint(ctx);
173
188
  if (run.state === "stopped") await stopThreads(ctx.runtime, [started.runId], run.stopReason);
174
189
  const result = await waitForNodeSettlement(ctx.runtime, started.runId, run.controller.signal);
175
190
  node.endedAt = Date.now();
176
191
  node.result = result;
177
- if (result && getResultOutput(result).length > UPSTREAM_OUTPUT_MAX_CHARS && !result.resultFile) {
192
+ if (result && (node.kind === "acceptance" || getResultOutput(result).length > UPSTREAM_OUTPUT_MAX_CHARS) && !result.resultFile) {
178
193
  try {
179
194
  result.resultFile = writeResultArtifact(getResultOutput(result), `workflow-${run.slug}-${node.id}`, ctx.resultsRoot);
180
195
  } catch {
181
196
  /* The dependent brief explicitly reports an unavailable full answer. */
182
197
  }
183
198
  }
184
- if (run.state !== "running") {
185
- if (result && !isFailedResult(result)) { node.state = "completed"; return; }
199
+ if (run.state !== "running" || run.controller.signal.aborted || !ctx.runtime.sessionActive) {
200
+ if (node.kind !== "acceptance" && result && !isFailedResult(result)) { node.state = "completed"; return; }
186
201
  node.state = "stopped";
187
202
  node.error ??= run.stopReason ?? "workflow stopped";
188
203
  return;
@@ -201,6 +216,15 @@ async function dispatchNode(ctx: RunContext, node: WorkflowNodeRun): Promise<voi
201
216
  );
202
217
  return;
203
218
  }
219
+ if (node.kind === "acceptance") {
220
+ const review = parseAcceptanceVerdict(getResultOutput(result));
221
+ if (review.verdict !== "PASS") {
222
+ node.state = "failed";
223
+ node.error = review.error ?? "Required acceptance rejected the integrated outcome (WORKFLOW_ACCEPTANCE: FAIL). Read the review result for blockers and limitations.";
224
+ ctx.notify(`✗ workflow ${run.name} · required acceptance rejected: ${formatTaskSummary(node.error, 200, false)}`, "error");
225
+ return;
226
+ }
227
+ }
204
228
  node.state = "completed";
205
229
  }
206
230
 
@@ -209,7 +233,7 @@ async function dispatchNode(ctx: RunContext, node: WorkflowNodeRun): Promise<voi
209
233
  function blockDependents(run: WorkflowRun): boolean {
210
234
  let changed = false;
211
235
  for (const node of run.nodes) {
212
- if (node.state !== "pending") continue;
236
+ if (node.state !== "pending" || node.kind === "acceptance") continue;
213
237
  const broken = node.dependsOn.find((dependency) => {
214
238
  const state = nodeById(run, dependency)?.state;
215
239
  return state !== undefined && terminalFailure(state);
@@ -233,13 +257,23 @@ async function drive(ctx: RunContext): Promise<void> {
233
257
  const inFlight = new Set<Promise<void>>();
234
258
  await checkpoint(ctx);
235
259
  while (run.state === "running") {
260
+ if (!ctx.runtime.sessionActive) {
261
+ await persistInterruptedWorkflows(ctx.runtime);
262
+ break;
263
+ }
236
264
  while (blockDependents(run)) { /* Propagate through any author order. */ }
237
265
  const ready = run.nodes.filter(
238
266
  (node) =>
239
267
  node.state === "pending" &&
240
- node.dependsOn.every((dependency) => nodeById(run, dependency)?.state === "completed"),
268
+ node.dependsOn.every((dependency) => {
269
+ const state = nodeById(run, dependency)?.state;
270
+ return node.kind === "acceptance"
271
+ ? state !== undefined && state !== "pending" && state !== "running"
272
+ : state === "completed";
273
+ }),
241
274
  );
242
275
  for (const node of ready) {
276
+ if (!canDispatch(ctx)) break;
243
277
  // dispatchNode marks the node running synchronously, so the next pass
244
278
  // cannot start it twice.
245
279
  const task = dispatchNode(ctx, node).catch((error: unknown) => {
@@ -279,7 +313,10 @@ function stateLabel(state: WorkflowRunState): string {
279
313
  }
280
314
  }
281
315
 
282
- function nodeStateWord(node: WorkflowNodeRun): string {
316
+ function nodeStateWord(node: Pick<WorkflowNodeRun, "kind" | "state">): string {
317
+ if (node.kind === "acceptance") {
318
+ return `required acceptance ${node.state === "completed" ? "accepted" : node.state === "failed" ? "rejected" : node.state}`;
319
+ }
283
320
  return node.state === "blocked" ? "never ran (blocked)" : node.state;
284
321
  }
285
322
 
@@ -317,9 +354,13 @@ export function formatWorkflowReport(run: WorkflowRun): string {
317
354
  for (const node of run.nodes) {
318
355
  const output = node.result ? getResultOutput(node.result).trim() : "";
319
356
  lines.push("", `## ${node.id} (${node.agent}) — ${nodeStateWord(node)}`, "");
357
+ lines.push(`Phase: ${node.phaseId}`, `Working directory: ${node.cwd}`, `Dependencies: ${node.dependsOn.join(", ") || "none"}`);
358
+ if (node.scope) lines.push(`Declared scope: ${JSON.stringify(node.scope)}`);
359
+ if (node.result?.integrationStatus) lines.push(`Integration: ${node.result.integrationStatus}`);
360
+ lines.push(`Task / done condition:\n${node.task}`, "");
320
361
  lines.push(output || "(no answer recorded)");
321
362
  if (node.error) lines.push("", `Error: ${node.error}`);
322
- for (const [label, path] of [["Full result", node.result?.resultFile], ["Retained worktree", node.result?.integrationWorktreePath], ["Retained patch", node.result?.integrationPatchPath]]) {
363
+ 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]]) {
323
364
  if (path) lines.push(`${label}: ${path}`);
324
365
  }
325
366
  }
@@ -360,7 +401,8 @@ export function formatWorkflowSummary(run: WorkflowRun, resultsRoot?: string): s
360
401
  const inline = inlineNodeAnswer(node);
361
402
  if (!inline.text) continue;
362
403
  if (inline.truncated) anyTruncated = true;
363
- answers.push(`#### ${node.id} (${node.agent})`, inline.text, "");
404
+ answers.push(`#### ${node.id} (${node.agent})${node.kind === "acceptance" ? " — required acceptance review" : ""}`, inline.text, "");
405
+ if (node.kind === "acceptance" && node.result?.resultFile) answers.push(`Full acceptance review: ${node.result.resultFile}`, "");
364
406
  }
365
407
  if (answers.length > 0) {
366
408
  lines.push("", "Node answers:", "", ...answers);
@@ -389,7 +431,9 @@ export function formatWorkflowSummary(run: WorkflowRun, resultsRoot?: string): s
389
431
  }
390
432
 
391
433
  function workflowRecord(run: WorkflowRun, state: WorkflowRecord["state"]): WorkflowRecord {
434
+ run.durableId ??= randomUUID();
392
435
  return {
436
+ durableId: run.durableId,
393
437
  workflowId: run.id,
394
438
  name: run.name,
395
439
  ...(run.description ? { description: run.description } : {}),
@@ -403,8 +447,12 @@ function workflowRecord(run: WorkflowRun, state: WorkflowRecord["state"]): Workf
403
447
  agent: node.agent,
404
448
  task: node.task,
405
449
  dependsOn: [...node.dependsOn],
450
+ ...(node.kind ? { kind: node.kind } : {}),
451
+ ...(node.evidenceFile ? { evidenceFile: node.evidenceFile } : {}),
452
+ ...(node.result?.resultFile ? { resultFile: node.result.resultFile } : {}),
406
453
  state: node.state as RecordedNodeState,
407
454
  ...(node.runId !== undefined ? { runId: node.runId } : {}),
455
+ ...(node.durableRunId ? { durableRunId: node.durableRunId } : {}),
408
456
  ...(node.error ? { error: node.error } : {}),
409
457
  })),
410
458
  };
@@ -416,11 +464,12 @@ async function settle(ctx: RunContext): Promise<void> {
416
464
  // it is the evidence the next session explains, not a settled run.
417
465
  const interrupted = run.state === "interrupted";
418
466
  if (run.state === "running") {
419
- run.state = run.nodes.some((node) => node.state !== "completed") ? "failed" : "completed";
467
+ const accepted = run.nodes.some((node) => node.kind === "acceptance" && node.state === "completed");
468
+ run.state = !accepted || run.nodes.some((node) => node.state !== "completed") ? "failed" : "completed";
420
469
  }
421
470
  run.endedAt ??= Date.now();
422
471
  if (runtime.sessionActive) monitor.updateWorkflow(run);
423
- if (!interrupted) await removeWorkflowRecord(runtime.configPath, run.id, run.cwd).catch(() => undefined);
472
+ if (!interrupted && run.durableId) await removeWorkflowRecord(runtime.configPath, run.durableId, run.cwd).catch(() => undefined);
424
473
  if (!runtime.sessionActive) return;
425
474
  const item: CompletionMessageItem = {
426
475
  agent: `workflow:${run.name}`,
@@ -473,8 +522,18 @@ export function findOwnedPhases(runtime: SubagentRuntime, workflow: CompiledWork
473
522
 
474
523
  /** Start a compiled graph. Nodes dispatch as their prerequisites settle. */
475
524
  export function startWorkflow(deps: WorkflowRunDeps, workflow: CompiledWorkflow): WorkflowHandle {
525
+ const work = workflow.nodes.filter((node) => node.kind !== "acceptance");
526
+ const reviews = workflow.nodes.filter((node) => node.kind === "acceptance");
527
+ const review = reviews[0];
528
+ if (reviews.length !== 1 || !review || review.id !== WORKFLOW_ACCEPTANCE_ID || review.agent !== WORKFLOW_ACCEPTANCE_AGENT ||
529
+ review.cwd !== workflow.cwd || review.isolation !== "shared" || review.scope ||
530
+ review.dependsOn.length !== work.length || work.some((node) => !review.dependsOn.includes(node.id))) {
531
+ throw new Error("A workflow requires exactly one compiler-owned independent acceptance node covering all authored work.");
532
+ }
476
533
  const runtime = deps.runtime;
534
+ const durableId = randomUUID();
477
535
  const run: WorkflowRun = {
536
+ durableId,
478
537
  id: runtime.reserveWorkflowId(),
479
538
  name: workflow.name,
480
539
  slug: workflow.slug,
@@ -485,6 +544,7 @@ export function startWorkflow(deps: WorkflowRunDeps, workflow: CompiledWorkflow)
485
544
  controller: new AbortController(),
486
545
  nodes: workflow.nodes.map((node) => ({
487
546
  id: node.id,
547
+ ...(node.kind ? { kind: node.kind } : {}),
488
548
  agent: node.agent,
489
549
  task: node.task,
490
550
  dependsOn: [...node.dependsOn],
@@ -497,6 +557,7 @@ export function startWorkflow(deps: WorkflowRunDeps, workflow: CompiledWorkflow)
497
557
  })),
498
558
  };
499
559
  runtime.workflows.set(run.id, run);
560
+ runtime.workflowRecordIds.set(durableId, run.id);
500
561
 
501
562
  let wakeRequested = false;
502
563
  let wakeResolver: (() => void) | undefined;
@@ -533,7 +594,7 @@ export function startWorkflow(deps: WorkflowRunDeps, workflow: CompiledWorkflow)
533
594
  run.endedAt = Date.now();
534
595
  run.stopReason = error instanceof Error ? error.message : String(error);
535
596
  deps.notify(`✗ workflow ${run.name} crashed: ${run.stopReason}`, "error");
536
- void removeWorkflowRecord(runtime.configPath, run.id, run.cwd).catch(() => undefined);
597
+ void removeWorkflowRecord(runtime.configPath, durableId, run.cwd).catch(() => undefined);
537
598
  return run;
538
599
  },
539
600
  );
@@ -585,26 +646,44 @@ export async function persistInterruptedWorkflows(runtime: SubagentRuntime): Pro
585
646
 
586
647
  export interface RetainedWorkflow {
587
648
  id: number;
649
+ durableId: string;
588
650
  name: string;
589
651
  state: WorkflowRecord["state"];
590
652
  stopReason?: string;
591
653
  updatedAt: number;
592
- nodes: WorkflowRecord["nodes"];
654
+ nodes: Array<WorkflowRecord["nodes"][number] & { originalRunId?: number }>;
593
655
  }
594
656
 
595
- /** Retained records for this checkout, offered to the status view and to the
596
- * session-start notice. Also raises the id allocator above restored graphs. */
657
+ /** Reconcile persisted identities with this window's ids. Never attach an old
658
+ * node to an unrelated run merely because their display numbers match. */
597
659
  export async function readRetainedWorkflows(runtime: SubagentRuntime, cwd: string): Promise<RetainedWorkflow[]> {
598
660
  const records = await readWorkflowRecords(runtime.configPath, cwd);
599
661
  for (const record of records) runtime.ensureWorkflowIdAbove(record.workflowId);
600
- return records.map((record) => ({
601
- id: record.workflowId,
602
- name: record.name,
603
- state: record.state === "running" ? "interrupted" : record.state,
604
- ...(record.stopReason ? { stopReason: record.stopReason } : {}),
605
- updatedAt: record.updatedAt,
606
- nodes: record.nodes,
607
- }));
662
+ const threadsByIdentity = new Map([...runtime.threads.values()].filter((thread) => thread.durableId)
663
+ .map((thread) => [thread.durableId!, thread.id]));
664
+ const allocated = new Set([...runtime.workflowRecordIds.values(), ...runtime.workflows.keys()]);
665
+ return records.map((record) => {
666
+ const durableId = workflowRecordIdentity(record);
667
+ let id = runtime.workflowRecordIds.get(durableId);
668
+ if (id === undefined) {
669
+ id = allocated.has(record.workflowId) ? runtime.reserveWorkflowId() : record.workflowId;
670
+ runtime.workflowRecordIds.set(durableId, id);
671
+ allocated.add(id);
672
+ }
673
+ return {
674
+ id, durableId, name: record.name,
675
+ state: record.state === "running" ? "interrupted" : record.state,
676
+ ...(record.stopReason ? { stopReason: record.stopReason } : {}),
677
+ updatedAt: record.updatedAt,
678
+ nodes: record.nodes.map((node) => {
679
+ const { runId: originalRunId, ...facts } = node;
680
+ const runId = node.durableRunId ? threadsByIdentity.get(node.durableRunId) : undefined;
681
+ return { ...facts, ...(runId === undefined
682
+ ? originalRunId === undefined ? {} : { originalRunId }
683
+ : { runId }) };
684
+ }),
685
+ };
686
+ });
608
687
  }
609
688
 
610
689
  /** Status-facing projection of a live or settled graph. */
@@ -619,6 +698,9 @@ export interface WorkflowStatusView {
619
698
  endedAt?: number;
620
699
  nodes: Array<{
621
700
  id: string;
701
+ kind?: "acceptance";
702
+ evidenceFile?: string;
703
+ resultFile?: string;
622
704
  agent: string;
623
705
  state: WorkflowNodeRun["state"];
624
706
  task: string;
@@ -647,6 +729,9 @@ export function workflowStatus(run: WorkflowRun): WorkflowStatusView {
647
729
  const live = node.runId === undefined ? undefined : monitor.findRun(node.runId);
648
730
  return {
649
731
  id: node.id,
732
+ ...(node.kind ? { kind: node.kind } : {}),
733
+ ...(node.evidenceFile ? { evidenceFile: node.evidenceFile } : {}),
734
+ ...(node.result?.resultFile ? { resultFile: node.result.resultFile } : {}),
650
735
  agent: node.agent,
651
736
  state: node.state,
652
737
  task: formatTaskSummary(node.task, 160, false),
@@ -672,7 +757,7 @@ export function formatWorkflowStatus(run: WorkflowRun): string[] {
672
757
  if (view.description) lines.push(` ${view.description}`);
673
758
  if (view.stopReason) lines.push(` stop reason: ${formatTaskSummary(view.stopReason, 200, false)}`);
674
759
  for (const node of view.nodes) {
675
- const parts = [`${node.id} (${node.agent}) ${node.state}`];
760
+ const parts = [`${node.id} (${node.agent}) ${nodeStateWord(node)}`];
676
761
  if (node.runId !== undefined) parts.push(`run #${node.runId}`);
677
762
  if (node.waitingFor) parts.push(`waiting for ${node.waitingFor.join(", ")}`);
678
763
  if (node.elapsedMs !== undefined) parts.push(formatDuration(node.elapsedMs));
@@ -695,10 +780,13 @@ export function formatRetainedWorkflow(record: RetainedWorkflow): string[] {
695
780
  ];
696
781
  if (record.stopReason) lines.push(" stop reason: " + formatTaskSummary(record.stopReason, 200, false));
697
782
  for (const node of record.nodes) {
698
- const parts = [node.id + " (" + node.agent + ") " + node.state];
783
+ const parts = [node.id + " (" + node.agent + ") " + nodeStateWord(node)];
699
784
  if (node.runId !== undefined) parts.push("run #" + node.runId);
785
+ else if (node.originalRunId !== undefined) parts.push("original run #" + node.originalRunId + " (not restored in this window)");
700
786
  if (node.dependsOn.length > 0) parts.push("after " + node.dependsOn.join(", "));
701
787
  if (node.error) parts.push("error: " + formatTaskSummary(node.error, 160, false));
788
+ if (node.evidenceFile) parts.push("acceptance evidence: " + node.evidenceFile);
789
+ if (node.resultFile) parts.push("full result: " + node.resultFile);
702
790
  lines.push(" - " + parts.join(" · "));
703
791
  }
704
792
  lines.push(" A retained graph is not resumed automatically: main finishes the unfinished nodes from their run evidence.");
@@ -20,9 +20,10 @@ import {
20
20
  type PhaseScopeInput,
21
21
  } from "../delegation/phase-scope.ts";
22
22
  import type { IsolationMode } from "../isolation/worktree.ts";
23
+ import { acceptanceTask, WORKFLOW_ACCEPTANCE_AGENT, WORKFLOW_ACCEPTANCE_ID } from "./acceptance.ts";
23
24
 
24
- /** Nodes per graph. A workflow pays for one model session per node, so this is
25
- * a guard against a graph nobody will read, not a concurrency limit. */
25
+ /** Authored nodes per graph, plus one mandatory internal acceptance session.
26
+ * This bounds graph size rather than concurrency. */
26
27
  export const WORKFLOW_NODE_LIMIT = 24;
27
28
 
28
29
  export const WORKFLOW_NODE_ID_MAX_LENGTH = 40;
@@ -56,6 +57,8 @@ export interface WorkflowPlanInput {
56
57
 
57
58
  export interface CompiledWorkflowNode {
58
59
  id: string;
60
+ /** Compiler-owned required review; authored work omits kind. */
61
+ kind?: "acceptance";
59
62
  agent: string;
60
63
  task: string;
61
64
  /** Direct prerequisites, in author order. */
@@ -82,7 +85,7 @@ export interface CompiledWorkflow {
82
85
  }
83
86
 
84
87
  /** Placeholder syntax accepted in a node's task. */
85
- const PLACEHOLDER = /\{\{\s*([^{}]+?)\s*\}\}/gu;
88
+ const PLACEHOLDER = /(?<!\\)\{\{\s*([^{}]+?)\s*\}\}/gu;
86
89
  const FACT_SUFFIXES = [".status", ".runId", ".error"] as const;
87
90
  type PlaceholderFact = "output" | "status" | "runId" | "error";
88
91
 
@@ -207,6 +210,7 @@ export function compileWorkflow(
207
210
  throw new Error(error instanceof Error ? error.message : String(error));
208
211
  }
209
212
 
213
+ if (!knownAgents.includes(WORKFLOW_ACCEPTANCE_AGENT)) problems.push(`Required acceptance agent "${WORKFLOW_ACCEPTANCE_AGENT}" is not an enabled agent.`);
210
214
  const ids: string[] = [];
211
215
  const seenIds = new Set<string>();
212
216
  for (const [index, node] of rawNodes.entries()) {
@@ -218,6 +222,7 @@ export function compileWorkflow(
218
222
  );
219
223
  continue;
220
224
  }
225
+ if (id === WORKFLOW_ACCEPTANCE_ID) problems.push(`${label}.id "${id}" is reserved for required workflow acceptance.`);
221
226
  if (seenIds.has(id)) {
222
227
  problems.push(`${label}.id "${id}" is declared twice; node ids identify results and dependencies.`);
223
228
  continue;
@@ -303,6 +308,19 @@ export function compileWorkflow(
303
308
  });
304
309
  }
305
310
 
311
+ // Append before ownership checks so authored phase ids cannot collide with
312
+ // the mandatory reviewer. The authored node limit remains unchanged.
313
+ nodes.push({
314
+ id: WORKFLOW_ACCEPTANCE_ID,
315
+ kind: "acceptance",
316
+ agent: WORKFLOW_ACCEPTANCE_AGENT,
317
+ task: acceptanceTask(name),
318
+ dependsOn: [...ids],
319
+ ancestors: [...ids],
320
+ cwd: resolve(callerCwd),
321
+ isolation: "shared",
322
+ });
323
+
306
324
  for (const [index, node] of nodes.entries()) {
307
325
  const phaseId = node.phaseId ?? defaultPhaseId({ slug: slugify(name) }, node);
308
326
  const duplicate = nodes.slice(0, index).find((other) => {
@@ -362,7 +380,10 @@ function boundOutput(view: UpstreamOutput): string {
362
380
 
363
381
  /** Render a node's brief, substituting facts from the nodes it waited for. */
364
382
  export function renderNodeTask(task: string, upstream: ReadonlyMap<string, UpstreamOutput>): string {
365
- const rendered = task.replace(PLACEHOLDER, (whole, rawToken: string) => {
383
+ const rendered = task.replace(/\\\{\{|\{\{\s*([^{}]+?)\s*\}\}/gu, (whole, rawToken: string | undefined) => {
384
+ // Literal task inputs are unescaped in this pass, never interpreted as
385
+ // dependencies or reprocessed after an upstream answer is inserted.
386
+ if (rawToken === undefined) return "{{";
366
387
  const { id, fact } = splitPlaceholder(rawToken.trim(), (id) => upstream.has(id));
367
388
  const view = upstream.get(id);
368
389
  if (!view) return whole;
@@ -12,6 +12,9 @@ export type WorkflowNodeState = RecordedNodeState;
12
12
 
13
13
  export interface WorkflowNodeRun {
14
14
  id: string;
15
+ kind?: "acceptance";
16
+ /** Complete pre-review graph evidence retained for independent acceptance. */
17
+ evidenceFile?: string;
15
18
  agent: string;
16
19
  /** Authored brief, still carrying its result placeholders. */
17
20
  task: string;
@@ -23,6 +26,7 @@ export interface WorkflowNodeRun {
23
26
  cwd: string;
24
27
  state: WorkflowNodeState;
25
28
  runId?: number;
29
+ durableRunId?: string;
26
30
  startedAt?: number;
27
31
  endedAt?: number;
28
32
  result?: SingleResult;
@@ -32,6 +36,8 @@ export interface WorkflowNodeRun {
32
36
  export type WorkflowRunState = "running" | "completed" | "failed" | "stopped" | "interrupted";
33
37
 
34
38
  export interface WorkflowRun {
39
+ /** Stable persisted identity; id is local to this Pi window. */
40
+ durableId?: string;
35
41
  id: number;
36
42
  name: string;
37
43
  slug: string;
@@ -0,0 +1,156 @@
1
+ /** Built-in workflow plans and their explicit input slots. Runtime policy lives
2
+ * in the compiler/runner; templates contain only task-specific briefs. */
3
+
4
+ import { createHash } from "node:crypto";
5
+ import { compileWorkflow, type CompiledWorkflow, type WorkflowPlanInput } from "./plan.ts";
6
+
7
+ export const WORKFLOW_INPUT_KEYS = [
8
+ "QUESTION", "TARGET", "CONTRACT", "CORE_CHANGE", "ADAPTER_CHANGE",
9
+ "CORE_SCOPE", "CORE_TEST_SCOPE", "ADAPTER_SCOPE", "ADAPTER_TEST_SCOPE",
10
+ ] as const;
11
+
12
+ const INPUT_PATTERN = new RegExp(`<(${WORKFLOW_INPUT_KEYS.join("|")})>`, "gu");
13
+
14
+ /** Each lookup returns a fresh plan so customizing one dispatch cannot mutate
15
+ * the catalog used by the next dispatch. */
16
+ export function builtinWorkflowPlans(): WorkflowPlanInput[] {
17
+ return [
18
+ {
19
+ name: "code-review",
20
+ description: "Inspect a target change; the required acceptance review checks the findings and evidence.",
21
+ nodes: [{
22
+ id: "review",
23
+ agent: "sentinel",
24
+ task: "Review <TARGET> against the stated requirements and relevant callers. Establish the diff once, then inspect correctness, regressions, compatibility, and concrete failure paths within that target. Reuse existing research and valid checks; run a focused reproduction only to resolve a suspected defect. Stay read-only and do not change Git state. Return confirmed actionable findings with path:line, trigger, consequence, evidence, and smallest fix; include checks and material gaps. State clearly if no confirmed findings were found. The final acceptance officer will verify the report and its evidence; do not add another general review.",
25
+ }],
26
+ },
27
+ {
28
+ name: "research",
29
+ description: "Research a question from independent angles, synthesize an answer, and submit its evidence for acceptance.",
30
+ nodes: [
31
+ {
32
+ id: "primary",
33
+ agent: "scout",
34
+ task: "Research <QUESTION> from first-party sources only: official documentation, specifications, release notes, and the project's own repository. Record versions and dates. Cite every fact you state. Mark anything you could only find second-hand.",
35
+ },
36
+ {
37
+ id: "practice",
38
+ agent: "scout",
39
+ task: "Research <QUESTION> from practice: issue threads, migration notes, benchmarks, and post-mortems that describe what actually happened when people used it. Separate reported experience from vendor claims and cite each source.",
40
+ },
41
+ {
42
+ id: "codebase",
43
+ agent: "scout",
44
+ task: "Establish what this repository already does about <QUESTION>: the relevant modules, configuration, and tests, with path:line citations. State where the code disagrees with the documentation if you find such a place.",
45
+ },
46
+ {
47
+ id: "synthesis",
48
+ agent: "scout",
49
+ dependsOn: ["primary", "practice", "codebase"],
50
+ task: "Answer <QUESTION> from these three research passes. Reconcile disagreements explicitly; check dates, versions, and conditions when official claims conflict with observed practice. Prefer evidence applicable to this question.\n\nFirst-party:\n{{primary}}\n\nPractice:\n{{practice}}\n\nThis repository:\n{{codebase}}\n\nReturn the answer, decisive citations, open questions, and what would change the answer. The final acceptance officer checks the answer and its evidence.",
51
+ },
52
+ ],
53
+ },
54
+ {
55
+ name: "migration",
56
+ description: "Apply two planned migration slices, run their integrated gate, and submit the result for acceptance.",
57
+ nodes: [
58
+ {
59
+ id: "apply-core",
60
+ agent: "artisan",
61
+ task: "Migrate the core slice to <TARGET>. <CORE_CHANGE>. Interface contract: <CONTRACT>. Follow the declared write scope. Implement the change and its regression tests together; run the relevant checks. Report changed paths, command results, and blockers. If the plan conflicts with the code or requires another slice's files, stop and report evidence instead of inventing a new scope.",
62
+ scope: { paths: ["<CORE_SCOPE>", "<CORE_TEST_SCOPE>"] },
63
+ },
64
+ {
65
+ id: "apply-adapters",
66
+ agent: "artisan",
67
+ task: "Migrate the adapter slice to <TARGET>. <ADAPTER_CHANGE>. Interface contract: <CONTRACT>. Follow the declared write scope. Implement the change and its regression tests together; run the relevant checks. Report changed paths, command results, and blockers. If the plan conflicts with the code or requires another slice's files, stop and report evidence instead of inventing a new scope.",
68
+ scope: { paths: ["<ADAPTER_SCOPE>", "<ADAPTER_TEST_SCOPE>"] },
69
+ },
70
+ {
71
+ id: "gate",
72
+ agent: "artisan",
73
+ dependsOn: ["apply-core", "apply-adapters"],
74
+ task: "Run the project's documented required checks on the integrated migration to <TARGET>. Interface contract: <CONTRACT>. Verify both slices meet their done conditions; report missing prerequisites instead of guessing. Reuse valid checks on unchanged code and inspect cross-slice callers for mismatches. Fix failures caused by the migration within its declared scope. Report commands, results, and unverified risks. The final acceptance officer independently checks the result.\n\nCore:\n{{apply-core}}\n\nAdapters:\n{{apply-adapters}}",
75
+ scope: { paths: ["<CORE_SCOPE>", "<CORE_TEST_SCOPE>", "<ADAPTER_SCOPE>", "<ADAPTER_TEST_SCOPE>"] },
76
+ },
77
+ ],
78
+ },
79
+ ];
80
+ }
81
+
82
+ /** Resolve only a shipped plan. There is no filesystem discovery and callers
83
+ * cannot replace the graph, its roles, or the acceptance policy. */
84
+ export function resolveBuiltinWorkflow(
85
+ name: string,
86
+ inputs: Record<string, string> = {},
87
+ ): WorkflowPlanInput {
88
+ const plans = builtinWorkflowPlans();
89
+ const plan = typeof name === "string" ? plans.find((entry) => entry.name === name.trim().toLowerCase()) : undefined;
90
+ if (!plan) {
91
+ throw new Error(`Unknown built-in workflow "${String(name ?? "")}". Choose ${plans.map((entry) => entry.name).join(", ")}. No nodes were started.`);
92
+ }
93
+ return fillWorkflowTemplate(plan, inputs);
94
+ }
95
+
96
+ /** Different built-in inputs own different phases; the same deliverable keeps
97
+ * its identity across repeated calls. Display names remain short and stable. */
98
+ export function compileBuiltinWorkflow(
99
+ name: string,
100
+ inputs: Record<string, string> | undefined,
101
+ cwd: string,
102
+ knownAgents: readonly string[],
103
+ ): CompiledWorkflow {
104
+ const plan = resolveBuiltinWorkflow(name, inputs);
105
+ const identity = createHash("sha256").update(JSON.stringify(plan)).digest("hex").slice(0, 12);
106
+ const workflow = compileWorkflow(plan, cwd, knownAgents);
107
+ workflow.slug = `${workflow.slug}-${identity}`;
108
+ for (const node of workflow.nodes) {
109
+ // Pending phases also match exact task text. Acceptance must distinguish
110
+ // two questions even before their evidence briefs have been built.
111
+ if (node.kind === "acceptance") node.task += `\n\nDeliverable identity: ${workflow.slug}`;
112
+ }
113
+ return workflow;
114
+ }
115
+
116
+ /** Fill only explicit template slots, in one pass. Ordinary code such as <T>
117
+ * and graph result placeholders {{id}} keep their original meaning. Unknown or
118
+ * unused inputs are errors so a misspelled scope cannot silently change a plan. */
119
+ function fillWorkflowTemplate(
120
+ plan: WorkflowPlanInput,
121
+ inputs: Record<string, string> = {},
122
+ ): WorkflowPlanInput {
123
+ if (!inputs || typeof inputs !== "object" || Array.isArray(inputs)) {
124
+ throw new Error("Workflow inputs must be an object of named strings. No nodes were started.");
125
+ }
126
+ for (const [key, value] of Object.entries(inputs)) {
127
+ if (!(WORKFLOW_INPUT_KEYS as readonly string[]).includes(key)) {
128
+ throw new Error(`Unknown workflow input "${key}". Available inputs: ${WORKFLOW_INPUT_KEYS.join(", ")}. No nodes were started.`);
129
+ }
130
+ if (typeof value !== "string" || !value.trim()) {
131
+ throw new Error(`Workflow input "${key}" must be a non-blank string. No nodes were started.`);
132
+ }
133
+ }
134
+ const used = new Set<string>();
135
+ const missing = new Set<string>();
136
+ const fill = (value: string, literalTask = false): string => value.replace(INPUT_PATTERN, (slot, key: string) => {
137
+ used.add(key);
138
+ if (!Object.hasOwn(inputs, key)) { missing.add(key); return slot; }
139
+ return literalTask ? inputs[key]!.replace(/\{\{/gu, "\\{{") : inputs[key]!;
140
+ });
141
+ const next: WorkflowPlanInput = {
142
+ ...plan,
143
+ nodes: plan.nodes.map((node) => ({
144
+ ...node,
145
+ task: fill(node.task, true),
146
+ ...(node.scope ? { scope: {
147
+ ...node.scope,
148
+ paths: node.scope.paths?.map((path) => fill(path)),
149
+ } } : {}),
150
+ })),
151
+ };
152
+ if (missing.size) throw new Error(`Workflow "${plan.name}" requires inputs: ${[...missing].join(", ")}. No nodes were started.`);
153
+ const unused = Object.keys(inputs).filter((key) => !used.has(key));
154
+ if (unused.length) throw new Error(`Unused workflow inputs: ${unused.join(", ")}. No nodes were started.`);
155
+ return next;
156
+ }