@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.
@@ -116,6 +116,16 @@ export interface WorktreeIsolation {
116
116
  finalize(): Promise<WorktreeFinalization>;
117
117
  }
118
118
 
119
+ export class WorktreeUnavailableError extends Error {
120
+ readonly reason: "not a Git repository" | "no committed HEAD";
121
+
122
+ constructor(reason: "not a Git repository" | "no committed HEAD") {
123
+ super(`Worktree isolation unavailable: ${reason}.`);
124
+ this.name = "WorktreeUnavailableError";
125
+ this.reason = reason;
126
+ }
127
+ }
128
+
119
129
  class WorktreeSetupError extends Error {
120
130
  constructor(message: string) {
121
131
  super(message);
@@ -248,6 +258,9 @@ async function resolveRepositoryLocation(
248
258
  `Git repository discovery for ${originalCwd}`,
249
259
  );
250
260
  } catch (error) {
261
+ if (error instanceof Error && /not a git repository/iu.test(error.message)) {
262
+ throw new WorktreeUnavailableError("not a Git repository");
263
+ }
251
264
  throw new WorktreeSetupError(
252
265
  `Worktree isolation requires cwd to be inside a Git worktree/repository: ${error instanceof Error ? error.message : String(error)}`,
253
266
  );
@@ -280,13 +293,17 @@ async function resolveWorktreeTarget(
280
293
  const { originalCwd, originalRoot } = await resolveRepositoryLocation(cwd, runner);
281
294
  let headResult: CommandResult;
282
295
  try {
283
- headResult = await runGit(
284
- runner,
285
- originalRoot,
286
- ["rev-parse", "--verify", "HEAD"],
287
- `Resolving HEAD for ${originalRoot}`,
288
- );
296
+ headResult = await runner("git", ["rev-parse", "--verify", "--quiet", "HEAD"], {
297
+ cwd: originalRoot,
298
+ timeoutMs: GIT_COMMAND_TIMEOUT_MS,
299
+ maxOutputBytes: GIT_OUTPUT_MAX_BYTES,
300
+ });
301
+ if (headResult.code === 1 && !headResult.stdout.length && !headResult.stderr.length) {
302
+ throw new WorktreeUnavailableError("no committed HEAD");
303
+ }
304
+ if (headResult.code !== 0) throw commandFailure(`Resolving HEAD for ${originalRoot}`, headResult);
289
305
  } catch (error) {
306
+ if (error instanceof WorktreeUnavailableError) throw error;
290
307
  throw new WorktreeSetupError(
291
308
  `Worktree isolation requires a repository with a committed HEAD: ${error instanceof Error ? error.message : String(error)}`,
292
309
  );
@@ -587,9 +604,67 @@ async function linkNodeModules(
587
604
  }
588
605
  }
589
606
 
607
+ /** Capture the caller's current files without staging into its real index or
608
+ * advancing any ref. The detached worktree keeps this synthetic commit alive
609
+ * and uses it as both its initial checkout and its integration diff base. */
610
+ async function createWorktreeBaseline(
611
+ target: WorktreeTarget,
612
+ tempDir: string,
613
+ runner: CommandRunner,
614
+ ): Promise<string> {
615
+ const indexCopy = join(tempDir, "baseline-index");
616
+ const env = { GIT_INDEX_FILE: indexCopy };
617
+ try {
618
+ const indexPath = resolve(
619
+ target.originalRoot,
620
+ (await runGit(
621
+ runner,
622
+ target.originalRoot,
623
+ ["rev-parse", "--git-path", "index"],
624
+ "Resolving caller baseline index path",
625
+ )).stdout.toString("utf8").trim(),
626
+ );
627
+ if (existsSync(indexPath)) {
628
+ await copyFile(indexPath, indexCopy);
629
+ } else {
630
+ await runGit(
631
+ runner, target.originalRoot, ["read-tree", target.head],
632
+ "Initializing caller baseline index", undefined, env,
633
+ );
634
+ }
635
+ await runGit(
636
+ runner, target.originalRoot, ["add", "-A", "--", "."],
637
+ "Capturing caller working tree baseline", undefined, env,
638
+ );
639
+ const tree = await runGit(
640
+ runner, target.originalRoot, ["write-tree"],
641
+ "Writing caller baseline tree", undefined, env,
642
+ );
643
+ const treeId = tree.stdout.toString("utf8").trim();
644
+ if (!treeId) throw new Error("Git returned no caller baseline tree id.");
645
+ const commit = await runGit(
646
+ runner,
647
+ target.originalRoot,
648
+ [
649
+ "-c", "user.name=pi-subagents",
650
+ "-c", "user.email=pi-subagents@example.invalid",
651
+ "commit-tree", treeId,
652
+ "-p", target.head,
653
+ "-m", "pi-subagents caller baseline",
654
+ ],
655
+ "Creating caller baseline commit",
656
+ );
657
+ const commitId = commit.stdout.toString("utf8").trim();
658
+ if (!commitId) throw new Error("Git returned no caller baseline commit id.");
659
+ return commitId;
660
+ } finally {
661
+ await rm(indexCopy, { force: true });
662
+ }
663
+ }
664
+
590
665
  /**
591
- * Create a detached worktree at repository HEAD. The returned cwd mirrors the
592
- * caller's subdirectory inside that new worktree.
666
+ * Create a detached worktree from the caller's current non-ignored files. The
667
+ * returned cwd mirrors the caller's subdirectory inside that new worktree.
593
668
  */
594
669
  export async function createWorktreeIsolation(
595
670
  cwd: string,
@@ -607,10 +682,11 @@ export async function createWorktreeIsolation(
607
682
  const patchPath = join(tempDir, "changes.patch");
608
683
  let added = false;
609
684
  try {
685
+ const baseline = await createWorktreeBaseline(target, tempDir, runner);
610
686
  await runGit(
611
687
  runner,
612
688
  target.originalRoot,
613
- ["worktree", "add", "--detach", worktreePath, "HEAD"],
689
+ ["worktree", "add", "--detach", worktreePath, baseline],
614
690
  `Creating detached worktree from ${target.originalRoot}`,
615
691
  );
616
692
  added = true;
@@ -627,7 +703,7 @@ export async function createWorktreeIsolation(
627
703
  worktreePath,
628
704
  tempDir,
629
705
  patchPath,
630
- target.head,
706
+ baseline,
631
707
  runner,
632
708
  );
633
709
  } catch (error) {
@@ -23,7 +23,7 @@ export interface DispatchCore {
23
23
  /** Stamp a terminal monitor state and toast the result once. */
24
24
  finishRun: (runId: number, status: "done" | "failed", opts?: { silent?: boolean }) => void;
25
25
  makeLiveHandler: (runId: number, generation?: number) => (event: SubagentLiveEvent) => void;
26
- makeDetails: (mode: "single" | "parallel", background?: boolean) => (results: SingleResult[]) => SubagentDetails;
26
+ makeDetails: (mode: "single" | "parallel") => (results: SingleResult[]) => SubagentDetails;
27
27
  }
28
28
 
29
29
  export function createDispatchCore(runtime: SubagentRuntime): DispatchCore {
@@ -118,8 +118,8 @@ export function createDispatchCore(runtime: SubagentRuntime): DispatchCore {
118
118
  };
119
119
 
120
120
  const makeDetails =
121
- (mode: "single" | "parallel", background = false) =>
122
- (results: SingleResult[]): SubagentDetails => ({ mode, results, background });
121
+ (mode: "single" | "parallel") =>
122
+ (results: SingleResult[]): SubagentDetails => ({ mode, results });
123
123
 
124
124
  const startBackground = createBackgroundDispatcher({
125
125
  runtime,
@@ -20,6 +20,7 @@ import { uptime } from "node:os";
20
20
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
21
21
  import type { UsageStats } from "../execution/run-control.ts";
22
22
  import { normalizePhaseId, normalizePhaseScope, type PhaseScope } from "../delegation/phase-scope.ts";
23
+ import { migrateStoredRecordRoles } from "../configuration/role-migration.ts";
23
24
  import type { SubagentThread } from "./runtime.ts";
24
25
  import { getResultOutput, isFailedResult, getProjectRoot, getSubagentsRoot, type SingleResult } from "../execution/spawn.ts";
25
26
  import { isManagedSessionDir, isManagedWorktreeLayout, samePath } from "../isolation/managed-paths.ts";
@@ -211,6 +212,7 @@ function normalizeRecord(value: unknown): ThreadRecord | undefined {
211
212
 
212
213
  interface ThreadManifestRead {
213
214
  valid: boolean;
215
+ rolesMigrated?: boolean;
214
216
  sourceCount: number;
215
217
  records: ThreadRecord[];
216
218
  }
@@ -219,8 +221,11 @@ async function readManifest(path: string): Promise<ThreadManifestRead> {
219
221
  try {
220
222
  const parsed = JSON.parse(await readFile(path, "utf8")) as { records?: unknown };
221
223
  if (!Array.isArray(parsed.records)) return { valid: false, sourceCount: 0, records: [] };
224
+ let rolesMigrated = false;
225
+ for (const record of parsed.records) rolesMigrated = migrateStoredRecordRoles(record) || rolesMigrated;
222
226
  return {
223
227
  valid: true,
228
+ rolesMigrated,
224
229
  sourceCount: parsed.records.length,
225
230
  records: parsed.records.flatMap((record) => {
226
231
  const normalized = normalizeRecord(record);
@@ -304,7 +309,7 @@ export async function readThreadRecords(configPath: string): Promise<ThreadRecor
304
309
  .map((path) => withFileMutationQueue(path, async () => {
305
310
  const manifest = await readManifest(path);
306
311
  const validated = await validatedManifestRecords(configPath, path, manifest.records);
307
- if (!manifest.valid || validated.length !== manifest.sourceCount) await writeManifest(path, validated);
312
+ if (!manifest.valid || manifest.rolesMigrated || validated.length !== manifest.sourceCount) await writeManifest(path, validated);
308
313
  return validated;
309
314
  })),
310
315
  );
@@ -10,6 +10,7 @@
10
10
 
11
11
  import type { ExtensionAPI, ToolInfo } from "@earendil-works/pi-coding-agent";
12
12
  import { findDuplicateDispatch } from "../delegation/prompt.ts";
13
+ import { pendingWorkflowLeases } from "../delegation/ownership.ts";
13
14
  import type { PhaseScope } from "../delegation/phase-scope.ts";
14
15
  import { rmSync } from "node:fs";
15
16
  import { BackgroundTaskQueue } from "../execution/background.ts";
@@ -122,6 +123,8 @@ export interface SubagentRuntime {
122
123
  registerRunResult: (runId: number, result: SingleResult) => void;
123
124
  /** Logical threads outlive process attempts and completed generations. */
124
125
  threads: Map<number, SubagentThread>;
126
+ /** Explicit main edit/write calls hold their paths until tool_execution_end. */
127
+ mainWrites: Map<string, { toolName: string; scope: PhaseScope }>;
125
128
  /** Workflow graphs started in this parent session, live and settled. */
126
129
  workflows: Map<number, WorkflowRun>;
127
130
  /** Allocate a graph id that no retained or live workflow record owns. */
@@ -147,16 +150,9 @@ export function findPendingWorkflowPhase(
147
150
  phaseId?: string,
148
151
  excludeWorkflowId?: number,
149
152
  ): { workflowId: number; nodeId: string; agent: string } | undefined {
150
- for (const graph of runtime.workflows.values()) {
151
- if (graph.state !== "running" || graph.id === excludeWorkflowId) continue;
152
- for (const node of graph.nodes) {
153
- if (node.state !== "pending" && !(node.state === "running" && node.runId === undefined)) continue;
154
- if (findDuplicateDispatch([{ id: graph.id, agentName: node.agent, task: node.task, cwd: node.cwd, phaseId: node.phaseId, state: "queued" }], task, cwd, phaseId)) {
155
- return { workflowId: graph.id, nodeId: node.id, agent: node.agent };
156
- }
157
- }
158
- }
159
- return undefined;
153
+ const duplicate = findDuplicateDispatch(pendingWorkflowLeases(runtime, excludeWorkflowId), task, cwd, phaseId);
154
+ const owner = duplicate?.source;
155
+ return owner?.workflow ? { workflowId: owner.workflow.workflowId, nodeId: owner.workflow.nodeId, agent: owner.agentName } : undefined;
160
156
  }
161
157
 
162
158
  export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRuntime {
@@ -253,6 +249,7 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
253
249
  settledRuns: new Map<number, SingleResult>(),
254
250
  settledListeners: new Map<number, Set<(result: SingleResult) => void>>(),
255
251
  threads: new Map<number, SubagentThread>(),
252
+ mainWrites: new Map(),
256
253
  workflows: new Map<number, WorkflowRun>(),
257
254
  reserveWorkflowId: () => nextWorkflowId++,
258
255
  ensureWorkflowIdAbove: (id) => {
@@ -395,6 +392,7 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
395
392
  // manifest; the next process re-registers them at restore.
396
393
  runtime.sessionDirs.clear();
397
394
  runtime.threads.clear();
395
+ runtime.mainWrites.clear();
398
396
  runtime.workflows.clear();
399
397
  runtime.shutdownHooks = [];
400
398
  monitor.clear();
@@ -22,6 +22,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
22
22
  generation: number;
23
23
  controller: AbortController | undefined;
24
24
  completion: Promise<void>;
25
+ releaseQuiescence: () => void;
25
26
  stopVersion: number;
26
27
  stopMessage: string;
27
28
  }> = [];
@@ -36,6 +37,12 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
36
37
  thread.retired = true;
37
38
  thread.retireOnSettle = true;
38
39
  thread.state = "stopped";
40
+ const completion = thread.generationCompletion;
41
+ let releaseQuiescence!: () => void;
42
+ const stopCompletion = new Promise<void>((resolve) => { releaseQuiescence = resolve; });
43
+ // A repeated stop must also wait for this owner's finalization, even if
44
+ // the bounded control call has already returned a partial result.
45
+ thread.generationCompletion = Promise.allSettled([completion, stopCompletion]).then(() => undefined);
39
46
  const stopMessage = reason ?? (wasQueued
40
47
  ? "Stopped by subagent_stop before the run started."
41
48
  : wasActive ? "Stopped by subagent_stop."
@@ -45,7 +52,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
45
52
  runId, thread, run: monitor.findRun(runId), previousState, wasQueued, wasActive,
46
53
  generation: thread.generation,
47
54
  controller: thread.queueController,
48
- completion: thread.generationCompletion,
55
+ completion, releaseQuiescence,
49
56
  stopVersion, stopMessage,
50
57
  });
51
58
  }
@@ -74,6 +81,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
74
81
  generation,
75
82
  controller,
76
83
  completion,
84
+ releaseQuiescence,
77
85
  stopVersion,
78
86
  stopMessage,
79
87
  } = claim;
@@ -91,6 +99,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
91
99
  // lifecycle. Synthesize and publish the one aborted result here only when
92
100
  // this stop actually interrupted unfinished work.
93
101
  let stoppedResult: SingleResult | undefined;
102
+ let finalizationCompletion: Promise<WorktreeFinalization | undefined> = Promise.resolve(undefined);
94
103
  if (
95
104
  wasQueued ||
96
105
  previousState === "parked" ||
@@ -123,8 +132,9 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
123
132
  const worktree = thread.worktree;
124
133
  let finalization: WorktreeFinalization | undefined;
125
134
  try {
135
+ finalizationCompletion = thread.finalizeIsolation(generation, stoppedResult);
126
136
  finalization = await Promise.race([
127
- thread.finalizeIsolation(generation, stoppedResult),
137
+ finalizationCompletion,
128
138
  new Promise<undefined>((resolve) => {
129
139
  const timer = setTimeout(() => resolve(undefined), CONTROL_QUIESCE_TIMEOUT_MS);
130
140
  if (typeof timer.unref === "function") timer.unref();
@@ -167,9 +177,14 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
167
177
  // The destructive retire removes the durable record with the session;
168
178
  // an id never resurrects after subagent_stop.
169
179
  await removeThreadRecord(runtime.configPath, runId, thread.cwd).catch(() => undefined);
170
- if (thread.lifecycleVersion === stopVersion && thread.lifecycleOperation === "stop") {
171
- thread.lifecycleOperation = undefined;
172
- }
180
+ // Returning from a bounded stop retires context, but cannot release a
181
+ // writer or phase lease while a child or Git tail can still change files.
182
+ void Promise.allSettled([interruptionPromises[claimIndex]!, completion, finalizationCompletion]).then(() => {
183
+ if (thread.lifecycleVersion === stopVersion && thread.lifecycleOperation === "stop") {
184
+ thread.lifecycleOperation = undefined;
185
+ }
186
+ releaseQuiescence();
187
+ });
173
188
  stopped.push(`#${runId} ${thread.agentName}${wasQueued ? " (queued)" : wasActive ? "" : ` (${previousState})`}`);
174
189
  }
175
190
  return { stopped, retainedIntegration, pendingIntegration, completionResults };
@@ -14,7 +14,8 @@ import { DEFAULT_IDLE_TIMEOUT_SEC, DEFAULT_MAX_RESULT_LINES, loadConfig } from "
14
14
  import { dispatchFailedResult, failedStartResult, formatCompletionBlock, modelLevelTakeoverNote, queuedResult } from "../presentation/format.ts";
15
15
  import { formatTaskSummary, monitor } from "../presentation/monitor.ts";
16
16
  import { findDuplicateDispatch } from "../delegation/prompt.ts";
17
- import { findWriterLeaseScopeOverlap, normalizePhaseId, normalizePhaseScope } from "../delegation/phase-scope.ts";
17
+ import { normalizePhaseId, normalizePhaseScope } from "../delegation/phase-scope.ts";
18
+ import { findRuntimeWriterConflict } from "../delegation/ownership.ts";
18
19
  import { persistRecoveryRecords, recoveryRecordFromFinalization } from "../isolation/recovery.ts";
19
20
  import { findPendingWorkflowPhase, type SubagentRuntime, type SubagentThread, type ThreadState } from "./runtime.ts";
20
21
  import {
@@ -40,6 +41,7 @@ import {
40
41
  } from "./thread-shared.ts";
41
42
  import {
42
43
  createWorktreeIsolation,
44
+ WorktreeUnavailableError,
43
45
  worktreeGroupId,
44
46
  type IsolationMode,
45
47
  type WorktreeFinalization,
@@ -134,10 +136,10 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
134
136
  `Run #${owner.id} (${owner.agentName}) already owns this logical phase (${owner.state}). ${remedy}`);
135
137
  }
136
138
  if (writeCapable && scope) {
137
- const conflict = findWriterLeaseScopeOverlap(scope, runtime.threads.values());
139
+ const conflict = findRuntimeWriterConflict(runtime, scope, { excludeWorkflowId: startOptions.workflow?.workflowId });
138
140
  if (conflict) {
139
141
  return failedStartResult(agentName, task,
140
- `Declared writer scope ${conflict.overlap.left} overlaps active run #${conflict.lease.id} scope ${conflict.overlap.right}; no run was started.`);
142
+ `Declared writer scope ${conflict.overlap.left} overlaps ${conflict.owner} scope ${conflict.overlap.right}; no run was started.`);
141
143
  }
142
144
  }
143
145
  const projectRoot = getProjectRoot(runtime.configPath, originalCwd);
@@ -148,7 +150,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
148
150
  let executionCwd = originalCwd;
149
151
  let worktreeGroup: string | undefined;
150
152
  const resolvedRoute = resolveDispatchModelRoute(agent, runConfig, runCtx);
151
- const route = isolation === "worktree"
153
+ let route = isolation === "worktree"
152
154
  ? { ...resolvedRoute, agent: withWorktreeSystemPrompt(resolvedRoute.agent) }
153
155
  : resolvedRoute;
154
156
  const thinkingLevel = route.thinkingLevel;
@@ -216,18 +218,35 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
216
218
  const runGeneration = async (backgroundSignal: AbortSignal): Promise<void> => {
217
219
  if (runtime.threads.get(runId)?.generation !== generation) return;
218
220
  if (isolation === "worktree" && !worktree) {
219
- const prepared = await createWorktreeIsolation(originalCwd, { tempBaseDir: worktreesRoot });
220
- if (runtime.threads.get(runId)?.generation !== generation || backgroundSignal.aborted) {
221
- await prepared.discard().catch(() => undefined);
222
- return;
221
+ let prepared: WorktreeIsolation | undefined;
222
+ try {
223
+ prepared = await createWorktreeIsolation(originalCwd, { tempBaseDir: worktreesRoot });
224
+ } catch (error) {
225
+ if (!startOptions.automaticIsolation || !(error instanceof WorktreeUnavailableError)) throw error;
226
+ if (runtime.threads.get(runId)?.generation !== generation || backgroundSignal.aborted) return;
227
+ isolation = "shared";
228
+ thread.isolation = "shared";
229
+ pending.isolation = "shared";
230
+ delete pending.integrationStatus;
231
+ pending.isolationNote = `Using the caller's directory: ${error.reason}; automatic worktree isolation is unavailable.`;
232
+ route = resolvedRoute;
233
+ monitor.setIsolation(runId, "shared");
234
+ runCtx.ui.notify(`#${runId}: ${pending.isolationNote}`, "info");
235
+ installCurrentLifecycle();
236
+ }
237
+ if (prepared) {
238
+ if (runtime.threads.get(runId)?.generation !== generation || backgroundSignal.aborted) {
239
+ await prepared.discard().catch(() => undefined);
240
+ return;
241
+ }
242
+ worktree = prepared;
243
+ executionCwd = prepared.cwd;
244
+ worktreeGroup = worktreeGroupId(prepared);
245
+ thread.worktree = prepared;
246
+ thread.executionCwd = executionCwd;
247
+ monitor.setIsolation(runId, "worktree", "pending", worktreeGroup);
248
+ installCurrentLifecycle();
223
249
  }
224
- worktree = prepared;
225
- executionCwd = prepared.cwd;
226
- worktreeGroup = worktreeGroupId(prepared);
227
- thread.worktree = prepared;
228
- thread.executionCwd = executionCwd;
229
- monitor.setIsolation(runId, "worktree", "pending", worktreeGroup);
230
- installCurrentLifecycle();
231
250
  }
232
251
  // Independent runs start immediately; only worktree integration serializes.
233
252
  monitor.setWaitReason(runId, "starting");
@@ -285,6 +304,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
285
304
  result.runId = runId;
286
305
  result.projectCwd = originalCwd;
287
306
  result.isolation = isolation;
307
+ if (pending.isolationNote) result.isolationNote = pending.isolationNote;
288
308
  thread.task = result.task;
289
309
  thread.sessionId = result.sessionId;
290
310
  thread.sessionDir = result.sessionDir;
@@ -93,7 +93,7 @@ export function persistThreadCheckpoint(
93
93
  }
94
94
 
95
95
  const WORKTREE_ISOLATION_INSTRUCTIONS =
96
- "You are running in a temporary detached Git worktree. Work only in the current cwd; do not create another worktree or manually copy/apply changes to the original checkout. The parent dispatcher will integrate your tracked, deleted, and untracked changes when this thread finally settles.";
96
+ "You are running in a temporary detached Git worktree. Work only in the current cwd; interpret paths from the brief relative to this checkout. Do not write to the original checkout, create another worktree, or copy/apply changes back manually. The runtime will merge your tracked, deleted, and untracked changes after you finish.";
97
97
 
98
98
  export function withWorktreeSystemPrompt(agent: AgentConfig): AgentConfig {
99
99
  return {
@@ -121,6 +121,8 @@ export interface StartBackgroundOptions {
121
121
  scope?: PhaseScope;
122
122
  /** A false hint cannot downgrade a live write-capable role. */
123
123
  writeCapable?: boolean;
124
+ /** Omitted public isolation may fall back only when no Git baseline exists. */
125
+ automaticIsolation?: boolean;
124
126
  /** Chosen by the tool call before the queue can start a fast child. */
125
127
  deliveryRoute?: "background" | "await";
126
128
  /** A workflow node reports through its graph's single summary: no per-run
@@ -87,7 +87,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
87
87
  pi.registerTool({
88
88
  name: "subagent_status",
89
89
  label: "Subagent Status",
90
- description: "Check live subagent progress without waiting or changing execution: state, elapsed time, an activity trail (what the run has been doing), and failure diagnostics. Omit id to list runs. Results arrive automatically in completion messages; use this to inspect progress, not as a polling loop.",
90
+ description: "Inspect run or workflow ownership, progress, and failures. An exact run id also returns its retained result so completed work can be reused. Omit id to list runs. Results arrive automatically; do not poll.",
91
91
  exposure: "model-only",
92
92
  executionMode: "parallel",
93
93
  annotations: {
@@ -134,6 +134,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
134
134
  resultFile: result?.resultFile,
135
135
  sessionDir: thread.retired ? undefined : thread.sessionDir ?? result?.sessionDir,
136
136
  isolation: thread.isolation,
137
+ isolationNote: result?.isolationNote,
137
138
  integrationStatus: live?.integrationStatus ?? result?.integrationStatus ?? thread.worktree?.state,
138
139
  integrationError: result?.integrationError,
139
140
  integrationWorktreePath: result?.integrationWorktreePath ?? (state === "interrupted" ? thread.worktree?.worktreePath : undefined),
@@ -145,6 +146,9 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
145
146
  : runs.map((run) => {
146
147
  const wait = run.waitReason ? ` — ${runWaitLabel({ status: "queued", waitReason: run.waitReason })}` : "";
147
148
  const lines = [`#${run.id} ${run.agent} · ${run.state} · ${formatDuration(run.elapsedMs)}${wait}`, ` task: ${run.taskSummary}`];
149
+ if (run.phaseId) lines.push(` phase: ${run.phaseId}`);
150
+ if (run.scope) lines.push(` scope: ${JSON.stringify(run.scope)}`);
151
+ if (run.isolationNote) lines.push(` isolation: ${run.isolationNote}`);
148
152
  // The trail is the progress answer: what the run has been doing,
149
153
  // newest last. It replaces pointing the parent at child session
150
154
  // files, which it cannot usefully read mid-run.
@@ -176,7 +180,14 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
176
180
  ...workflowRuns.map((run) => formatWorkflowStatus(run).join("\n")),
177
181
  ...retainedWorkflows.map((record) => formatRetainedWorkflow(record).join("\n")),
178
182
  ] : [];
179
- const sections = [text, ...workflowSections].filter((section) => section.trim().length > 0);
183
+ const selected = params.id === undefined ? undefined : runtime.threads.get(params.id);
184
+ const retainedResult = selected ? runtime.settledRuns.get(selected.id) ?? selected.lastResult : undefined;
185
+ const evidence = retainedResult && retainedResult.exitCode !== -1
186
+ ? retainedResult.resultFile
187
+ ? `Read the retained result: ${retainedResult.resultFile}`
188
+ : formatCompletionBlock(retainedResult, DEFAULT_MAX_RESULT_LINES, { resultRoot: projectResultsRoot(runtime.configPath, selected!.cwd) })
189
+ : "";
190
+ const sections = [text, ...workflowSections, evidence].filter((section) => section.trim().length > 0);
180
191
  const unknownWorkflow = workflowId !== undefined && workflowRuns.length === 0 && retainedWorkflows.length === 0;
181
192
  return {
182
193
  content: [{
@@ -113,6 +113,7 @@ export function formatCompletionBlock(
113
113
  if (result.integrationError) lines.push(`Integration error: ${result.integrationError}`);
114
114
  lines.push("");
115
115
  }
116
+ if (result.isolationNote) lines.push(`Isolation: ${result.isolationNote}`, "");
116
117
  if (!truncated) lines.push(text);
117
118
  // Failed-tool diagnostics ride along only when the run itself failed: they
118
119
  // explain the failure, while on a successful run a transient failed call
@@ -91,7 +91,7 @@ function renderBoard(groups: TaskGroup[], theme: Theme, width: number, overview?
91
91
  selected.add(row);
92
92
  used += cost;
93
93
  }
94
- // Completed graphs still report their progress without listing every completed node.
94
+ // Keep graph status visible even when no actionable node rows remain.
95
95
  for (const group of sorted) {
96
96
  if (!group.rows.length && group.header && used < capacity) { included.add(group); used++; }
97
97
  }
@@ -120,7 +120,7 @@ function workflowGroup(graph: WorkflowRun, runs: readonly RunView[], theme: Them
120
120
  const count = (state: WorkflowNodeRun["state"]) => graph.nodes.filter((node) => node.state === state).length;
121
121
  const completed = count("completed");
122
122
  const progress = completed + "/" + graph.nodes.length + " completed";
123
- const color = graph.state === "failed" ? "error" : graph.state === "completed" ? "success" : "accent";
123
+ const color = graph.state === "failed" ? "error" : "accent";
124
124
  const name = theme.fg(color, theme.bold("Workflow #" + graph.id + " · " + graph.name));
125
125
  const parts = [progress, ...(["failed", "blocked", "pending"] as const).filter((state) => count(state))
126
126
  .map((state) => count(state) + " " + (state === "pending" ? "waiting" : state))];
@@ -150,7 +150,7 @@ export function formatSubagentWidgetLines(
150
150
  ): string[] {
151
151
  if (width <= 0) return [];
152
152
  const graphIds = new Set(workflows.map((graph) => graph.id));
153
- const visibleWorkflows = workflows.filter((graph) => graph.state !== "stopped");
153
+ const visibleWorkflows = workflows.filter((graph) => graph.state !== "stopped" && graph.state !== "completed");
154
154
  const standalone = runs.filter((run) => (!run.workflow || !graphIds.has(run.workflow.workflowId)) && (isRunActiveStatus(run.status) || run.status === "failed"));
155
155
  const groups = visibleWorkflows.map((graph) => workflowGroup(graph, runs, theme, width, now));
156
156
  if (standalone.length) {
@@ -20,6 +20,7 @@ import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
20
20
  import { dirname, isAbsolute, join, resolve } from "node:path";
21
21
  import { getProjectRoot, getSubagentsRoot } from "../execution/spawn.ts";
22
22
  import { PARKED_RECORD_MAX_AGE_MS } from "../lifecycle/durable.ts";
23
+ import { migrateStoredRecordRoles } from "../configuration/role-migration.ts";
23
24
 
24
25
  export const WORKFLOWS_MANIFEST_FILE_NAME = "pi-subagents-workflows.json";
25
26
  const WORKFLOWS_MANIFEST_VERSION = 1;
@@ -111,19 +112,26 @@ function normalizeRecord(value: unknown): WorkflowRecord | undefined {
111
112
  };
112
113
  }
113
114
 
114
- async function readManifestRecords(path: string): Promise<WorkflowRecord[]> {
115
+ async function readManifest(path: string): Promise<{ records: WorkflowRecord[]; rolesMigrated: boolean }> {
115
116
  try {
116
117
  const parsed = JSON.parse(await readFile(path, "utf8")) as { records?: unknown };
117
- if (!Array.isArray(parsed.records)) return [];
118
- return parsed.records.flatMap((record) => {
118
+ if (!Array.isArray(parsed.records)) return { records: [], rolesMigrated: false };
119
+ let rolesMigrated = false;
120
+ for (const record of parsed.records) rolesMigrated = migrateStoredRecordRoles(record) || rolesMigrated;
121
+ const records = parsed.records.flatMap((record) => {
119
122
  const normalized = normalizeRecord(record);
120
123
  return normalized ? [normalized] : [];
121
124
  });
125
+ return { records, rolesMigrated };
122
126
  } catch {
123
- return [];
127
+ return { records: [], rolesMigrated: false };
124
128
  }
125
129
  }
126
130
 
131
+ async function readManifestRecords(path: string): Promise<WorkflowRecord[]> {
132
+ return (await readManifest(path)).records;
133
+ }
134
+
127
135
  async function writeManifest(path: string, records: readonly WorkflowRecord[]): Promise<void> {
128
136
  if (records.length === 0) {
129
137
  await rm(path, { force: true });
@@ -167,7 +175,12 @@ export async function removeWorkflowRecord(configPath: string, workflowId: numbe
167
175
  /** Records for one checkout, newest first. */
168
176
  export async function readWorkflowRecords(configPath: string, cwd: string): Promise<WorkflowRecord[]> {
169
177
  const path = getWorkflowsManifestPath(configPath, cwd);
170
- const records = (await readManifestRecords(path)).filter(
178
+ const migrated = await withFileMutationQueue(path, async () => {
179
+ const manifest = await readManifest(path);
180
+ if (manifest.rolesMigrated) await writeManifest(path, manifest.records);
181
+ return manifest.records;
182
+ });
183
+ const records = migrated.filter(
171
184
  (record) => process.platform === "win32"
172
185
  ? record.cwd.toLowerCase() === resolve(cwd).toLowerCase()
173
186
  : record.cwd === resolve(cwd),
@@ -31,6 +31,7 @@ import {
31
31
  type WorkflowRecord,
32
32
  } from "./durable.ts";
33
33
  import type { WorkflowNodeRun, WorkflowRun, WorkflowRunState } from "./state.ts";
34
+ import type { PhaseScope } from "../delegation/phase-scope.ts";
34
35
 
35
36
  /** Lines of one node's answer inlined into the graph summary. The complete text
36
37
  * of every node is always written to a single workflow artifact, so nothing is
@@ -147,6 +148,7 @@ async function dispatchNode(ctx: RunContext, node: WorkflowNodeRun): Promise<voi
147
148
  started = await ctx.startBackground(node.agent, task, node.cwd, node.isolation ?? ctx.resolveIsolation(node.agent), {
148
149
  phaseId: node.phaseId,
149
150
  scope: node.scope,
151
+ automaticIsolation: node.isolation === undefined,
150
152
  deliveryRoute: "background",
151
153
  quiet: true,
152
154
  workflow: { workflowId: run.id, name: run.name, nodeId: node.id },
@@ -619,6 +621,10 @@ export interface WorkflowStatusView {
619
621
  id: string;
620
622
  agent: string;
621
623
  state: WorkflowNodeRun["state"];
624
+ task: string;
625
+ phaseId: string;
626
+ scope?: PhaseScope;
627
+ cwd: string;
622
628
  runId?: number;
623
629
  waitingFor?: string[];
624
630
  error?: string;
@@ -643,6 +649,10 @@ export function workflowStatus(run: WorkflowRun): WorkflowStatusView {
643
649
  id: node.id,
644
650
  agent: node.agent,
645
651
  state: node.state,
652
+ task: formatTaskSummary(node.task, 160, false),
653
+ phaseId: node.phaseId,
654
+ scope: node.scope,
655
+ cwd: node.cwd,
646
656
  ...(node.runId !== undefined ? { runId: node.runId } : {}),
647
657
  ...(node.state === "pending" && node.dependsOn.length > 0 ? { waitingFor: [...node.dependsOn] } : {}),
648
658
  ...(node.error ? { error: node.error } : {}),
@@ -669,6 +679,8 @@ export function formatWorkflowStatus(run: WorkflowRun): string[] {
669
679
  if (node.activity) parts.push(node.activity);
670
680
  if (node.error) parts.push(`error: ${formatTaskSummary(node.error, 200, false)}`);
671
681
  lines.push(` - ${parts.join(" · ")}`);
682
+ lines.push(` phase: ${node.phaseId} · task: ${node.task}`);
683
+ if (node.scope) lines.push(` scope: ${JSON.stringify(node.scope)}`);
672
684
  }
673
685
  return lines;
674
686
  }