@ferris1225/pi-subagents 5.0.6 → 6.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +39 -0
- package/README.md +95 -67
- package/index.ts +1 -1
- package/package.json +1 -6
- package/src/configuration/role-migration.ts +2 -2
- package/src/configuration/setup.ts +4 -2
- package/src/configuration/ui.ts +144 -132
- package/src/delegation/dispatch.ts +1 -1
- package/src/delegation/prompt.ts +6 -5
- package/src/execution/spawn.ts +15 -5
- package/src/isolation/cleanup.ts +9 -5
- package/src/isolation/manifest-mutation.ts +73 -0
- package/src/isolation/recovery.ts +24 -16
- package/src/lifecycle/durable.ts +61 -25
- package/src/lifecycle/runtime.ts +9 -3
- package/src/lifecycle/stop.ts +2 -2
- package/src/lifecycle/thread-lifecycle.ts +4 -1
- package/src/lifecycle/thread-restore.ts +15 -5
- package/src/lifecycle/thread-shared.ts +15 -3
- package/src/presentation/monitor.ts +5 -3
- package/src/presentation/widget.ts +157 -113
- package/src/workflow/acceptance.ts +67 -0
- package/src/workflow/durable.ts +32 -12
- package/src/workflow/engine.ts +118 -30
- package/src/workflow/plan.ts +25 -4
- package/src/workflow/state.ts +6 -0
- package/src/workflow/templates.ts +156 -0
- package/src/workflow/tool.ts +23 -104
- package/skills/workflow/SKILL.md +0 -268
- package/src/workflow/files.ts +0 -236
- package/workflows/code-review.md +0 -38
- package/workflows/migration.md +0 -42
- package/workflows/research.md +0 -48
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/** Durable handoff for worktree integration/cleanup failures across sessions. */
|
|
2
2
|
|
|
3
|
-
import {
|
|
3
|
+
import { withManifestMutation } from "./manifest-mutation.ts";
|
|
4
4
|
import { existsSync } from "node:fs";
|
|
5
5
|
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
6
6
|
import { dirname, join } from "node:path";
|
|
@@ -13,6 +13,7 @@ const RECOVERY_MANIFEST_FILE_NAME = "pi-subagents-recovery.json";
|
|
|
13
13
|
const RECOVERY_MANIFEST_VERSION = 1;
|
|
14
14
|
|
|
15
15
|
export interface RecoveryRecord {
|
|
16
|
+
durableId?: string;
|
|
16
17
|
runId: number;
|
|
17
18
|
createdAt: number;
|
|
18
19
|
integrated: boolean;
|
|
@@ -38,6 +39,7 @@ function normalizeRecord(value: unknown): RecoveryRecord | undefined {
|
|
|
38
39
|
if (typeof raw.runId !== "number" || !Number.isInteger(raw.runId) || raw.runId < 1) return undefined;
|
|
39
40
|
if (typeof raw.createdAt !== "number" || !Number.isFinite(raw.createdAt)) return undefined;
|
|
40
41
|
return {
|
|
42
|
+
...(typeof raw.durableId === "string" && raw.durableId ? { durableId: raw.durableId } : {}),
|
|
41
43
|
runId: raw.runId,
|
|
42
44
|
createdAt: raw.createdAt,
|
|
43
45
|
integrated: raw.integrated === true,
|
|
@@ -86,7 +88,7 @@ export async function referencedRecoveryPaths(
|
|
|
86
88
|
|
|
87
89
|
export async function readRecoveryRecords(configPath: string): Promise<RecoveryRecord[]> {
|
|
88
90
|
const path = getRecoveryManifestPath(configPath);
|
|
89
|
-
return
|
|
91
|
+
return withManifestMutation(path, async () => {
|
|
90
92
|
const manifest = await readManifest(path);
|
|
91
93
|
const records = await validatedRecords(configPath, manifest.records);
|
|
92
94
|
if (!manifest.valid || records.length !== manifest.sourceCount) await writeManifest(path, records);
|
|
@@ -100,7 +102,7 @@ export async function relocateRecoveryManifest(configPath: string): Promise<void
|
|
|
100
102
|
const legacyPath = join(dirname(configPath), RECOVERY_MANIFEST_FILE_NAME);
|
|
101
103
|
const currentPath = getRecoveryManifestPath(configPath);
|
|
102
104
|
if (legacyPath === currentPath || !existsSync(legacyPath)) return;
|
|
103
|
-
await
|
|
105
|
+
await withManifestMutation(legacyPath, async () => {
|
|
104
106
|
const legacy = await readManifest(legacyPath);
|
|
105
107
|
if (!legacy.valid) {
|
|
106
108
|
await rm(legacyPath, { force: true });
|
|
@@ -112,7 +114,7 @@ export async function relocateRecoveryManifest(configPath: string): Promise<void
|
|
|
112
114
|
}
|
|
113
115
|
|
|
114
116
|
function recoveryKey(record: RecoveryRecord): string {
|
|
115
|
-
return `${record.runId}\0${record.worktreePath ?? ""}\0${record.patchPath ?? ""}\0${record.error ?? ""}`;
|
|
117
|
+
return `${record.durableId ?? record.runId}\0${record.worktreePath ?? ""}\0${record.patchPath ?? ""}\0${record.error ?? ""}`;
|
|
116
118
|
}
|
|
117
119
|
|
|
118
120
|
async function writeManifest(path: string, records: readonly RecoveryRecord[]): Promise<void> {
|
|
@@ -141,7 +143,7 @@ export async function persistRecoveryRecords(
|
|
|
141
143
|
): Promise<void> {
|
|
142
144
|
if (records.length === 0) return;
|
|
143
145
|
const path = getRecoveryManifestPath(configPath);
|
|
144
|
-
await
|
|
146
|
+
await withManifestMutation(path, async () => {
|
|
145
147
|
const merged = new Map<string, RecoveryRecord>();
|
|
146
148
|
const existing = await readManifest(path);
|
|
147
149
|
for (const record of await validatedRecords(configPath, existing.records)) {
|
|
@@ -158,8 +160,10 @@ export function recoveryRecordFromFinalization(
|
|
|
158
160
|
runId: number,
|
|
159
161
|
finalization: WorktreeFinalization,
|
|
160
162
|
now = Date.now(),
|
|
163
|
+
durableId?: string,
|
|
161
164
|
): RecoveryRecord {
|
|
162
165
|
return {
|
|
166
|
+
...(durableId ? { durableId } : {}),
|
|
163
167
|
runId,
|
|
164
168
|
createdAt: now,
|
|
165
169
|
integrated: finalization.integrated,
|
|
@@ -195,11 +199,11 @@ export async function announceRecoveryRecords(
|
|
|
195
199
|
if (ctx.hasUI === false) return;
|
|
196
200
|
const records = await readRecoveryRecords(configPath);
|
|
197
201
|
if (records.length === 0) return;
|
|
198
|
-
const local = new Set<
|
|
202
|
+
const local = new Set<string>();
|
|
199
203
|
for (const record of records) {
|
|
200
204
|
const groupDir = await managedRecoveryGroup(configPath, record);
|
|
201
205
|
if (!groupDir || !recoveryBelongsToSession(configPath, ctx.cwd, groupDir)) continue;
|
|
202
|
-
local.add(record);
|
|
206
|
+
local.add(recoveryKey(record));
|
|
203
207
|
if (!record.integrated || !record.worktreePath) continue;
|
|
204
208
|
if (!existsSync(record.worktreePath) && !(record.patchPath ? existsSync(record.patchPath) : false)) continue;
|
|
205
209
|
await removeWorktreeGroup({
|
|
@@ -207,16 +211,20 @@ export async function announceRecoveryRecords(
|
|
|
207
211
|
tempDir: groupDir,
|
|
208
212
|
});
|
|
209
213
|
}
|
|
210
|
-
const
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
|
|
214
|
+
const path = getRecoveryManifestPath(configPath);
|
|
215
|
+
const live = await withManifestMutation(path, async () => {
|
|
216
|
+
// Cleanup awaits Git/filesystem work outside the queue. Re-read here so
|
|
217
|
+
// failures persisted during those awaits survive this pruning pass.
|
|
218
|
+
const current = await readManifest(path);
|
|
219
|
+
const remaining = (await validatedRecords(configPath, current.records)).filter((record) =>
|
|
220
|
+
(record.worktreePath ? existsSync(record.worktreePath) : false) ||
|
|
221
|
+
(record.patchPath ? existsSync(record.patchPath) : false),
|
|
222
|
+
);
|
|
223
|
+
if (!current.valid || remaining.length !== current.sourceCount) await writeManifest(path, remaining);
|
|
224
|
+
return remaining;
|
|
225
|
+
});
|
|
218
226
|
for (const record of live) {
|
|
219
|
-
if (!local.has(record)) continue;
|
|
227
|
+
if (!local.has(recoveryKey(record))) continue;
|
|
220
228
|
const paths = [
|
|
221
229
|
record.worktreePath ? `worktree ${stripVTControlCharacters(record.worktreePath)}` : undefined,
|
|
222
230
|
record.patchPath ? `patch ${stripVTControlCharacters(record.patchPath)}` : undefined,
|
package/src/lifecycle/durable.ts
CHANGED
|
@@ -10,10 +10,11 @@
|
|
|
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
|
|
13
|
+
* through the same cross-process manifest lock as recovery records.
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
|
-
import {
|
|
16
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
17
|
+
import { withManifestMutation } from "../isolation/manifest-mutation.ts";
|
|
17
18
|
import { existsSync, type Dirent, readdirSync, statSync } from "node:fs";
|
|
18
19
|
import { mkdir, readFile, realpath, rename, rm, writeFile } from "node:fs/promises";
|
|
19
20
|
import { uptime } from "node:os";
|
|
@@ -71,6 +72,8 @@ export interface ThreadResultSummary {
|
|
|
71
72
|
}
|
|
72
73
|
|
|
73
74
|
export interface ThreadRecord {
|
|
75
|
+
/** Stable identity across windows and locally renumbered restores. Absent in legacy records. */
|
|
76
|
+
durableId?: string;
|
|
74
77
|
runId: number;
|
|
75
78
|
createdAt: number;
|
|
76
79
|
updatedAt: number;
|
|
@@ -180,6 +183,7 @@ function normalizeRecord(value: unknown): ThreadRecord | undefined {
|
|
|
180
183
|
return undefined;
|
|
181
184
|
}
|
|
182
185
|
return {
|
|
186
|
+
...(typeof raw.durableId === "string" && raw.durableId ? { durableId: raw.durableId } : {}),
|
|
183
187
|
runId: raw.runId,
|
|
184
188
|
createdAt: raw.createdAt,
|
|
185
189
|
updatedAt: raw.updatedAt,
|
|
@@ -262,25 +266,54 @@ async function validateThreadRecord(
|
|
|
262
266
|
}
|
|
263
267
|
const worktree = record.worktree;
|
|
264
268
|
if (!worktree || !await isManagedWorktreeLayout(configPath, record.cwd, worktree)) return false;
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
if (existsSync(worktree.cwd)) {
|
|
269
|
+
if (
|
|
270
|
+
!isAbsolute(worktree.originalCwd) || worktree.originalCwd !== resolve(worktree.originalCwd) ||
|
|
271
|
+
!isAbsolute(worktree.originalRoot) || worktree.originalRoot !== resolve(worktree.originalRoot) ||
|
|
272
|
+
!isPathInside(worktree.originalRoot, worktree.originalCwd)
|
|
273
|
+
) return false;
|
|
274
|
+
const restoredCwd = join(worktree.worktreePath, relative(worktree.originalRoot, worktree.originalCwd));
|
|
275
|
+
if (!samePath(worktree.cwd, restoredCwd) || !samePath(record.executionCwd, restoredCwd)) return false;
|
|
276
|
+
if (existsSync(worktree.cwd)) {
|
|
277
|
+
try {
|
|
275
278
|
const [realWorktree, realCwd] = await Promise.all([realpath(worktree.worktreePath), realpath(worktree.cwd)]);
|
|
276
|
-
if (!samePath(realCwd, join(realWorktree, relative(
|
|
279
|
+
if (!samePath(realCwd, join(realWorktree, relative(worktree.originalRoot, worktree.originalCwd)))) return false;
|
|
280
|
+
} catch {
|
|
281
|
+
return false;
|
|
277
282
|
}
|
|
283
|
+
}
|
|
284
|
+
// Managed recovery references survive a missing checkout or failed Git
|
|
285
|
+
// discovery. A successfully resolved source must still match the snapshot.
|
|
286
|
+
try {
|
|
287
|
+
if (!samePath(worktree.originalCwd, await realpath(record.cwd))) return false;
|
|
288
|
+
} catch {
|
|
278
289
|
return true;
|
|
290
|
+
}
|
|
291
|
+
try {
|
|
292
|
+
return samePath(worktree.originalRoot, await resolveRepositoryRoot(record.cwd));
|
|
293
|
+
} catch {
|
|
294
|
+
return true;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
export async function isThreadSourceAvailable(record: ThreadRecord): Promise<boolean> {
|
|
299
|
+
if (!record.worktree) return true;
|
|
300
|
+
try {
|
|
301
|
+
return samePath(await realpath(record.cwd), record.worktree.originalCwd) &&
|
|
302
|
+
samePath(await resolveRepositoryRoot(record.cwd), record.worktree.originalRoot);
|
|
279
303
|
} catch {
|
|
280
304
|
return false;
|
|
281
305
|
}
|
|
282
306
|
}
|
|
283
307
|
|
|
308
|
+
/** Legacy identities include immutable source/artifact metadata, so adopting a
|
|
309
|
+
* record does not let a fresh run with the same display id overwrite it. */
|
|
310
|
+
export function threadRecordIdentity(record: ThreadRecord): string {
|
|
311
|
+
return record.durableId ?? `legacy-${createHash("sha256").update(JSON.stringify([
|
|
312
|
+
record.cwd, record.runId, record.createdAt, record.ownerPid, record.bootId,
|
|
313
|
+
record.sessionDir, record.worktree?.tempDir,
|
|
314
|
+
])).digest("hex")}`;
|
|
315
|
+
}
|
|
316
|
+
|
|
284
317
|
async function validatedManifestRecords(
|
|
285
318
|
configPath: string,
|
|
286
319
|
path: string,
|
|
@@ -294,7 +327,7 @@ async function validatedManifestRecords(
|
|
|
294
327
|
function projectManifestPaths(durableRoot: string): string[] {
|
|
295
328
|
try {
|
|
296
329
|
return readdirSync(durableRoot, { withFileTypes: true })
|
|
297
|
-
.filter((entry) => entry.isDirectory() && !entry.isSymbolicLink())
|
|
330
|
+
.filter((entry) => entry.isDirectory() && !entry.isSymbolicLink() && !entry.name.endsWith(".lock"))
|
|
298
331
|
.map((entry) => join(durableRoot, entry.name, THREADS_MANIFEST_FILE_NAME));
|
|
299
332
|
} catch {
|
|
300
333
|
return [];
|
|
@@ -306,7 +339,7 @@ function projectManifestPaths(durableRoot: string): string[] {
|
|
|
306
339
|
export async function readThreadRecords(configPath: string): Promise<ThreadRecord[]> {
|
|
307
340
|
const manifests = await Promise.all(
|
|
308
341
|
projectManifestPaths(getSubagentsRoot(configPath))
|
|
309
|
-
.map((path) =>
|
|
342
|
+
.map((path) => withManifestMutation(path, async () => {
|
|
310
343
|
const manifest = await readManifest(path);
|
|
311
344
|
const validated = await validatedManifestRecords(configPath, path, manifest.records);
|
|
312
345
|
if (!manifest.valid || manifest.rolesMigrated || validated.length !== manifest.sourceCount) await writeManifest(path, validated);
|
|
@@ -337,23 +370,24 @@ async function writeManifest(path: string, records: readonly ThreadRecord[]): Pr
|
|
|
337
370
|
|
|
338
371
|
export async function upsertThreadRecord(configPath: string, record: ThreadRecord): Promise<void> {
|
|
339
372
|
const path = getThreadsManifestPath(configPath, record.cwd);
|
|
340
|
-
await
|
|
373
|
+
await withManifestMutation(path, async () => {
|
|
341
374
|
const records = await readManifestRecords(path);
|
|
342
|
-
const
|
|
375
|
+
const identity = threadRecordIdentity(record);
|
|
376
|
+
const index = records.findIndex((candidate) => threadRecordIdentity(candidate) === identity);
|
|
343
377
|
const merged: ThreadRecord = index === -1
|
|
344
|
-
? record
|
|
345
|
-
: { ...record, createdAt: records[index]!.createdAt };
|
|
378
|
+
? { ...record, durableId: identity }
|
|
379
|
+
: { ...record, durableId: identity, createdAt: records[index]!.createdAt };
|
|
346
380
|
if (index === -1) records.push(merged);
|
|
347
381
|
else records[index] = merged;
|
|
348
382
|
await writeManifest(path, records);
|
|
349
383
|
});
|
|
350
384
|
}
|
|
351
385
|
|
|
352
|
-
export async function removeThreadRecord(configPath: string,
|
|
386
|
+
export async function removeThreadRecord(configPath: string, identity: string, cwd: string): Promise<void> {
|
|
353
387
|
const path = getThreadsManifestPath(configPath, cwd);
|
|
354
|
-
await
|
|
388
|
+
await withManifestMutation(path, async () => {
|
|
355
389
|
const records = await readManifestRecords(path);
|
|
356
|
-
const next = records.filter((record) => record
|
|
390
|
+
const next = records.filter((record) => threadRecordIdentity(record) !== identity);
|
|
357
391
|
if (next.length === records.length) return;
|
|
358
392
|
await writeManifest(path, next);
|
|
359
393
|
});
|
|
@@ -389,7 +423,9 @@ export function threadRecordFromThread(
|
|
|
389
423
|
now = Date.now(),
|
|
390
424
|
): ThreadRecord {
|
|
391
425
|
const worktree = thread.worktree ? worktreeSnapshot(thread.worktree) : undefined;
|
|
426
|
+
thread.durableId ??= previous ? threadRecordIdentity(previous) : randomUUID();
|
|
392
427
|
return {
|
|
428
|
+
durableId: thread.durableId,
|
|
393
429
|
runId: thread.id,
|
|
394
430
|
createdAt: previous?.createdAt ?? now,
|
|
395
431
|
updatedAt: now,
|
|
@@ -447,7 +483,7 @@ export async function discardRecordArtifacts(record: ThreadRecord): Promise<void
|
|
|
447
483
|
if (record.sessionDir) {
|
|
448
484
|
await rm(record.sessionDir, { recursive: true, force: true }).catch(() => undefined);
|
|
449
485
|
}
|
|
450
|
-
if (record.worktree && (record.worktree.state === "active" || record.worktree.state === "retained")) {
|
|
486
|
+
if (record.worktree && (record.worktree.state === "active" || record.worktree.state === "retained") && await isThreadSourceAvailable(record)) {
|
|
451
487
|
const worktree = await restoreWorktreeIsolation(record.worktree).catch(() => undefined);
|
|
452
488
|
await worktree?.discard().catch(() => undefined);
|
|
453
489
|
}
|
|
@@ -461,7 +497,7 @@ export async function pruneThreadRecords(
|
|
|
461
497
|
): Promise<void> {
|
|
462
498
|
const durableRoot = getSubagentsRoot(configPath);
|
|
463
499
|
for (const path of projectManifestPaths(durableRoot)) {
|
|
464
|
-
await
|
|
500
|
+
await withManifestMutation(path, async () => {
|
|
465
501
|
const manifest = await readManifest(path);
|
|
466
502
|
const records = manifest.records;
|
|
467
503
|
if (manifest.valid && records.length === 0) return;
|
|
@@ -565,7 +601,7 @@ export async function pruneStaleProjectRoots(
|
|
|
565
601
|
}
|
|
566
602
|
const removed: string[] = [];
|
|
567
603
|
for (const project of projects) {
|
|
568
|
-
if (!project.isDirectory() || project.isSymbolicLink()) continue;
|
|
604
|
+
if (!project.isDirectory() || project.isSymbolicLink() || project.name.endsWith(".lock")) continue;
|
|
569
605
|
const projectDir = join(root, project.name);
|
|
570
606
|
if (containsReferencedPath(projectDir, referenced)) continue;
|
|
571
607
|
if (!isIdleSince(projectDir, now - PROJECT_ROOT_MAX_AGE_MS, now)) continue;
|
package/src/lifecycle/runtime.ts
CHANGED
|
@@ -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;
|
|
@@ -127,6 +129,8 @@ export interface SubagentRuntime {
|
|
|
127
129
|
mainWrites: Map<string, { toolName: string; scope: PhaseScope }>;
|
|
128
130
|
/** Workflow graphs started in this parent session, live and settled. */
|
|
129
131
|
workflows: Map<number, WorkflowRun>;
|
|
132
|
+
/** Stable mapping from persisted identities to this window's display ids. */
|
|
133
|
+
workflowRecordIds: Map<string, number>;
|
|
130
134
|
/** Allocate a graph id that no retained or live workflow record owns. */
|
|
131
135
|
reserveWorkflowId: () => number;
|
|
132
136
|
/** Raise the graph-id allocator above an id restored from a durable record. */
|
|
@@ -251,6 +255,7 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
251
255
|
threads: new Map<number, SubagentThread>(),
|
|
252
256
|
mainWrites: new Map(),
|
|
253
257
|
workflows: new Map<number, WorkflowRun>(),
|
|
258
|
+
workflowRecordIds: new Map(),
|
|
254
259
|
reserveWorkflowId: () => nextWorkflowId++,
|
|
255
260
|
ensureWorkflowIdAbove: (id) => {
|
|
256
261
|
if (id >= nextWorkflowId) nextWorkflowId = id + 1;
|
|
@@ -331,7 +336,7 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
331
336
|
// thread whose settlement finished during the wait above already
|
|
332
337
|
// wrote (or removed) its own record; the lastResult-derived state
|
|
333
338
|
// below matches it.
|
|
334
|
-
const settled: Array<{
|
|
339
|
+
const settled: Array<{ identity: string; cwd: string }> = [];
|
|
335
340
|
const records: ThreadRecord[] = [];
|
|
336
341
|
for (const thread of runtime.threads.values()) {
|
|
337
342
|
if (thread.retired) continue;
|
|
@@ -354,11 +359,11 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
354
359
|
state = "parked";
|
|
355
360
|
}
|
|
356
361
|
if (state === "parked") records.push(threadRecordFromThread(thread, state));
|
|
357
|
-
else settled.push({
|
|
362
|
+
else if (thread.durableId) settled.push({ identity: thread.durableId, cwd: thread.cwd });
|
|
358
363
|
}
|
|
359
364
|
await Promise.all([
|
|
360
365
|
...records.map((record) => upsertThreadRecord(runtime.configPath, record).catch(() => undefined)),
|
|
361
|
-
...settled.map(({
|
|
366
|
+
...settled.map(({ identity, cwd }) => removeThreadRecord(runtime.configPath, identity, cwd).catch(() => undefined)),
|
|
362
367
|
]);
|
|
363
368
|
// Retained-failure recovery records are persisted by the finalization
|
|
364
369
|
// itself; shutdown only drops sessions no record claims anymore.
|
|
@@ -394,6 +399,7 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
394
399
|
runtime.threads.clear();
|
|
395
400
|
runtime.mainWrites.clear();
|
|
396
401
|
runtime.workflows.clear();
|
|
402
|
+
runtime.workflowRecordIds.clear();
|
|
397
403
|
runtime.shutdownHooks = [];
|
|
398
404
|
monitor.clear();
|
|
399
405
|
},
|
package/src/lifecycle/stop.ts
CHANGED
|
@@ -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,
|
|
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";
|
|
@@ -187,6 +188,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
187
188
|
|
|
188
189
|
thread = {
|
|
189
190
|
id: runId,
|
|
191
|
+
durableId: randomUUID(),
|
|
190
192
|
generation,
|
|
191
193
|
agentName: agent.name,
|
|
192
194
|
task,
|
|
@@ -485,6 +487,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
485
487
|
/** Install the shared settlement hook for a fresh run or recovered worktree. */
|
|
486
488
|
export function installThreadLifecycle(thread: SubagentThread, deps: ThreadLifecycleDeps): void {
|
|
487
489
|
const { runtime } = deps;
|
|
490
|
+
thread.durableId ??= randomUUID();
|
|
488
491
|
const runId = thread.id;
|
|
489
492
|
|
|
490
493
|
thread.notifyIsolationFailure = (finalization) => {
|
|
@@ -556,7 +559,7 @@ export function installThreadLifecycle(thread: SubagentThread, deps: ThreadLifec
|
|
|
556
559
|
// Every retained finalization gets a durable recovery record, so the
|
|
557
560
|
// artifacts stay findable even when the owning process dies next.
|
|
558
561
|
void persistRecoveryRecords(runtime.configPath, [
|
|
559
|
-
recoveryRecordFromFinalization(runId, finalization),
|
|
562
|
+
recoveryRecordFromFinalization(runId, finalization, Date.now(), thread.durableId),
|
|
560
563
|
]).catch(() => undefined);
|
|
561
564
|
}
|
|
562
565
|
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";
|
|
@@ -37,7 +39,7 @@ import { installThreadLifecycle } from "./thread-lifecycle.ts";
|
|
|
37
39
|
async function discardRestoredRecord(runtime: SubagentRuntime, record: ThreadRecord): Promise<void> {
|
|
38
40
|
await discardRecordArtifacts(record);
|
|
39
41
|
if (record.sessionDir) runtime.sessionDirs.delete(record.sessionDir);
|
|
40
|
-
await removeThreadRecord(runtime.configPath, record
|
|
42
|
+
await removeThreadRecord(runtime.configPath, threadRecordIdentity(record), record.cwd).catch(() => undefined);
|
|
41
43
|
}
|
|
42
44
|
|
|
43
45
|
function createRestoredThread(
|
|
@@ -47,6 +49,7 @@ function createRestoredThread(
|
|
|
47
49
|
state: ThreadState,
|
|
48
50
|
): SubagentThread {
|
|
49
51
|
const thread: SubagentThread = {
|
|
52
|
+
durableId: threadRecordIdentity(record),
|
|
50
53
|
id: record.runId,
|
|
51
54
|
generation: record.generation,
|
|
52
55
|
agentName: record.agentName,
|
|
@@ -86,9 +89,11 @@ function belongsToSessionProject(configPath: string, cwd: string, record: Thread
|
|
|
86
89
|
export async function restoreDurableThreads(runtime: SubagentRuntime, cwd: string): Promise<number[]> {
|
|
87
90
|
const records = await readThreadRecords(runtime.configPath);
|
|
88
91
|
const restoredIds: number[] = [];
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
+
const localRecords = records.filter((record) => belongsToSessionProject(runtime.configPath, cwd, record));
|
|
93
|
+
for (const record of localRecords) monitor.ensureNextIdAbove(record.runId);
|
|
94
|
+
for (let record of localRecords) {
|
|
95
|
+
const identity = threadRecordIdentity(record);
|
|
96
|
+
if ([...runtime.threads.values()].some((thread) => thread.durableId === identity)) continue;
|
|
92
97
|
// Another Pi window may own this checkpoint, and PID reuse means a live
|
|
93
98
|
// recorded child is not proof of ownership. Never kill either on restore.
|
|
94
99
|
if (isCurrentBoot(record) && (
|
|
@@ -99,12 +104,17 @@ export async function restoreDurableThreads(runtime: SubagentRuntime, cwd: strin
|
|
|
99
104
|
await discardRestoredRecord(runtime, record);
|
|
100
105
|
continue;
|
|
101
106
|
}
|
|
107
|
+
if (runtime.threads.has(record.runId) || monitor.findRun(record.runId)) {
|
|
108
|
+
record = { ...record, durableId: identity, runId: monitor.reserveRunId() };
|
|
109
|
+
}
|
|
110
|
+
// Freeze a legacy identity before dropping missing session metadata.
|
|
111
|
+
record = { ...record, durableId: identity };
|
|
102
112
|
const sessionValid =
|
|
103
113
|
record.sessionId !== undefined &&
|
|
104
114
|
record.sessionDir !== undefined &&
|
|
105
115
|
sessionExists(record.sessionDir, record.sessionId);
|
|
106
116
|
const restoredRecord = sessionValid ? record : { ...record, sessionId: undefined, sessionDir: undefined };
|
|
107
|
-
const worktree = record.worktree
|
|
117
|
+
const worktree = record.worktree && await isThreadSourceAvailable(record)
|
|
108
118
|
? await restoreWorktreeIsolation(record.worktree).catch(() => undefined)
|
|
109
119
|
: undefined;
|
|
110
120
|
const restorationFailed = record.isolation === "worktree" && record.worktree !== undefined && !worktree;
|
|
@@ -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,
|
|
91
|
-
: removeThreadRecord(runtime.configPath,
|
|
102
|
+
? upsertThreadRecord(runtime.configPath, record)
|
|
103
|
+
: removeThreadRecord(runtime.configPath, threadRecordIdentity(record), thread.cwd);
|
|
92
104
|
void write.catch(() => undefined);
|
|
93
105
|
}
|
|
94
106
|
|
|
@@ -193,8 +193,9 @@ function tailGraphemes(segments: string[], maxWidth: number): string {
|
|
|
193
193
|
* Grapheme-safe — CJK, ZWJ emoji and combining sequences are never split.
|
|
194
194
|
*/
|
|
195
195
|
export function formatTaskSummary(task: string, maxWidth: number = TASK_SUMMARY_MAX, keysOnly = true): string {
|
|
196
|
+
if (maxWidth <= 0) return "";
|
|
196
197
|
const oneLine = stripVTControlCharacters(task).replace(/\s+/g, " ").trim();
|
|
197
|
-
if (
|
|
198
|
+
if (visibleWidth(oneLine) <= maxWidth) return oneLine;
|
|
198
199
|
|
|
199
200
|
const segments = [...graphemeSegmenter.segment(oneLine)].map((s) => s.segment);
|
|
200
201
|
const ellipsisWidth = visibleWidth(TASK_SUMMARY_ELLIPSIS);
|
|
@@ -248,9 +249,10 @@ const RUN_LABEL_MAX = 32;
|
|
|
248
249
|
* head slice of its prose. Grapheme-safe.
|
|
249
250
|
*/
|
|
250
251
|
export function runLabel(task: string): string {
|
|
251
|
-
const
|
|
252
|
+
const oneLine = stripVTControlCharacters(task).replace(/\s+/g, " ").trim();
|
|
253
|
+
const fragments = extractKeyFragments(oneLine);
|
|
252
254
|
const fragment = fragments.find((candidate) => /[\\/]|\.[A-Za-z0-9]{1,5}$/.test(candidate)) ?? fragments[0];
|
|
253
|
-
const src = fragment ??
|
|
255
|
+
const src = fragment ?? oneLine;
|
|
254
256
|
if (visibleWidth(src) <= RUN_LABEL_MAX) return src;
|
|
255
257
|
const chars = [...graphemeSegmenter.segment(src)].map((s) => s.segment);
|
|
256
258
|
// A path/symbol fragment keeps its tail (filename/symbol is recognisable);
|