@ferris1225/pi-subagents 5.0.6 → 6.0.1

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 (43) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/README.md +187 -97
  3. package/index.ts +1 -1
  4. package/package.json +4 -9
  5. package/src/configuration/role-migration.ts +2 -2
  6. package/src/configuration/setup.ts +4 -2
  7. package/src/configuration/ui.ts +144 -132
  8. package/src/delegation/agents.ts +15 -22
  9. package/src/delegation/dispatch.ts +17 -122
  10. package/src/delegation/prompt.ts +13 -12
  11. package/src/execution/cli-run.ts +112 -39
  12. package/src/execution/process-tree.ts +12 -8
  13. package/src/execution/run-control.ts +11 -3
  14. package/src/execution/spawn.ts +24 -7
  15. package/src/isolation/cleanup.ts +31 -12
  16. package/src/isolation/managed-paths.ts +6 -4
  17. package/src/isolation/manifest-mutation.ts +89 -0
  18. package/src/isolation/recovery.ts +33 -29
  19. package/src/isolation/temp-hygiene.ts +1 -1
  20. package/src/lifecycle/await-results.ts +114 -0
  21. package/src/lifecycle/dispatch-core.ts +7 -1
  22. package/src/lifecycle/durable.ts +83 -39
  23. package/src/lifecycle/runtime.ts +12 -4
  24. package/src/lifecycle/stop.ts +2 -2
  25. package/src/lifecycle/thread-lifecycle.ts +10 -5
  26. package/src/lifecycle/thread-restore.ts +26 -25
  27. package/src/lifecycle/thread-shared.ts +15 -3
  28. package/src/lifecycle/tools.ts +90 -33
  29. package/src/presentation/announcements.ts +8 -2
  30. package/src/presentation/monitor.ts +5 -3
  31. package/src/presentation/widget.ts +157 -113
  32. package/src/workflow/acceptance.ts +67 -0
  33. package/src/workflow/durable.ts +34 -14
  34. package/src/workflow/engine.ts +161 -51
  35. package/src/workflow/plan.ts +25 -4
  36. package/src/workflow/state.ts +6 -0
  37. package/src/workflow/templates.ts +156 -0
  38. package/src/workflow/tool.ts +65 -109
  39. package/skills/workflow/SKILL.md +0 -268
  40. package/src/workflow/files.ts +0 -236
  41. package/workflows/code-review.md +0 -38
  42. package/workflows/migration.md +0 -42
  43. package/workflows/research.md +0 -48
@@ -10,12 +10,13 @@
10
10
  * and disappears on its own. Records are small path/state snapshots, never
11
11
  * full transcripts; the retained Pi session files and worktrees they point at
12
12
  * remain the actual context. Writes are atomic (tmp+rename) and serialized
13
- * through the same withFileMutationQueue as the recovery manifest.
13
+ * through the same cross-process manifest lock as recovery records.
14
14
  */
15
15
 
16
- import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
16
+ import { createHash, randomUUID } from "node:crypto";
17
+ import { replaceManifestFile, withManifestMutation } from "../isolation/manifest-mutation.ts";
17
18
  import { existsSync, type Dirent, readdirSync, statSync } from "node:fs";
18
- import { mkdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
19
+ import { mkdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
19
20
  import { uptime } from "node:os";
20
21
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
21
22
  import type { UsageStats } from "../execution/run-control.ts";
@@ -25,6 +26,7 @@ import type { SubagentThread } from "./runtime.ts";
25
26
  import { getResultOutput, isFailedResult, getProjectRoot, getSubagentsRoot, type SingleResult } from "../execution/spawn.ts";
26
27
  import { isManagedSessionDir, isManagedWorktreeLayout, samePath } from "../isolation/managed-paths.ts";
27
28
  import { readRecoveryRecords, referencedRecoveryPaths } from "../isolation/recovery.ts";
29
+ import { isProcessAlive, readTempOwnerMarker } from "../isolation/temp-hygiene.ts";
28
30
  import {
29
31
  isPathInside,
30
32
  normalizeWorktreeSnapshot,
@@ -71,6 +73,8 @@ export interface ThreadResultSummary {
71
73
  }
72
74
 
73
75
  export interface ThreadRecord {
76
+ /** Stable identity across windows and locally renumbered restores. Absent in legacy records. */
77
+ durableId?: string;
74
78
  runId: number;
75
79
  createdAt: number;
76
80
  updatedAt: number;
@@ -180,6 +184,7 @@ function normalizeRecord(value: unknown): ThreadRecord | undefined {
180
184
  return undefined;
181
185
  }
182
186
  return {
187
+ ...(typeof raw.durableId === "string" && raw.durableId ? { durableId: raw.durableId } : {}),
183
188
  runId: raw.runId,
184
189
  createdAt: raw.createdAt,
185
190
  updatedAt: raw.updatedAt,
@@ -211,7 +216,6 @@ function normalizeRecord(value: unknown): ThreadRecord | undefined {
211
216
  }
212
217
 
213
218
  interface ThreadManifestRead {
214
- valid: boolean;
215
219
  rolesMigrated?: boolean;
216
220
  sourceCount: number;
217
221
  records: ThreadRecord[];
@@ -219,12 +223,11 @@ interface ThreadManifestRead {
219
223
 
220
224
  async function readManifest(path: string): Promise<ThreadManifestRead> {
221
225
  try {
222
- const parsed = JSON.parse(await readFile(path, "utf8")) as { records?: unknown };
223
- if (!Array.isArray(parsed.records)) return { valid: false, sourceCount: 0, records: [] };
226
+ const parsed = JSON.parse(await readFile(path, "utf8")) as { records?: unknown } | null;
227
+ if (!Array.isArray(parsed?.records)) throw new Error(`Invalid thread manifest: ${path}`);
224
228
  let rolesMigrated = false;
225
229
  for (const record of parsed.records) rolesMigrated = migrateStoredRecordRoles(record) || rolesMigrated;
226
230
  return {
227
- valid: true,
228
231
  rolesMigrated,
229
232
  sourceCount: parsed.records.length,
230
233
  records: parsed.records.flatMap((record) => {
@@ -232,8 +235,10 @@ async function readManifest(path: string): Promise<ThreadManifestRead> {
232
235
  return normalized ? [normalized] : [];
233
236
  }),
234
237
  };
235
- } catch {
236
- return { valid: false, sourceCount: 0, records: [] };
238
+ } catch (error) {
239
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { sourceCount: 0, records: [] };
240
+ // A failed read or corrupt document is not evidence that no records exist.
241
+ throw error;
237
242
  }
238
243
  }
239
244
 
@@ -262,25 +267,55 @@ async function validateThreadRecord(
262
267
  }
263
268
  const worktree = record.worktree;
264
269
  if (!worktree || !await isManagedWorktreeLayout(configPath, record.cwd, worktree)) return false;
265
- try {
266
- const canonicalCwd = await realpath(record.cwd);
267
- const canonicalRoot = await resolveRepositoryRoot(record.cwd);
268
- if (!samePath(worktree.originalCwd, canonicalCwd) || !samePath(worktree.originalRoot, canonicalRoot)) {
269
- return false;
270
- }
271
- if (!isPathInside(canonicalRoot, canonicalCwd)) return false;
272
- const restoredCwd = join(worktree.worktreePath, relative(canonicalRoot, canonicalCwd));
273
- if (!samePath(worktree.cwd, restoredCwd) || !samePath(record.executionCwd, restoredCwd)) return false;
274
- if (existsSync(worktree.cwd)) {
270
+ if (
271
+ !isAbsolute(worktree.originalCwd) || worktree.originalCwd !== resolve(worktree.originalCwd) ||
272
+ !isAbsolute(worktree.originalRoot) || worktree.originalRoot !== resolve(worktree.originalRoot) ||
273
+ !isPathInside(worktree.originalRoot, worktree.originalCwd)
274
+ ) return false;
275
+ const restoredCwd = join(worktree.worktreePath, relative(worktree.originalRoot, worktree.originalCwd));
276
+ if (!samePath(worktree.cwd, restoredCwd) || !samePath(record.executionCwd, restoredCwd)) return false;
277
+ if (existsSync(worktree.cwd)) {
278
+ try {
275
279
  const [realWorktree, realCwd] = await Promise.all([realpath(worktree.worktreePath), realpath(worktree.cwd)]);
276
- if (!samePath(realCwd, join(realWorktree, relative(canonicalRoot, canonicalCwd)))) return false;
280
+ if (!samePath(realCwd, join(realWorktree, relative(worktree.originalRoot, worktree.originalCwd)))) return false;
281
+ } catch (error) {
282
+ if (["ENOENT", "ENOTDIR"].includes((error as NodeJS.ErrnoException).code ?? "")) return false;
283
+ throw error;
277
284
  }
285
+ }
286
+ // Managed recovery references survive a missing checkout or failed Git
287
+ // discovery. A successfully resolved source must still match the snapshot.
288
+ try {
289
+ if (!samePath(worktree.originalCwd, await realpath(record.cwd))) return false;
290
+ } catch {
291
+ return true;
292
+ }
293
+ try {
294
+ return samePath(worktree.originalRoot, await resolveRepositoryRoot(record.cwd));
295
+ } catch {
278
296
  return true;
297
+ }
298
+ }
299
+
300
+ export async function isThreadSourceAvailable(record: ThreadRecord): Promise<boolean> {
301
+ if (!record.worktree) return true;
302
+ try {
303
+ return samePath(await realpath(record.cwd), record.worktree.originalCwd) &&
304
+ samePath(await resolveRepositoryRoot(record.cwd), record.worktree.originalRoot);
279
305
  } catch {
280
306
  return false;
281
307
  }
282
308
  }
283
309
 
310
+ /** Legacy identities include immutable source/artifact metadata, so adopting a
311
+ * record does not let a fresh run with the same display id overwrite it. */
312
+ export function threadRecordIdentity(record: ThreadRecord): string {
313
+ return record.durableId ?? `legacy-${createHash("sha256").update(JSON.stringify([
314
+ record.cwd, record.runId, record.createdAt, record.ownerPid, record.bootId,
315
+ record.sessionDir, record.worktree?.tempDir,
316
+ ])).digest("hex")}`;
317
+ }
318
+
284
319
  async function validatedManifestRecords(
285
320
  configPath: string,
286
321
  path: string,
@@ -294,10 +329,11 @@ async function validatedManifestRecords(
294
329
  function projectManifestPaths(durableRoot: string): string[] {
295
330
  try {
296
331
  return readdirSync(durableRoot, { withFileTypes: true })
297
- .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())
332
+ .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && !entry.name.endsWith(".lock"))
298
333
  .map((entry) => join(durableRoot, entry.name, THREADS_MANIFEST_FILE_NAME));
299
- } catch {
300
- return [];
334
+ } catch (error) {
335
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
336
+ throw error;
301
337
  }
302
338
  }
303
339
 
@@ -306,10 +342,10 @@ function projectManifestPaths(durableRoot: string): string[] {
306
342
  export async function readThreadRecords(configPath: string): Promise<ThreadRecord[]> {
307
343
  const manifests = await Promise.all(
308
344
  projectManifestPaths(getSubagentsRoot(configPath))
309
- .map((path) => withFileMutationQueue(path, async () => {
345
+ .map((path) => withManifestMutation(path, async () => {
310
346
  const manifest = await readManifest(path);
311
347
  const validated = await validatedManifestRecords(configPath, path, manifest.records);
312
- if (!manifest.valid || manifest.rolesMigrated || validated.length !== manifest.sourceCount) await writeManifest(path, validated);
348
+ if (manifest.rolesMigrated || validated.length !== manifest.sourceCount) await writeManifest(path, validated);
313
349
  return validated;
314
350
  })),
315
351
  );
@@ -329,7 +365,7 @@ async function writeManifest(path: string, records: readonly ThreadRecord[]): Pr
329
365
  records: [...records],
330
366
  };
331
367
  await writeFile(temporaryPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
332
- await rename(temporaryPath, path);
368
+ await replaceManifestFile(temporaryPath, path);
333
369
  } finally {
334
370
  await rm(temporaryPath, { force: true }).catch(() => undefined);
335
371
  }
@@ -337,23 +373,24 @@ async function writeManifest(path: string, records: readonly ThreadRecord[]): Pr
337
373
 
338
374
  export async function upsertThreadRecord(configPath: string, record: ThreadRecord): Promise<void> {
339
375
  const path = getThreadsManifestPath(configPath, record.cwd);
340
- await withFileMutationQueue(path, async () => {
376
+ await withManifestMutation(path, async () => {
341
377
  const records = await readManifestRecords(path);
342
- const index = records.findIndex((candidate) => candidate.runId === record.runId);
378
+ const identity = threadRecordIdentity(record);
379
+ const index = records.findIndex((candidate) => threadRecordIdentity(candidate) === identity);
343
380
  const merged: ThreadRecord = index === -1
344
- ? record
345
- : { ...record, createdAt: records[index]!.createdAt };
381
+ ? { ...record, durableId: identity }
382
+ : { ...record, durableId: identity, createdAt: records[index]!.createdAt };
346
383
  if (index === -1) records.push(merged);
347
384
  else records[index] = merged;
348
385
  await writeManifest(path, records);
349
386
  });
350
387
  }
351
388
 
352
- export async function removeThreadRecord(configPath: string, runId: number, cwd: string): Promise<void> {
389
+ export async function removeThreadRecord(configPath: string, identity: string, cwd: string): Promise<void> {
353
390
  const path = getThreadsManifestPath(configPath, cwd);
354
- await withFileMutationQueue(path, async () => {
391
+ await withManifestMutation(path, async () => {
355
392
  const records = await readManifestRecords(path);
356
- const next = records.filter((record) => record.runId !== runId);
393
+ const next = records.filter((record) => threadRecordIdentity(record) !== identity);
357
394
  if (next.length === records.length) return;
358
395
  await writeManifest(path, next);
359
396
  });
@@ -389,7 +426,9 @@ export function threadRecordFromThread(
389
426
  now = Date.now(),
390
427
  ): ThreadRecord {
391
428
  const worktree = thread.worktree ? worktreeSnapshot(thread.worktree) : undefined;
429
+ thread.durableId ??= previous ? threadRecordIdentity(previous) : randomUUID();
392
430
  return {
431
+ durableId: thread.durableId,
393
432
  runId: thread.id,
394
433
  createdAt: previous?.createdAt ?? now,
395
434
  updatedAt: now,
@@ -447,7 +486,7 @@ export async function discardRecordArtifacts(record: ThreadRecord): Promise<void
447
486
  if (record.sessionDir) {
448
487
  await rm(record.sessionDir, { recursive: true, force: true }).catch(() => undefined);
449
488
  }
450
- if (record.worktree && (record.worktree.state === "active" || record.worktree.state === "retained")) {
489
+ if (record.worktree && (record.worktree.state === "active" || record.worktree.state === "retained") && await isThreadSourceAvailable(record)) {
451
490
  const worktree = await restoreWorktreeIsolation(record.worktree).catch(() => undefined);
452
491
  await worktree?.discard().catch(() => undefined);
453
492
  }
@@ -461,16 +500,19 @@ export async function pruneThreadRecords(
461
500
  ): Promise<void> {
462
501
  const durableRoot = getSubagentsRoot(configPath);
463
502
  for (const path of projectManifestPaths(durableRoot)) {
464
- await withFileMutationQueue(path, async () => {
503
+ await withManifestMutation(path, async () => {
465
504
  const manifest = await readManifest(path);
466
505
  const records = manifest.records;
467
- if (manifest.valid && records.length === 0) return;
506
+ if (manifest.sourceCount === 0) return;
468
507
  const validity = await Promise.all(records.map((record) => validateThreadRecord(configPath, path, record)));
469
- let changed = !manifest.valid || manifest.sourceCount !== records.length || validity.some((valid) => !valid);
508
+ let changed = Boolean(manifest.rolesMigrated) || manifest.sourceCount !== records.length || validity.some((valid) => !valid);
470
509
  const kept: ThreadRecord[] = [];
471
510
  for (const [index, record] of records.entries()) {
472
511
  if (!validity[index]) continue;
473
- if (now - record.updatedAt <= PARKED_RECORD_MAX_AGE_MS) {
512
+ const live = isCurrentBoot(record) && (
513
+ (record.ownerPid !== undefined && isProcessAlive(record.ownerPid)) || record.childPids.some(isProcessAlive)
514
+ );
515
+ if (live || now - record.updatedAt <= PARKED_RECORD_MAX_AGE_MS) {
474
516
  kept.push(record);
475
517
  continue;
476
518
  }
@@ -520,6 +562,8 @@ function isIdleSince(root: string, cutoffMs: number, now: number): boolean {
520
562
  const stack: string[] = [root];
521
563
  while (stack.length > 0) {
522
564
  const dir = stack.pop()!;
565
+ const owner = readTempOwnerMarker(dir);
566
+ if (owner && isProcessAlive(owner.pid)) return false;
523
567
  let entries: Dirent[];
524
568
  try {
525
569
  entries = readdirSync(dir, { withFileTypes: true });
@@ -565,7 +609,7 @@ export async function pruneStaleProjectRoots(
565
609
  }
566
610
  const removed: string[] = [];
567
611
  for (const project of projects) {
568
- if (!project.isDirectory() || project.isSymbolicLink()) continue;
612
+ if (!project.isDirectory() || project.isSymbolicLink() || project.name.endsWith(".lock")) continue;
569
613
  const projectDir = join(root, project.name);
570
614
  if (containsReferencedPath(projectDir, referenced)) continue;
571
615
  if (!isIdleSince(projectDir, now - PROJECT_ROOT_MAX_AGE_MS, now)) continue;
@@ -24,7 +24,7 @@ import {
24
24
  import { type ThinkingLevel } from "../configuration/config.ts";
25
25
  import { removeThreadRecord, threadRecordFromThread, upsertThreadRecord, type ThreadRecord } from "./durable.ts";
26
26
  import { isRunActiveStatus, monitor, type RunWorkflowTag } from "../presentation/monitor.ts";
27
- import type { RunControl } from "../execution/run-control.ts";
27
+ import type { RunControl, SteeringReceipt } from "../execution/run-control.ts";
28
28
  import { isFailedResult, type SingleResult } from "../execution/spawn.ts";
29
29
  import type { IsolationMode, WorktreeFinalization, WorktreeIsolation } from "../isolation/worktree.ts";
30
30
  import type { WorkflowRun } from "../workflow/state.ts";
@@ -34,6 +34,8 @@ export type ThreadState = "queued" | "running" | "interrupting" | "parked" | "co
34
34
  export type ThreadLifecycleOperation = "stop" | "settle";
35
35
 
36
36
  export interface SubagentThread {
37
+ /** Stable manifest identity; display ids are local to a Pi window. */
38
+ durableId?: string;
37
39
  id: number;
38
40
  generation: number;
39
41
  agentName: string;
@@ -56,6 +58,8 @@ export interface SubagentThread {
56
58
  restorationRecord?: ThreadRecord;
57
59
  state: ThreadState;
58
60
  control: RunControl;
61
+ /** Last child acknowledgement; queued delivery does not prove model execution. */
62
+ lastSteering?: SteeringReceipt & { message: string };
59
63
  queueController?: AbortController;
60
64
  /** Resolves after the child, isolation finalization, and queue work fully quiesce. */
61
65
  generationCompletion: Promise<void>;
@@ -127,6 +131,8 @@ export interface SubagentRuntime {
127
131
  mainWrites: Map<string, { toolName: string; scope: PhaseScope }>;
128
132
  /** Workflow graphs started in this parent session, live and settled. */
129
133
  workflows: Map<number, WorkflowRun>;
134
+ /** Stable mapping from persisted identities to this window's display ids. */
135
+ workflowRecordIds: Map<string, number>;
130
136
  /** Allocate a graph id that no retained or live workflow record owns. */
131
137
  reserveWorkflowId: () => number;
132
138
  /** Raise the graph-id allocator above an id restored from a durable record. */
@@ -251,6 +257,7 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
251
257
  threads: new Map<number, SubagentThread>(),
252
258
  mainWrites: new Map(),
253
259
  workflows: new Map<number, WorkflowRun>(),
260
+ workflowRecordIds: new Map(),
254
261
  reserveWorkflowId: () => nextWorkflowId++,
255
262
  ensureWorkflowIdAbove: (id) => {
256
263
  if (id >= nextWorkflowId) nextWorkflowId = id + 1;
@@ -331,7 +338,7 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
331
338
  // thread whose settlement finished during the wait above already
332
339
  // wrote (or removed) its own record; the lastResult-derived state
333
340
  // below matches it.
334
- const settled: Array<{ runId: number; cwd: string }> = [];
341
+ const settled: Array<{ identity: string; cwd: string }> = [];
335
342
  const records: ThreadRecord[] = [];
336
343
  for (const thread of runtime.threads.values()) {
337
344
  if (thread.retired) continue;
@@ -354,11 +361,11 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
354
361
  state = "parked";
355
362
  }
356
363
  if (state === "parked") records.push(threadRecordFromThread(thread, state));
357
- else settled.push({ runId: thread.id, cwd: thread.cwd });
364
+ else if (thread.durableId) settled.push({ identity: thread.durableId, cwd: thread.cwd });
358
365
  }
359
366
  await Promise.all([
360
367
  ...records.map((record) => upsertThreadRecord(runtime.configPath, record).catch(() => undefined)),
361
- ...settled.map(({ runId, cwd }) => removeThreadRecord(runtime.configPath, runId, cwd).catch(() => undefined)),
368
+ ...settled.map(({ identity, cwd }) => removeThreadRecord(runtime.configPath, identity, cwd).catch(() => undefined)),
362
369
  ]);
363
370
  // Retained-failure recovery records are persisted by the finalization
364
371
  // itself; shutdown only drops sessions no record claims anymore.
@@ -394,6 +401,7 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
394
401
  runtime.threads.clear();
395
402
  runtime.mainWrites.clear();
396
403
  runtime.workflows.clear();
404
+ runtime.workflowRecordIds.clear();
397
405
  runtime.shutdownHooks = [];
398
406
  monitor.clear();
399
407
  },
@@ -159,7 +159,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
159
159
  ...(existsSync(worktree.worktreePath) ? { worktreePath: worktree.worktreePath } : {}),
160
160
  ...(existsSync(worktree.patchPath) ? { patchPath: worktree.patchPath } : {}),
161
161
  error: "subagent_stop timed out waiting for worktree integration; it continues in the background",
162
- }),
162
+ }, Date.now(), thread.durableId),
163
163
  ]).catch(() => undefined);
164
164
  pendingIntegration.push(`#${runId}`);
165
165
  }
@@ -176,7 +176,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
176
176
  runtime.retireThreadSession(thread);
177
177
  // The destructive retire removes the durable record with the session;
178
178
  // an id never resurrects after subagent_stop.
179
- await removeThreadRecord(runtime.configPath, runId, thread.cwd).catch(() => undefined);
179
+ if (thread.durableId) await removeThreadRecord(runtime.configPath, thread.durableId, thread.cwd).catch(() => undefined);
180
180
  // Returning from a bounded stop retires context, but cannot release a
181
181
  // writer or phase lease while a child or Git tail can still change files.
182
182
  void Promise.allSettled([interruptionPromises[claimIndex]!, completion, finalizationCompletion]).then(() => {
@@ -7,6 +7,7 @@
7
7
  * recovery artifacts, and guarded one-time terminal publication.
8
8
  */
9
9
 
10
+ import { randomUUID } from "node:crypto";
10
11
  import { join, resolve } from "node:path";
11
12
  import { isWriteCapableAgent, resolveAgentTools, type AgentConfig } from "../delegation/agents.ts";
12
13
  import type { CompletionMessageItem } from "./completion.ts";
@@ -128,10 +129,12 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
128
129
  // owner and leaves the caller with no way forward.
129
130
  const owner = duplicate.source;
130
131
  const remedy = owner.state === "parked" || owner.retired
131
- ? `That run was interrupted (possibly in an earlier session) and keeps the phase claimed; retire it with subagent_stop({ id: ${owner.id} }) to reuse the phase, or give this work a different phaseId. Main handles follow-up work.`
132
- : owner.state === "completed" || owner.state === "failed"
133
- ? "Inspect it with subagent_status; a different deliverable needs a different phaseId. Main handles follow-up work."
134
- : "Do not redispatch it; inspect its result or let it finish. Main handles follow-up work.";
132
+ ? `That interrupted run keeps the phase claimed. Inspect its retained result with subagent_status and finish from that evidence. Retire it with subagent_stop({ id: "${owner.id}" }) only if discarding its retained session is intended; then the phase can be reused. Changing only phaseId cannot bypass equal-task ownership.`
133
+ : owner.state === "completed"
134
+ ? `Reuse its result via subagent_status({ id: ${owner.id} }); use subagent_message({ id: ${owner.id}, message: "<bounded next step>" }) for additional work. A new deliverable needs its own brief and phaseId.`
135
+ : owner.state === "failed"
136
+ ? "Inspect the failure with subagent_status and finish the remaining work from its evidence. Do not repeat the same phase."
137
+ : "Do not redispatch it; let it finish or steer it with subagent_message. Its result returns automatically; then continue the task.";
135
138
  return failedStartResult(agentName, task,
136
139
  `Run #${owner.id} (${owner.agentName}) already owns this logical phase (${owner.state}). ${remedy}`);
137
140
  }
@@ -187,6 +190,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
187
190
 
188
191
  thread = {
189
192
  id: runId,
193
+ durableId: randomUUID(),
190
194
  generation,
191
195
  agentName: agent.name,
192
196
  task,
@@ -485,6 +489,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
485
489
  /** Install the shared settlement hook for a fresh run or recovered worktree. */
486
490
  export function installThreadLifecycle(thread: SubagentThread, deps: ThreadLifecycleDeps): void {
487
491
  const { runtime } = deps;
492
+ thread.durableId ??= randomUUID();
488
493
  const runId = thread.id;
489
494
 
490
495
  thread.notifyIsolationFailure = (finalization) => {
@@ -556,7 +561,7 @@ export function installThreadLifecycle(thread: SubagentThread, deps: ThreadLifec
556
561
  // Every retained finalization gets a durable recovery record, so the
557
562
  // artifacts stay findable even when the owning process dies next.
558
563
  void persistRecoveryRecords(runtime.configPath, [
559
- recoveryRecordFromFinalization(runId, finalization),
564
+ recoveryRecordFromFinalization(runId, finalization, Date.now(), thread.durableId),
560
565
  ]).catch(() => undefined);
561
566
  }
562
567
  return finalization;
@@ -4,12 +4,14 @@ import { type ThinkingLevel } from "../configuration/config.ts";
4
4
  import {
5
5
  discardRecordArtifacts,
6
6
  isCurrentBoot,
7
+ isThreadSourceAvailable,
7
8
  pruneStaleProjectRoots,
8
9
  pruneThreadRecords,
9
10
  readReferencedDurablePaths,
10
11
  readThreadRecords,
11
12
  removeThreadRecord,
12
13
  restoredResultFromSummary,
14
+ threadRecordIdentity,
13
15
  type ThreadRecord,
14
16
  } from "./durable.ts";
15
17
  import { monitor } from "../presentation/monitor.ts";
@@ -19,7 +21,6 @@ import {
19
21
  getProjectRoot,
20
22
  getSubagentsRoot,
21
23
  RunControl,
22
- sessionExists,
23
24
  sweepProjectResultArtifacts,
24
25
  type SingleResult,
25
26
  } from "../execution/spawn.ts";
@@ -37,7 +38,7 @@ import { installThreadLifecycle } from "./thread-lifecycle.ts";
37
38
  async function discardRestoredRecord(runtime: SubagentRuntime, record: ThreadRecord): Promise<void> {
38
39
  await discardRecordArtifacts(record);
39
40
  if (record.sessionDir) runtime.sessionDirs.delete(record.sessionDir);
40
- await removeThreadRecord(runtime.configPath, record.runId, record.cwd).catch(() => undefined);
41
+ await removeThreadRecord(runtime.configPath, threadRecordIdentity(record), record.cwd).catch(() => undefined);
41
42
  }
42
43
 
43
44
  function createRestoredThread(
@@ -47,6 +48,7 @@ function createRestoredThread(
47
48
  state: ThreadState,
48
49
  ): SubagentThread {
49
50
  const thread: SubagentThread = {
51
+ durableId: threadRecordIdentity(record),
50
52
  id: record.runId,
51
53
  generation: record.generation,
52
54
  agentName: record.agentName,
@@ -86,9 +88,11 @@ function belongsToSessionProject(configPath: string, cwd: string, record: Thread
86
88
  export async function restoreDurableThreads(runtime: SubagentRuntime, cwd: string): Promise<number[]> {
87
89
  const records = await readThreadRecords(runtime.configPath);
88
90
  const restoredIds: number[] = [];
89
- for (const record of records) {
90
- if (!belongsToSessionProject(runtime.configPath, cwd, record)) continue;
91
- if (runtime.threads.has(record.runId) || monitor.findRun(record.runId)) continue;
91
+ const localRecords = records.filter((record) => belongsToSessionProject(runtime.configPath, cwd, record));
92
+ for (const record of localRecords) monitor.ensureNextIdAbove(record.runId);
93
+ for (let record of localRecords) {
94
+ const identity = threadRecordIdentity(record);
95
+ if ([...runtime.threads.values()].some((thread) => thread.durableId === identity)) continue;
92
96
  // Another Pi window may own this checkpoint, and PID reuse means a live
93
97
  // recorded child is not proof of ownership. Never kill either on restore.
94
98
  if (isCurrentBoot(record) && (
@@ -99,16 +103,17 @@ export async function restoreDurableThreads(runtime: SubagentRuntime, cwd: strin
99
103
  await discardRestoredRecord(runtime, record);
100
104
  continue;
101
105
  }
102
- const sessionValid =
103
- record.sessionId !== undefined &&
104
- record.sessionDir !== undefined &&
105
- sessionExists(record.sessionDir, record.sessionId);
106
- const restoredRecord = sessionValid ? record : { ...record, sessionId: undefined, sessionDir: undefined };
107
- const worktree = record.worktree
106
+ if (runtime.threads.has(record.runId) || monitor.findRun(record.runId)) {
107
+ record = { ...record, durableId: identity, runId: monitor.reserveRunId() };
108
+ }
109
+ // Keep validated recovery paths even when their files are temporarily
110
+ // missing or unreadable. Availability is checked when a session is used.
111
+ record = { ...record, durableId: identity };
112
+ const worktree = record.worktree && await isThreadSourceAvailable(record)
108
113
  ? await restoreWorktreeIsolation(record.worktree).catch(() => undefined)
109
114
  : undefined;
110
115
  const restorationFailed = record.isolation === "worktree" && record.worktree !== undefined && !worktree;
111
- const thread = createRestoredThread(runtime, restoredRecord, worktree, restorationFailed ? "failed" : "parked");
116
+ const thread = createRestoredThread(runtime, record, worktree, restorationFailed ? "failed" : "parked");
112
117
  runtime.threads.set(record.runId, thread);
113
118
  if (thread.sessionDir) runtime.sessionDirs.add(thread.sessionDir);
114
119
  if (restorationFailed) {
@@ -174,16 +179,17 @@ export async function restoreDurableThreads(runtime: SubagentRuntime, cwd: strin
174
179
  return restoredIds;
175
180
  }
176
181
 
177
- /** Session-start durable bootstrap: restore threads, age out expired records, and
178
- * sweep leaked temp/state directories. Every stage is best-effort so a broken
179
- * manifest never blocks the session.
180
- *
181
- * Restore is published on the runtime as `durableRestore` before this returns,
182
- * so callers that must see restored threads await that pass alone and never the
183
- * hygiene sweeps behind it. Hygiene still runs after restore: pruning decides
184
- * what to delete from the records restore has already claimed. */
182
+ /** Age out expired records before restoring threads, then sweep leaked state.
183
+ * Each stage is best-effort so a broken manifest never blocks the session.
184
+ * `durableRestore` includes pruning: callers cannot see a restored owner whose
185
+ * checkpoint the same startup is about to delete. Later sweeps run separately. */
185
186
  export function bootstrapDurableState(runtime: SubagentRuntime, cwd: string): Promise<void> {
186
187
  const restore = (async () => {
188
+ try {
189
+ await pruneThreadRecords(runtime.configPath);
190
+ } catch {
191
+ /* unreadable recovery references remain protected */
192
+ }
187
193
  try {
188
194
  runtime.restoredRunIds = await restoreDurableThreads(runtime, cwd);
189
195
  } catch {
@@ -193,11 +199,6 @@ export function bootstrapDurableState(runtime: SubagentRuntime, cwd: string): Pr
193
199
  runtime.durableRestore = restore;
194
200
  return (async () => {
195
201
  await restore;
196
- try {
197
- await pruneThreadRecords(runtime.configPath);
198
- } catch {
199
- /* retention is best-effort */
200
- }
201
202
  const projectRoots = getSubagentsRoot(runtime.configPath);
202
203
  try {
203
204
  sweepProjectTempDirs(projectRoots);
@@ -1,12 +1,13 @@
1
1
  /** Shared contracts and coordination primitives for logical sub-agent threads. */
2
2
 
3
+ import { utimesSync } from "node:fs";
3
4
  import { realpath } from "node:fs/promises";
4
5
  import { join, resolve } from "node:path";
5
6
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
6
7
  import { isWriteCapableAgent, type AgentConfig, type ToolMetadata } from "../delegation/agents.ts";
7
8
  import type { PhaseScope } from "../delegation/phase-scope.ts";
8
9
  import { roleThinkingLevel, type SubagentsConfig, type ThinkingLevel } from "../configuration/config.ts";
9
- import { removeThreadRecord, threadRecordFromThread, upsertThreadRecord } from "./durable.ts";
10
+ import { removeThreadRecord, threadRecordFromThread, threadRecordIdentity, upsertThreadRecord } from "./durable.ts";
10
11
  import {
11
12
  availableModelsInScope,
12
13
  currentModelRef,
@@ -86,9 +87,20 @@ export function persistThreadCheckpoint(
86
87
  thread: SubagentThread,
87
88
  state: "parked" | "completed" | "failed",
88
89
  ): void {
90
+ if (state !== "parked" && thread.sessionDir) {
91
+ // Transcript appends do not touch the directory. Start the follow-up
92
+ // retention window at settlement, including slow isolation finalization.
93
+ try {
94
+ const now = new Date();
95
+ utimesSync(thread.sessionDir, now, now);
96
+ } catch {
97
+ /* A missing or locked session must not prevent settlement. */
98
+ }
99
+ }
100
+ const record = threadRecordFromThread(thread, state);
89
101
  const write = state === "parked"
90
- ? upsertThreadRecord(runtime.configPath, threadRecordFromThread(thread, state))
91
- : removeThreadRecord(runtime.configPath, thread.id, thread.cwd);
102
+ ? upsertThreadRecord(runtime.configPath, record)
103
+ : removeThreadRecord(runtime.configPath, threadRecordIdentity(record), thread.cwd);
92
104
  void write.catch(() => undefined);
93
105
  }
94
106