@ferris1225/pi-subagents 5.0.3 → 5.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.
@@ -16,9 +16,11 @@
16
16
  */
17
17
 
18
18
  import { type Dirent, existsSync, readdirSync, readFileSync, statSync } from "node:fs";
19
+ import { chmod, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
19
20
  import { basename, dirname, join, resolve } from "node:path";
20
21
  import { fileURLToPath } from "node:url";
21
- import { CONFIG_DIR_NAME, getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
22
+ import { CONFIG_DIR_NAME, getAgentDir, parseFrontmatter, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
23
+ import { migrateStoredAgentName, migrateStoredWorkflowRoles } from "../configuration/role-migration.ts";
22
24
  import type { WorkflowPlanInput } from "./plan.ts";
23
25
 
24
26
  /** Which workflow directories discovery reads. Same precedence as the templates
@@ -74,9 +76,10 @@ function asPlan(value: unknown, fallbackName: string): WorkflowPlanInput | undef
74
76
  };
75
77
  }
76
78
 
79
+ const JSON_FENCE = /^[ \t]*```json[ \t]*\r?\n([\s\S]*?)^[ \t]*```/mu;
80
+
77
81
  function fencedJson(body: string): string | undefined {
78
- const match = /^[ \t]*```json[ \t]*\r?\n([\s\S]*?)^[ \t]*```/mu.exec(body);
79
- return match?.[1];
82
+ return JSON_FENCE.exec(body)?.[1];
80
83
  }
81
84
 
82
85
  /** Read one definition file. Returns an error string instead of throwing so a
@@ -123,6 +126,44 @@ export function readWorkflowFile(
123
126
  };
124
127
  }
125
128
 
129
+ /** Migrate an already trusted, selected saved definition on disk. Discovery
130
+ * stays read-only; inline input is never translated into a different role. */
131
+ export async function migrateWorkflowDefinition(definition: WorkflowDefinition): Promise<WorkflowDefinition> {
132
+ if (definition.source === "builtin" || !definition.plan.nodes.some((node) =>
133
+ typeof node?.agent === "string" && migrateStoredAgentName(node.agent.trim()) !== node.agent.trim(),
134
+ )) return definition;
135
+
136
+ return withFileMutationQueue(definition.filePath, async () => {
137
+ const content = await readFile(definition.filePath, "utf8");
138
+ const isJson = /\.json$/iu.test(definition.filePath);
139
+ // parseFrontmatter normalizes newlines and trims the body; retain the raw
140
+ // prefix here so migration changes only the JSON block.
141
+ const bodyOffset = /^\uFEFF?---[\s\S]*?\r?\n---[^\r\n]*(?:\r?\n|$)/u.exec(content)?.[0].length ?? 0;
142
+ const body = content.slice(bodyOffset);
143
+ const json = isJson ? content : fencedJson(body);
144
+ if (json === undefined) throw new Error(`Cannot migrate workflow ${definition.filePath}: missing JSON block.`);
145
+ const parsed: unknown = JSON.parse(json);
146
+ if (migrateStoredWorkflowRoles(parsed)) {
147
+ const newline = content.includes("\r\n") ? "\r\n" : "\n";
148
+ const serialized = JSON.stringify(parsed, null, 2).replace(/\n/gu, newline) + newline;
149
+ const nextBody = body.replace(JSON_FENCE, (block, source: string) => block.replace(source, () => serialized));
150
+ const next = isJson ? serialized : content.slice(0, bodyOffset) + nextBody;
151
+ const temporary = `${definition.filePath}.${process.pid}.${Date.now()}.tmp`;
152
+ try {
153
+ const { mode } = await stat(definition.filePath);
154
+ await writeFile(temporary, next, { encoding: "utf8", mode });
155
+ await chmod(temporary, mode);
156
+ await rename(temporary, definition.filePath);
157
+ } finally {
158
+ await rm(temporary, { force: true }).catch(() => undefined);
159
+ }
160
+ }
161
+ const current = readWorkflowFile(definition.filePath, definition.source);
162
+ if (!current.definition) throw new Error(current.error ?? `Cannot read migrated workflow ${definition.filePath}.`);
163
+ return current.definition;
164
+ });
165
+ }
166
+
126
167
  function loadDefinitionsFromDir(dir: string, source: WorkflowSource): WorkflowDefinition[] {
127
168
  if (!existsSync(dir)) return [];
128
169
  let entries: Dirent[];
@@ -12,6 +12,7 @@ import { Text } from "@earendil-works/pi-tui";
12
12
  import { Type } from "typebox";
13
13
  import { isWriteCapableAgent, loadBuiltinAgents } from "../delegation/agents.ts";
14
14
  import { defaultIsolationMode, IsolationSchema, PhaseIdSchema, ScopeSchema } from "../delegation/dispatch.ts";
15
+ import { findRuntimeWriterConflict } from "../delegation/ownership.ts";
15
16
  import { loadConfig } from "../configuration/config.ts";
16
17
  import type { SubagentRuntime } from "../lifecycle/runtime.ts";
17
18
  import type { DispatchCore } from "../lifecycle/dispatch-core.ts";
@@ -26,7 +27,7 @@ import {
26
27
  workflowStatus,
27
28
  type WorkflowStatusView,
28
29
  } from "./engine.ts";
29
- import { resolveWorkflowDefinition } from "./files.ts";
30
+ import { migrateWorkflowDefinition, resolveWorkflowDefinition } from "./files.ts";
30
31
  import { compileWorkflow, WORKFLOW_NODE_ID_MAX_LENGTH, type WorkflowPlanInput } from "./plan.ts";
31
32
 
32
33
  const WorkflowNodeSchema = Type.Object({
@@ -75,7 +76,6 @@ const WorkflowParams = Type.Object({
75
76
 
76
77
  export interface WorkflowToolDetails {
77
78
  workflow: WorkflowStatusView;
78
- runIds: number[];
79
79
  }
80
80
 
81
81
  function launchReceipt(status: WorkflowStatusView): string {
@@ -95,7 +95,7 @@ function launchReceipt(status: WorkflowStatusView): string {
95
95
  return parts.join(" · ");
96
96
  }),
97
97
  "",
98
- "The graph dispatches each dependent the moment its prerequisites settle, with no further dispatch from you. One summary arrives when the whole graph settles; continue disjoint work or end your turn, and do not poll. Ready independent nodes start together without a process-count limit.",
98
+ "Every node is owned by this graph, including nodes waiting on dependencies. Do not perform or redispatch their work in main or another agent. The graph dispatches dependents automatically and sends one summary; continue only disjoint work or end your turn, and do not poll.",
99
99
  ];
100
100
  return lines.join("\n");
101
101
  }
@@ -135,7 +135,7 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
135
135
  name: "subagent_workflow",
136
136
  label: "Subagent Workflow",
137
137
  description:
138
- "Run a dependency graph of sub-agent phases: declare nodes with dependsOn, and the runtime dispatches each dependent as soon as its prerequisites settle. Choose this proactively for two or more substantial phases with known dependencies and writer scopes, when scheduling saves coordination. Use subagent tasks for independent work with no dependency edges; keep small or tightly coupled work in main. If a result must decide the next task or its scope, dispatch that phase alone, decide in main, then reassess whether a graph fits. Never add research, review, or gate nodes by habit. A graph saves dispatch turns; it does not plan or judge success beyond process results. One summary arrives when the graph settles. Nodes are ordinary one-shot runs; main still owns integration, the final gate, and release.",
138
+ "Run a fixed dependency graph for substantial phases with known scopes. dependsOn starts a node after prerequisites finish and integrate. Pending nodes already own their work; main must not execute or redispatch it. Duplicate phases and external writer conflicts reject the graph before any child starts. Independent work without dependency edges uses subagent tasks. If a result must decide the next phase, dispatch it alone and decide in main. Omit isolation for automatic selection. One summary arrives after settlement; main checks outcomes, integrates, and releases.",
139
139
  exposure: "model-only",
140
140
  executionMode: "parallel",
141
141
  annotations: {
@@ -179,7 +179,7 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
179
179
  if (resolved.error || !resolved.definition) {
180
180
  throw new Error((resolved.error ?? "workflow definition could not be read") + ". No nodes were started.");
181
181
  }
182
- const definition = resolved.definition;
182
+ const definition = await migrateWorkflowDefinition(resolved.definition);
183
183
  plan = {
184
184
  name: params.name ?? definition.plan.name ?? definition.name,
185
185
  ...(params.description ?? definition.description
@@ -225,6 +225,13 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
225
225
  );
226
226
  }
227
227
 
228
+ for (const node of workflow.nodes) {
229
+ const agent = agents.find((candidate) => candidate.name === node.agent)!;
230
+ if (!node.scope || !isWriteCapableAgent(agent, toolInfos)) continue;
231
+ const conflict = findRuntimeWriterConflict(runtime, node.scope);
232
+ if (conflict) throw new Error(`Workflow node "${node.id}" scope ${conflict.overlap.left} overlaps ${conflict.owner} scope ${conflict.overlap.right}. No nodes were started.`);
233
+ }
234
+
228
235
  const handle = startWorkflow(
229
236
  {
230
237
  runtime,
@@ -232,7 +239,6 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
232
239
  resolveIsolation: (agentName) => {
233
240
  const agent = agents.find((candidate) => candidate.name === agentName);
234
241
  return defaultIsolationMode(
235
- "parallel",
236
242
  agentName,
237
243
  undefined,
238
244
  agent ? isWriteCapableAgent(agent, toolInfos) : undefined,
@@ -246,10 +252,7 @@ export function registerWorkflowTool(pi: ExtensionAPI, runtime: SubagentRuntime,
246
252
  const status = workflowStatus(handle.run);
247
253
  return {
248
254
  content: [{ type: "text", text: launchReceipt(status) }],
249
- details: {
250
- workflow: status,
251
- runIds: status.nodes.flatMap((node) => (node.runId === undefined ? [] : [node.runId])),
252
- } satisfies WorkflowToolDetails,
255
+ details: { workflow: status } satisfies WorkflowToolDetails,
253
256
  };
254
257
  },
255
258
 
@@ -1,61 +1,37 @@
1
1
  ---
2
2
  name: code-review
3
- description: Review a change with independent eyes, confirm each finding, and report what was verified.
3
+ description: Inspect an implementation, then challenge only the reported findings.
4
4
  ---
5
5
 
6
6
  # Code review workflow
7
7
 
8
- Two reviewers read the same change from different angles, a third agent then
9
- tries to *disprove* every finding against the code, and the last node writes the
10
- report the user keeps. This saved template chooses a thorough adversarial review;
11
- for a small diff, combine the map with a reviewer and let main write the report.
8
+ Use one `sentinel` run for an ordinary review. This two-node template is for a
9
+ substantial change where independent verification of findings earns another
10
+ session. The sentinel inspects the implementation; the skeptic checks its named
11
+ claims and returns the final review. They do not perform two general reviews.
12
12
 
13
- Copy this file to `.pi/workflows/code-review.md` in the repository you are
14
- reviewing. Two things are yours to set before you run it:
13
+ Copy this file to `.pi/workflows/code-review.md` and replace `<TARGET>` with the
14
+ branch, commit range, or paths under review. Include any existing main research
15
+ and checks in the review brief so the sentinel can reuse them. If the first
16
+ result must decide whether a second phase is needed, dispatch only the sentinel
17
+ and make that decision in main.
15
18
 
16
- - Replace the review target in the `map` brief with the branch, commit range, or
17
- paths actually under review.
18
- - Nothing else needs to change to start; the reviewers inherit the target from
19
- `{{map}}`.
20
-
21
- Run it with `subagent_workflow({ "workflow": "code-review" })`, or by path with
22
- `file: ".pi/workflows/code-review.md"`.
19
+ Run with `subagent_workflow({ workflow: "code-review" })`, or use an explicit
20
+ `file` path. Omit isolation overrides for these read-only reviews.
23
21
 
24
22
  ```json
25
23
  {
26
24
  "nodes": [
27
25
  {
28
- "id": "map",
29
- "agent": "reviewer",
30
- "isolation": "shared",
31
- "task": "Read git diff and git status to establish what changed for a review of the working tree against HEAD, including staged and untracked changes. Stay read-only; do not edit files, install dependencies, or change Git state. Report: the changed files, what each change is trying to do, the call sites and tests that depend on them, and the checks the repository defines (package.json scripts, CI config, README verification line). Cite path:line for everything. Do not review quality yet."
32
- },
33
- {
34
- "id": "correctness",
35
- "agent": "reviewer",
36
- "isolation": "shared",
37
- "task": "You are the correctness reviewer. Using this map:\n\n{{map}}\n\nRead the changed code yourself and report what is wrong: logic errors, unhandled cases, broken invariants, missing tests that would catch a real failure. For each finding give path:line, what breaks, the concrete input or state that breaks it, and the smallest change that fixes it. Do not edit any file. Do not report style preferences.",
38
- "dependsOn": ["map"]
39
- },
40
- {
41
- "id": "risk",
42
- "agent": "reviewer",
43
- "isolation": "shared",
44
- "task": "You are the risk reviewer, with a different lens from the correctness reviewer. Using this map:\n\n{{map}}\n\nLook for what this change breaks outside its own diff: migrations and backward compatibility, concurrency and ordering, error paths, resource lifetime, security and data loss, and behaviour other modules rely on. Give path:line for each risk and say how likely it is to bite. Do not edit any file.",
45
- "dependsOn": ["map"]
46
- },
47
- {
48
- "id": "confirm",
49
- "agent": "critic",
50
- "isolation": "shared",
51
- "task": "Two reviewers reported findings. Your job is to try to disprove them, not to agree.\n\nCorrectness findings:\n{{correctness}}\n\nRisk findings:\n{{risk}}\n\nFor each finding, look for a counterexample in callers, invariants, and tests. Run a safe focused reproduction when needed and available. Do not edit files, install dependencies, or change Git state. Classify it as reproduced (command and result), source-supported (code evidence, not executed), disproved (counterevidence), or unverified (missing evidence). Return surviving findings with severity and the evidence that would falsify them.",
52
- "dependsOn": ["correctness", "risk"]
26
+ "id": "review",
27
+ "agent": "sentinel",
28
+ "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."
53
29
  },
54
30
  {
55
- "id": "report",
56
- "agent": "scout",
57
- "task": "Write the review the user acts on, from the surviving findings and evidence:\n\n{{confirm}}\n\nStructure it as: a two-sentence verdict, then each surviving finding as where / what / evidence / severity, then what was checked and how, then what the review did not cover. Say plainly which findings were confirmed and which stayed unverified. Do not edit code; this node produces the report only.",
58
- "dependsOn": ["confirm"]
31
+ "id": "verify",
32
+ "agent": "skeptic",
33
+ "dependsOn": ["review"],
34
+ "task": "Test only the specific defect claims reported here:\n\n{{review}}\n\nTry to disprove each claim against its callers, invariants, or focused checks. Reuse valid evidence; do not repeat the general review. If there are no defect claims, report that and stop. Stay read-only and do not change Git state. Return the final review: surviving confirmed findings ordered by severity with trigger, consequence, evidence, and smallest fix; briefly state refuted or unresolved claims, checks, and remaining limits."
59
35
  }
60
36
  ]
61
37
  }
@@ -8,10 +8,12 @@ description: Apply two already planned migration slices, then challenge the inte
8
8
  Use this template after main has established the target, interface contract,
9
9
  and disjoint writer scopes. If discovery determines those boundaries, run that
10
10
  discovery first and decide in main; a static graph cannot rewrite its own nodes.
11
- Replace <TARGET>, both slice briefs, and the example paths before running.
11
+ Replace <TARGET>, <CONTRACT> (the shared interface contract or its file path),
12
+ both slice briefs, and every example scope before running. Each child needs the
13
+ contract in its own brief because it cannot see main's conversation.
12
14
  Each slice owns its implementation and regression tests. Keep coupled changes
13
- with one owner. Add a separate adversarial reviewer for risk that the gate cannot
14
- cover; main still owns final integration and release.
15
+ with one owner. Use sentinel for a separate implementation review or skeptic
16
+ for a named assumption the gate cannot test; main owns final integration and release.
15
17
 
16
18
  ```json
17
19
  {
@@ -19,21 +21,21 @@ cover; main still owns final integration and release.
19
21
  {
20
22
  "id": "apply-core",
21
23
  "agent": "artisan",
22
- "task": "Migrate the core slice to <TARGET>. <CORE_CHANGE>. Follow the interface contract and paths main established. 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 rather than inventing a new scope.",
24
+ "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 rather than inventing a new scope.",
23
25
  "scope": { "paths": ["src/core", "test/core"] }
24
26
  },
25
27
  {
26
28
  "id": "apply-adapters",
27
29
  "agent": "artisan",
28
- "task": "Migrate the adapter slice to <TARGET>. <ADAPTER_CHANGE>. Follow the interface contract and paths main established. 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 rather than inventing a new scope.",
30
+ "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 rather than inventing a new scope.",
29
31
  "scope": { "paths": ["src/adapters", "test/adapters"] }
30
32
  },
31
33
  {
32
34
  "id": "gate",
33
35
  "agent": "artisan",
34
- "isolation": "shared",
35
- "task": "Challenge the integrated migration using the project's documented required checks and the interface contract. Run the required commands; inspect cross-slice call sites for mismatches. Fix failures caused by this migration within its authorized scope. Report commands, results, and unverified risks.\n\nCore:\n{{apply-core}}\n\nAdapters:\n{{apply-adapters}}",
36
- "dependsOn": ["apply-core", "apply-adapters"]
36
+ "task": "Challenge the integrated migration using the project's documented required checks. Interface contract: <CONTRACT>. Verify both slices meet their done conditions before proceeding; report missing prerequisites instead of guessing. Run the required commands; inspect cross-slice call sites for mismatches. Fix failures caused by this migration within its authorized scope. Report commands, results, and unverified risks.\n\nCore:\n{{apply-core}}\n\nAdapters:\n{{apply-adapters}}",
37
+ "dependsOn": ["apply-core", "apply-adapters"],
38
+ "scope": { "paths": ["src/core", "test/core", "src/adapters", "test/adapters"] }
37
39
  }
38
40
  ]
39
41
  }