@ferris1225/pi-subagents 6.0.0 → 6.0.2

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.
@@ -24,6 +24,7 @@ import {
24
24
  } from "./run-control.ts";
25
25
  import {
26
26
  currentSubagentDepth,
27
+ findSessionFile,
27
28
  runCliAgentAttempt,
28
29
  sessionExists,
29
30
  } from "./cli-run.ts";
@@ -31,6 +32,7 @@ import { writeTempOwnerMarker } from "../isolation/temp-hygiene.ts";
31
32
 
32
33
  export {
33
34
  currentSubagentDepth,
35
+ findSessionFile,
34
36
  RunControl,
35
37
  sessionExists,
36
38
  };
@@ -254,7 +256,7 @@ export function getResultOutput(result: SingleResult): string {
254
256
  /** Model handoff preserves useful history, but main or siblings may have edited
255
257
  * the workspace since the selected model last read it. */
256
258
  const RESUME_CONTINUATION_RULES =
257
- "Your earlier work — searches, reads, edits, and reasoning — is preserved in this session's history above; review it before acting. Do not redo searches, reads, or edits that already succeeded. The workspace may have changed while this thread was inactive: before editing a file, re-read it unless you read it during this continuation. Finish with the result-only handoff your role requires.";
259
+ "Your earlier work — searches, reads, edits, and reasoning — is preserved in this session's history above; review it before acting. Do not redo searches, reads, or edits that already succeeded. The workspace may have changed while this thread was inactive: before editing a file, re-read it unless you read it during this continuation. The current cwd is authoritative; do not reuse paths to an earlier temporary worktree. Finish with the result-only handoff your role requires.";
258
260
 
259
261
  /** The objective is a multi-line brief, so it gets its own block instead of
260
262
  * being spliced mid-sentence (where a trailing period also doubled up). */
@@ -379,7 +381,12 @@ export async function runSingleAgentWithMainFallback(
379
381
 
380
382
  const sessionId = options.sessionId ?? randomUUID();
381
383
  const sessionDir = options.sessionDir ?? (await createSessionDir(options.sessionRoot));
382
- const baseOptions: RunSingleOptions = { ...options, sessionDir, sessionId };
384
+ const baseOptions: RunSingleOptions = {
385
+ ...options, sessionDir, sessionId,
386
+ ...(options.sessionDir && options.stdinText === undefined
387
+ ? { stdinText: buildResumePrompt(options.task, "a follow-up was requested") }
388
+ : {}),
389
+ };
383
390
  if (!options.sessionDir) {
384
391
  // Surface the fresh session immediately so the dispatching thread can
385
392
  // persist a durable checkpoint before the child settles.
@@ -14,7 +14,7 @@ import { join } from "node:path";
14
14
  import { getSubagentsRoot, sweepProjectResultArtifacts } from "../execution/spawn.ts";
15
15
  import { pruneStaleProjectRoots, readReferencedDurablePaths, readThreadRecords } from "../lifecycle/durable.ts";
16
16
  import type { SubagentRuntime } from "../lifecycle/runtime.ts";
17
- import { isProcessAlive, sweepProjectDurableDirs, sweepProjectTempDirs } from "./temp-hygiene.ts";
17
+ import { isProcessAlive, readTempOwnerMarker, sweepProjectDurableDirs, sweepProjectTempDirs } from "./temp-hygiene.ts";
18
18
 
19
19
  /** Bytes a directory tree occupies, without following symlinks. */
20
20
  export function directoryBytes(path: string): number {
@@ -103,9 +103,10 @@ function removeEmptySessionCopies(path: string, claimed: readonly string[]): voi
103
103
  if (!entry.name.startsWith("pi-subagent-session-")) continue;
104
104
  const dir = join(path, "sessions", entry.name);
105
105
  if (claimed.some((claim) => claim.startsWith(dir))) continue;
106
- // A follow-up copies a session and the child resumes it; once that copy
107
- // holds nothing, it is pure overhead. Owner liveness already guards the
108
- // live case, so an empty unclaimed directory is safe to drop.
106
+ // The earlier orphan sweep kept live owners; this pass must honor the
107
+ // same guard while a fresh child has not written its first prompt yet.
108
+ const owner = readTempOwnerMarker(dir);
109
+ if (owner && isProcessAlive(owner.pid)) continue;
109
110
  let files = 0;
110
111
  try {
111
112
  files = readdirSync(dir).filter((name) => name !== "owner.json").length;
@@ -132,8 +133,8 @@ export interface CleanupResult {
132
133
  export async function runStorageCleanup(configPath: string, options: { now?: number; root?: string } = {}): Promise<CleanupResult> {
133
134
  const root = options.root ?? getSubagentsRoot(configPath);
134
135
  const before = measureDurableUsage(root);
135
- const records = await readThreadRecords(configPath).catch(() => []);
136
- const claimed = await readReferencedDurablePaths(configPath).catch(() => new Set<string>());
136
+ const records = await readThreadRecords(configPath);
137
+ const claimed = await readReferencedDurablePaths(configPath);
137
138
  const keep = (path: string) => [...claimed].some((claim) => path.startsWith(claim) || claim.startsWith(path));
138
139
 
139
140
  sweepProjectTempDirs(root);
@@ -203,6 +204,13 @@ export interface AutomaticCleanupOptions {
203
204
  force?: boolean;
204
205
  }
205
206
 
207
+ /** Another Pi process may still be preparing its checkpoint. Its owner marker
208
+ * protects the session even when this runtime has no thread or manifest for it. */
209
+ function hasForeignLiveOwner(path: string): boolean {
210
+ const owner = readTempOwnerMarker(path);
211
+ return owner !== undefined && owner.pid !== process.pid && isProcessAlive(owner.pid);
212
+ }
213
+
206
214
  interface SettledSession {
207
215
  path: string;
208
216
  mtimeMs: number;
@@ -221,6 +229,7 @@ function settledSessions(projectRoot: string): SettledSession[] {
221
229
  .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && entry.name.startsWith("pi-subagent-session-"))
222
230
  .flatMap((entry) => {
223
231
  const path = join(dir, entry.name);
232
+ if (hasForeignLiveOwner(path)) return [];
224
233
  try {
225
234
  // Pi appends the transcript in place, leaving the parent mtime
226
235
  // unchanged. Settlement also refreshes the directory timestamp.
@@ -306,7 +315,13 @@ export async function runAutomaticCleanup(
306
315
  if (!options.force && now - lastAutomaticCleanupAt < AUTO_CLEANUP_INTERVAL_MS) return { freedBytes: 0, skipped: true };
307
316
  lastAutomaticCleanupAt = now;
308
317
  const root = getSubagentsRoot(runtime.configPath);
309
- const claimed = await readReferencedDurablePaths(runtime.configPath).catch(() => new Set<string>());
318
+ let claimed: Set<string>;
319
+ try {
320
+ claimed = await readReferencedDurablePaths(runtime.configPath);
321
+ } catch {
322
+ // Unknown references cannot authorize deleting any recovery artifacts.
323
+ return { freedBytes: 0, skipped: true };
324
+ }
310
325
  const protectedPaths = protectedSessionPaths(runtime, claimed);
311
326
  const keep = (path: string) => protectedPaths.some((kept) => path.startsWith(kept) || kept.startsWith(path));
312
327
  const before = measureDurableUsage(root).totalBytes;
@@ -26,8 +26,9 @@ async function isPlainPath(path: string, kind: "directory" | "file"): Promise<bo
26
26
  try {
27
27
  const entry = await lstat(path);
28
28
  return !entry.isSymbolicLink() && (kind === "directory" ? entry.isDirectory() : entry.isFile());
29
- } catch {
30
- return false;
29
+ } catch (error) {
30
+ if (["ENOENT", "ENOTDIR"].includes((error as NodeJS.ErrnoException).code ?? "")) return false;
31
+ throw error;
31
32
  }
32
33
  }
33
34
 
@@ -35,8 +36,9 @@ async function isDirectRealChild(root: string, candidate: string): Promise<boole
35
36
  try {
36
37
  const [realRoot, realCandidate] = await Promise.all([realpath(root), realpath(candidate)]);
37
38
  return samePath(dirname(realCandidate), realRoot);
38
- } catch {
39
- return false;
39
+ } catch (error) {
40
+ if (["ENOENT", "ENOTDIR"].includes((error as NodeJS.ErrnoException).code ?? "")) return false;
41
+ throw error;
40
42
  }
41
43
  }
42
44
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
4
4
  import { randomUUID } from "node:crypto";
5
- import { mkdir, readdir, rmdir, stat, unlink, writeFile } from "node:fs/promises";
5
+ import { mkdir, readdir, rename, rmdir, stat, unlink, writeFile } from "node:fs/promises";
6
6
  import { uptime } from "node:os";
7
7
  import { dirname, join } from "node:path";
8
8
  import { setTimeout as delay } from "node:timers/promises";
@@ -12,6 +12,22 @@ const LOCK_TIMEOUT_MS = 15_000;
12
12
  const EMPTY_LOCK_MAX_AGE_MS = 60_000;
13
13
  const BOOT_TOLERANCE_MS = 60_000;
14
14
 
15
+ /** Windows can briefly deny replacement while another process inspects the
16
+ * checkpoint. Retry the same atomic rename under the caller's mutation lock;
17
+ * never unlink the last valid manifest to make a replacement succeed. */
18
+ export async function replaceManifestFile(temporaryPath: string, path: string): Promise<void> {
19
+ for (let attempt = 0; ; attempt++) {
20
+ try {
21
+ await rename(temporaryPath, path);
22
+ return;
23
+ } catch (error) {
24
+ const code = (error as NodeJS.ErrnoException).code;
25
+ if (process.platform !== "win32" || (code !== "EPERM" && code !== "EACCES") || attempt === 5) throw error;
26
+ await delay(25 * 2 ** attempt);
27
+ }
28
+ }
29
+ }
30
+
15
31
  function bootId(): number {
16
32
  return Math.round(Date.now() - uptime() * 1_000);
17
33
  }
@@ -1,8 +1,8 @@
1
1
  /** Durable handoff for worktree integration/cleanup failures across sessions. */
2
2
 
3
- import { withManifestMutation } from "./manifest-mutation.ts";
3
+ import { replaceManifestFile, withManifestMutation } from "./manifest-mutation.ts";
4
4
  import { existsSync } from "node:fs";
5
- import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
5
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
6
6
  import { dirname, join } from "node:path";
7
7
  import { stripVTControlCharacters } from "node:util";
8
8
  import { getProjectRoot, getSubagentsRoot } from "../execution/spawn.ts";
@@ -51,25 +51,25 @@ function normalizeRecord(value: unknown): RecoveryRecord | undefined {
51
51
  }
52
52
 
53
53
  interface RecoveryManifestRead {
54
- valid: boolean;
55
54
  sourceCount: number;
56
55
  records: RecoveryRecord[];
57
56
  }
58
57
 
59
58
  async function readManifest(path: string): Promise<RecoveryManifestRead> {
60
59
  try {
61
- const parsed = JSON.parse(await readFile(path, "utf8")) as { records?: unknown };
62
- if (!Array.isArray(parsed.records)) return { valid: false, sourceCount: 0, records: [] };
60
+ const parsed = JSON.parse(await readFile(path, "utf8")) as { records?: unknown } | null;
61
+ if (!Array.isArray(parsed?.records)) throw new Error(`Invalid recovery manifest: ${path}`);
63
62
  return {
64
- valid: true,
65
63
  sourceCount: parsed.records.length,
66
64
  records: parsed.records.flatMap((record) => {
67
65
  const normalized = normalizeRecord(record);
68
66
  return normalized ? [normalized] : [];
69
67
  }),
70
68
  };
71
- } catch {
72
- return { valid: false, sourceCount: 0, records: [] };
69
+ } catch (error) {
70
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { sourceCount: 0, records: [] };
71
+ // Keep the original document and its artifacts when references are unknown.
72
+ throw error;
73
73
  }
74
74
  }
75
75
 
@@ -91,7 +91,7 @@ export async function readRecoveryRecords(configPath: string): Promise<RecoveryR
91
91
  return withManifestMutation(path, async () => {
92
92
  const manifest = await readManifest(path);
93
93
  const records = await validatedRecords(configPath, manifest.records);
94
- if (!manifest.valid || records.length !== manifest.sourceCount) await writeManifest(path, records);
94
+ if (records.length !== manifest.sourceCount) await writeManifest(path, records);
95
95
  return records;
96
96
  });
97
97
  }
@@ -104,10 +104,6 @@ export async function relocateRecoveryManifest(configPath: string): Promise<void
104
104
  if (legacyPath === currentPath || !existsSync(legacyPath)) return;
105
105
  await withManifestMutation(legacyPath, async () => {
106
106
  const legacy = await readManifest(legacyPath);
107
- if (!legacy.valid) {
108
- await rm(legacyPath, { force: true });
109
- return;
110
- }
111
107
  await persistRecoveryRecords(configPath, legacy.records);
112
108
  await rm(legacyPath, { force: true });
113
109
  });
@@ -130,7 +126,7 @@ async function writeManifest(path: string, records: readonly RecoveryRecord[]):
130
126
  records: [...records],
131
127
  };
132
128
  await writeFile(temporaryPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
133
- await rename(temporaryPath, path);
129
+ await replaceManifestFile(temporaryPath, path);
134
130
  } finally {
135
131
  await rm(temporaryPath, { force: true }).catch(() => undefined);
136
132
  }
@@ -220,7 +216,7 @@ export async function announceRecoveryRecords(
220
216
  (record.worktreePath ? existsSync(record.worktreePath) : false) ||
221
217
  (record.patchPath ? existsSync(record.patchPath) : false),
222
218
  );
223
- if (!current.valid || remaining.length !== current.sourceCount) await writeManifest(path, remaining);
219
+ if (remaining.length !== current.sourceCount) await writeManifest(path, remaining);
224
220
  return remaining;
225
221
  });
226
222
  for (const record of live) {
@@ -72,7 +72,7 @@ export function writeTempOwnerMarker(dir: string, now = Date.now()): void {
72
72
  }
73
73
  }
74
74
 
75
- function readTempOwnerMarker(dir: string): TempOwner | undefined {
75
+ export function readTempOwnerMarker(dir: string): TempOwner | undefined {
76
76
  try {
77
77
  const parsed = JSON.parse(readFileSync(join(dir, TEMP_OWNER_FILE_NAME), "utf8")) as Partial<TempOwner>;
78
78
  if (typeof parsed.pid !== "number" || !Number.isInteger(parsed.pid) || parsed.pid <= 0) return undefined;
@@ -0,0 +1,114 @@
1
+ /** Shared in-turn completion delivery for dispatches and completed-run follow-ups. */
2
+
3
+ import { Type } from "typebox";
4
+ import { isFailedResult, type SingleResult } from "../execution/spawn.ts";
5
+ import { formatCompletionBlock } from "../presentation/format.ts";
6
+ import { monitor, statusLabel } from "../presentation/monitor.ts";
7
+ import type { SubagentRuntime } from "./runtime.ts";
8
+ import { projectResultsRoot } from "./thread-shared.ts";
9
+
10
+ export const WaitSchema = Type.Optional(Type.Boolean({
11
+ description: "Wait for runs started by this call and return their results once, after integration. Defaults to true in one-shot print/JSON sessions, false in TUI/RPC. Use true when the next step depends on the result; false to continue independent work. Cancelling the parent stops unfinished runs without background wake-ups.",
12
+ }));
13
+
14
+ /** In-turn wait for a new run or completed-run follow-up. Registration resolves it without a model-chosen
15
+ * timer; parent abort ends the wait and cancels its owned work. */
16
+ export async function awaitRunResults(
17
+ runtime: SubagentRuntime,
18
+ runIds: number[],
19
+ signal: AbortSignal | undefined,
20
+ maxResultLines: number,
21
+ fallbackCwd: string,
22
+ onProgress?: (text: string) => void,
23
+ ): Promise<string> {
24
+ const waitForRun = (runId: number): Promise<{ result?: SingleResult; note?: string }> => {
25
+ const already = runtime.settledRuns.get(runId);
26
+ if (already) return Promise.resolve({ result: already });
27
+ if (monitor.findRun(runId)?.status === "parked") {
28
+ return Promise.resolve({ note: `run #${runId} was interrupted; inspect retained work with subagent_status and finish it in main` });
29
+ }
30
+ return new Promise((resolve) => {
31
+ let done = false;
32
+ let unsub: (() => void) | undefined;
33
+ const cleanup = (): void => {
34
+ if (unsub) unsub();
35
+ signal?.removeEventListener("abort", onAbort);
36
+ const listeners = runtime.settledListeners.get(runId);
37
+ if (listeners) {
38
+ listeners.delete(onSettled);
39
+ if (listeners.size === 0) runtime.settledListeners.delete(runId);
40
+ }
41
+ };
42
+ const finish = (outcome: { result?: SingleResult; note?: string }): void => {
43
+ if (done) return;
44
+ done = true;
45
+ cleanup();
46
+ resolve(outcome);
47
+ };
48
+ const onSettled = (result: SingleResult): void => finish({ result });
49
+ const onMonitor = (): void => {
50
+ const current = runtime.settledRuns.get(runId);
51
+ if (current) {
52
+ finish({ result: current });
53
+ return;
54
+ }
55
+ const live = monitor.findRun(runId);
56
+ if (live?.status === "parked") {
57
+ finish({ note: `run #${runId} was interrupted; inspect retained work with subagent_status and finish it in main` });
58
+ return;
59
+ }
60
+ if (!live) {
61
+ // Removal is followed synchronously by registerRunResult in the
62
+ // finishing task; re-check on the next tick so the result wins.
63
+ setTimeout(() => {
64
+ const late = runtime.settledRuns.get(runId);
65
+ if (late) finish({ result: late });
66
+ else finish({ note: `run #${runId} was removed before its result was recorded (cancelled or session ended)` });
67
+ }, 0);
68
+ }
69
+ };
70
+ const onAbort = (): void => finish({ note: `Parent wait cancelled for run #${runId}; automatic cancellation stops unfinished child work. No additional subagent_stop is needed.` });
71
+ let listeners = runtime.settledListeners.get(runId);
72
+ if (!listeners) {
73
+ listeners = new Set();
74
+ runtime.settledListeners.set(runId, listeners);
75
+ }
76
+ listeners.add(onSettled);
77
+ unsub = monitor.subscribe(onMonitor);
78
+ if (signal?.aborted) onAbort();
79
+ else signal?.addEventListener("abort", onAbort, { once: true });
80
+ });
81
+ };
82
+ // One shared subscription drives the progress line: each waiter already
83
+ // subscribes for its own settlement, and the tool card wants a single
84
+ // rolled-up line rather than one per run.
85
+ let lastProgress: string | undefined;
86
+ const emitProgress = onProgress
87
+ ? (): void => {
88
+ const parts = runIds.map((id) => {
89
+ const settled = runtime.settledRuns.get(id);
90
+ if (settled) return `#${id} ${isFailedResult(settled) ? "failed" : "done"}`;
91
+ const live = monitor.findRun(id);
92
+ return live ? `#${id} ${statusLabel(live.status)}` : `#${id} …`;
93
+ });
94
+ const text = `Waiting in-turn on ${runIds.length} run${runIds.length === 1 ? "" : "s"} · ${parts.join(", ")}`;
95
+ // The monitor notifies on every usage and activity change; this line
96
+ // names only statuses, so most notifications leave it identical.
97
+ if (text === lastProgress) return;
98
+ lastProgress = text;
99
+ onProgress(text);
100
+ }
101
+ : undefined;
102
+ const progressUnsub = emitProgress ? monitor.subscribe(emitProgress) : undefined;
103
+ try {
104
+ emitProgress?.();
105
+ const outcomes = await Promise.all(runIds.map(waitForRun));
106
+ return outcomes.map((outcome) =>
107
+ outcome.result
108
+ ? formatCompletionBlock(outcome.result, maxResultLines, { resultRoot: projectResultsRoot(runtime.configPath, outcome.result.projectCwd ?? fallbackCwd) })
109
+ : (outcome.note ?? "(no outcome)"),
110
+ ).join("\n\n");
111
+ } finally {
112
+ progressUnsub?.();
113
+ }
114
+ }
@@ -28,6 +28,10 @@ export interface DispatchCore {
28
28
 
29
29
  export function createDispatchCore(runtime: SubagentRuntime): DispatchCore {
30
30
  const environmentRef: { current: DispatchEnvironment | undefined } = { current: undefined };
31
+ // Sweeps outlive the queue task which starts them. Drain every started pass
32
+ // before shutdown releases this runtime and its filesystem ownership.
33
+ let cleanupPending: Promise<void> = Promise.resolve();
34
+ runtime.shutdownHooks.push(() => cleanupPending);
31
35
 
32
36
  // Terminal rows stay in the monitor until the next beginTurn so the footer
33
37
  // can count them beside siblings that are still live. The widget ignores
@@ -46,7 +50,9 @@ export function createDispatchCore(runtime: SubagentRuntime): DispatchCore {
46
50
  if (endedAt !== undefined) publishedEndedAt.set(runId, endedAt);
47
51
  // Settlement is the natural moment to reclaim disk: a burst of runs costs
48
52
  // one paced sweep, and every live or parked thread stays protected.
49
- void runAutomaticCleanup(runtime).catch(() => undefined);
53
+ if (runtime.sessionActive) {
54
+ cleanupPending = Promise.allSettled([cleanupPending, runAutomaticCleanup(runtime)]).then(() => undefined);
55
+ }
50
56
  if (opts?.silent || !runtime.sessionActive) return;
51
57
  const icon = status === "done" ? "✓" : "✗";
52
58
  const result = runtime.threads.get(runId)?.lastResult;
@@ -14,9 +14,9 @@
14
14
  */
15
15
 
16
16
  import { createHash, randomUUID } from "node:crypto";
17
- import { withManifestMutation } from "../isolation/manifest-mutation.ts";
17
+ import { replaceManifestFile, withManifestMutation } from "../isolation/manifest-mutation.ts";
18
18
  import { existsSync, type Dirent, readdirSync, statSync } from "node:fs";
19
- import { mkdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
19
+ import { mkdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
20
20
  import { uptime } from "node:os";
21
21
  import { dirname, isAbsolute, join, relative, resolve } from "node:path";
22
22
  import type { UsageStats } from "../execution/run-control.ts";
@@ -26,6 +26,7 @@ import type { SubagentThread } from "./runtime.ts";
26
26
  import { getResultOutput, isFailedResult, getProjectRoot, getSubagentsRoot, type SingleResult } from "../execution/spawn.ts";
27
27
  import { isManagedSessionDir, isManagedWorktreeLayout, samePath } from "../isolation/managed-paths.ts";
28
28
  import { readRecoveryRecords, referencedRecoveryPaths } from "../isolation/recovery.ts";
29
+ import { isProcessAlive, readTempOwnerMarker } from "../isolation/temp-hygiene.ts";
29
30
  import {
30
31
  isPathInside,
31
32
  normalizeWorktreeSnapshot,
@@ -215,7 +216,6 @@ function normalizeRecord(value: unknown): ThreadRecord | undefined {
215
216
  }
216
217
 
217
218
  interface ThreadManifestRead {
218
- valid: boolean;
219
219
  rolesMigrated?: boolean;
220
220
  sourceCount: number;
221
221
  records: ThreadRecord[];
@@ -223,12 +223,11 @@ interface ThreadManifestRead {
223
223
 
224
224
  async function readManifest(path: string): Promise<ThreadManifestRead> {
225
225
  try {
226
- const parsed = JSON.parse(await readFile(path, "utf8")) as { records?: unknown };
227
- 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}`);
228
228
  let rolesMigrated = false;
229
229
  for (const record of parsed.records) rolesMigrated = migrateStoredRecordRoles(record) || rolesMigrated;
230
230
  return {
231
- valid: true,
232
231
  rolesMigrated,
233
232
  sourceCount: parsed.records.length,
234
233
  records: parsed.records.flatMap((record) => {
@@ -236,8 +235,10 @@ async function readManifest(path: string): Promise<ThreadManifestRead> {
236
235
  return normalized ? [normalized] : [];
237
236
  }),
238
237
  };
239
- } catch {
240
- 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;
241
242
  }
242
243
  }
243
244
 
@@ -277,8 +278,9 @@ async function validateThreadRecord(
277
278
  try {
278
279
  const [realWorktree, realCwd] = await Promise.all([realpath(worktree.worktreePath), realpath(worktree.cwd)]);
279
280
  if (!samePath(realCwd, join(realWorktree, relative(worktree.originalRoot, worktree.originalCwd)))) return false;
280
- } catch {
281
- return false;
281
+ } catch (error) {
282
+ if (["ENOENT", "ENOTDIR"].includes((error as NodeJS.ErrnoException).code ?? "")) return false;
283
+ throw error;
282
284
  }
283
285
  }
284
286
  // Managed recovery references survive a missing checkout or failed Git
@@ -329,8 +331,9 @@ function projectManifestPaths(durableRoot: string): string[] {
329
331
  return readdirSync(durableRoot, { withFileTypes: true })
330
332
  .filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && !entry.name.endsWith(".lock"))
331
333
  .map((entry) => join(durableRoot, entry.name, THREADS_MANIFEST_FILE_NAME));
332
- } catch {
333
- return [];
334
+ } catch (error) {
335
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
336
+ throw error;
334
337
  }
335
338
  }
336
339
 
@@ -342,7 +345,7 @@ export async function readThreadRecords(configPath: string): Promise<ThreadRecor
342
345
  .map((path) => withManifestMutation(path, async () => {
343
346
  const manifest = await readManifest(path);
344
347
  const validated = await validatedManifestRecords(configPath, path, manifest.records);
345
- 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);
346
349
  return validated;
347
350
  })),
348
351
  );
@@ -362,7 +365,7 @@ async function writeManifest(path: string, records: readonly ThreadRecord[]): Pr
362
365
  records: [...records],
363
366
  };
364
367
  await writeFile(temporaryPath, `${JSON.stringify(manifest, null, 2)}\n`, "utf8");
365
- await rename(temporaryPath, path);
368
+ await replaceManifestFile(temporaryPath, path);
366
369
  } finally {
367
370
  await rm(temporaryPath, { force: true }).catch(() => undefined);
368
371
  }
@@ -500,13 +503,16 @@ export async function pruneThreadRecords(
500
503
  await withManifestMutation(path, async () => {
501
504
  const manifest = await readManifest(path);
502
505
  const records = manifest.records;
503
- if (manifest.valid && records.length === 0) return;
506
+ if (manifest.sourceCount === 0) return;
504
507
  const validity = await Promise.all(records.map((record) => validateThreadRecord(configPath, path, record)));
505
- 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);
506
509
  const kept: ThreadRecord[] = [];
507
510
  for (const [index, record] of records.entries()) {
508
511
  if (!validity[index]) continue;
509
- 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) {
510
516
  kept.push(record);
511
517
  continue;
512
518
  }
@@ -556,6 +562,8 @@ function isIdleSince(root: string, cutoffMs: number, now: number): boolean {
556
562
  const stack: string[] = [root];
557
563
  while (stack.length > 0) {
558
564
  const dir = stack.pop()!;
565
+ const owner = readTempOwnerMarker(dir);
566
+ if (owner && isProcessAlive(owner.pid)) return false;
559
567
  let entries: Dirent[];
560
568
  try {
561
569
  entries = readdirSync(dir, { withFileTypes: true });
@@ -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";
@@ -58,6 +58,8 @@ export interface SubagentThread {
58
58
  restorationRecord?: ThreadRecord;
59
59
  state: ThreadState;
60
60
  control: RunControl;
61
+ /** Last child acknowledgement; queued delivery does not prove model execution. */
62
+ lastSteering?: SteeringReceipt & { message: string };
61
63
  queueController?: AbortController;
62
64
  /** Resolves after the child, isolation finalization, and queue work fully quiesce. */
63
65
  generationCompletion: Promise<void>;
@@ -129,10 +129,12 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
129
129
  // owner and leaves the caller with no way forward.
130
130
  const owner = duplicate.source;
131
131
  const remedy = owner.state === "parked" || owner.retired
132
- ? `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.`
133
- : owner.state === "completed" || owner.state === "failed"
134
- ? "Inspect it with subagent_status; a different deliverable needs a different phaseId. Main handles follow-up work."
135
- : "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.";
136
138
  return failedStartResult(agentName, task,
137
139
  `Run #${owner.id} (${owner.agentName}) already owns this logical phase (${owner.state}). ${remedy}`);
138
140
  }
@@ -21,7 +21,6 @@ import {
21
21
  getProjectRoot,
22
22
  getSubagentsRoot,
23
23
  RunControl,
24
- sessionExists,
25
24
  sweepProjectResultArtifacts,
26
25
  type SingleResult,
27
26
  } from "../execution/spawn.ts";
@@ -107,18 +106,14 @@ export async function restoreDurableThreads(runtime: SubagentRuntime, cwd: strin
107
106
  if (runtime.threads.has(record.runId) || monitor.findRun(record.runId)) {
108
107
  record = { ...record, durableId: identity, runId: monitor.reserveRunId() };
109
108
  }
110
- // Freeze a legacy identity before dropping missing session metadata.
109
+ // Keep validated recovery paths even when their files are temporarily
110
+ // missing or unreadable. Availability is checked when a session is used.
111
111
  record = { ...record, durableId: identity };
112
- const sessionValid =
113
- record.sessionId !== undefined &&
114
- record.sessionDir !== undefined &&
115
- sessionExists(record.sessionDir, record.sessionId);
116
- const restoredRecord = sessionValid ? record : { ...record, sessionId: undefined, sessionDir: undefined };
117
112
  const worktree = record.worktree && await isThreadSourceAvailable(record)
118
113
  ? await restoreWorktreeIsolation(record.worktree).catch(() => undefined)
119
114
  : undefined;
120
115
  const restorationFailed = record.isolation === "worktree" && record.worktree !== undefined && !worktree;
121
- const thread = createRestoredThread(runtime, restoredRecord, worktree, restorationFailed ? "failed" : "parked");
116
+ const thread = createRestoredThread(runtime, record, worktree, restorationFailed ? "failed" : "parked");
122
117
  runtime.threads.set(record.runId, thread);
123
118
  if (thread.sessionDir) runtime.sessionDirs.add(thread.sessionDir);
124
119
  if (restorationFailed) {
@@ -184,16 +179,17 @@ export async function restoreDurableThreads(runtime: SubagentRuntime, cwd: strin
184
179
  return restoredIds;
185
180
  }
186
181
 
187
- /** Session-start durable bootstrap: restore threads, age out expired records, and
188
- * sweep leaked temp/state directories. Every stage is best-effort so a broken
189
- * manifest never blocks the session.
190
- *
191
- * Restore is published on the runtime as `durableRestore` before this returns,
192
- * so callers that must see restored threads await that pass alone and never the
193
- * hygiene sweeps behind it. Hygiene still runs after restore: pruning decides
194
- * 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. */
195
186
  export function bootstrapDurableState(runtime: SubagentRuntime, cwd: string): Promise<void> {
196
187
  const restore = (async () => {
188
+ try {
189
+ await pruneThreadRecords(runtime.configPath);
190
+ } catch {
191
+ /* unreadable recovery references remain protected */
192
+ }
197
193
  try {
198
194
  runtime.restoredRunIds = await restoreDurableThreads(runtime, cwd);
199
195
  } catch {
@@ -203,11 +199,6 @@ export function bootstrapDurableState(runtime: SubagentRuntime, cwd: string): Pr
203
199
  runtime.durableRestore = restore;
204
200
  return (async () => {
205
201
  await restore;
206
- try {
207
- await pruneThreadRecords(runtime.configPath);
208
- } catch {
209
- /* retention is best-effort */
210
- }
211
202
  const projectRoots = getSubagentsRoot(runtime.configPath);
212
203
  try {
213
204
  sweepProjectTempDirs(projectRoots);