pi-suite 0.3.7 → 0.3.8

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 (42) hide show
  1. package/package.json +1 -1
  2. package/src/agents/child.ts +9 -3
  3. package/src/agents/history.ts +3 -3
  4. package/src/agents/index.ts +22 -21
  5. package/src/agents/manager.ts +40 -12
  6. package/src/agents/records.ts +4 -2
  7. package/src/agents/runner.ts +12 -3
  8. package/src/agents/runtime.ts +1 -1
  9. package/src/agents/schedules/menu.ts +1 -1
  10. package/src/agents/types.ts +2 -1
  11. package/src/agents/ui/runs.ts +33 -13
  12. package/src/agents/viewer.ts +17 -11
  13. package/src/agents/workflow/index.ts +32 -9
  14. package/src/agents/workflow/manager.ts +18 -6
  15. package/src/agents/workflow/ui/menu.ts +2 -2
  16. package/src/jobs/index.ts +49 -36
  17. package/src/jobs/manager-record.ts +2 -2
  18. package/src/jobs/manager.ts +30 -12
  19. package/src/jobs/monitors/runtime.ts +41 -27
  20. package/src/jobs/store.ts +49 -10
  21. package/src/jobs/tools.ts +2 -2
  22. package/src/jobs/types.ts +2 -0
  23. package/src/jobs/viewer/metadata.ts +6 -0
  24. package/src/jobs/viewer.ts +30 -25
  25. package/src/runtime/branch.ts +14 -0
  26. package/src/runtime/cleanup/command.ts +116 -0
  27. package/src/runtime/cleanup/locations.ts +91 -0
  28. package/src/runtime/cleanup/occupancy.ts +117 -0
  29. package/src/runtime/cleanup/paths.ts +44 -0
  30. package/src/runtime/cleanup/quarantine.ts +162 -0
  31. package/src/runtime/cleanup/scan.ts +297 -0
  32. package/src/runtime/cleanup/session-use.ts +62 -0
  33. package/src/runtime/cleanup/sessions.ts +119 -0
  34. package/src/runtime/json-store.ts +6 -0
  35. package/src/runtime/owner.ts +1 -1
  36. package/src/runtime/settings/index.ts +9 -1
  37. package/src/runtime/suite.ts +43 -1
  38. package/src/tasks/store.ts +18 -1
  39. package/src/tasks/viewer.ts +14 -12
  40. package/src/ui/actions.ts +1 -1
  41. package/src/ui/browser.ts +95 -43
  42. package/src/ui/scroll.ts +5 -1
@@ -0,0 +1,162 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { lstat, mkdir, open, readdir, readFile, rename } from 'node:fs/promises';
3
+ import { basename, dirname, isAbsolute, join, relative, sep } from 'node:path';
4
+ import { Type, type Static } from 'typebox';
5
+ import { Value } from 'typebox/value';
6
+ import { maintenanceDir, SESSION_ID } from './locations.ts';
7
+ import { contains, inspect, matches, pathKey, type FileStamp } from './paths.ts';
8
+
9
+ export type Candidate = {owner: string; path: string; base: string; kind: string; stamp: FileStamp};
10
+ const batchId = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/;
11
+ const schema = Type.Object({version: Type.Literal(1), id: Type.String({pattern: batchId.source}), items: Type.Array(Type.Object({
12
+ owner: Type.String({pattern: SESSION_ID.source}), path: Type.String(), base: Type.String(), kind: Type.String(),
13
+ stamp: Type.Object({dev: Type.Number(), ino: Type.Number(), size: Type.Number(), mtimeMs: Type.Number(), birthtimeMs: Type.Number()}),
14
+ }))});
15
+ type Batch = Static<typeof schema>;
16
+ const logDir = (agentDir: string) => join(maintenanceDir(agentDir), 'batches');
17
+ const stash = (id: string, path: string) => join(dirname(path), '.pi-suite-quarantine', id, basename(path));
18
+
19
+ function validate(agentDir: string, value: unknown): Batch {
20
+ if (!Value.Check(schema, value)) throw new Error('Invalid cleanup batch manifest');
21
+ const paths = new Set<string>();
22
+ for (const item of value.items) {
23
+ const path = pathKey(item.path), base = pathKey(item.base), agent = pathKey(agentDir);
24
+ if (!isAbsolute(item.path) || !isAbsolute(item.base) || path === base || paths.has(path) || !contains(base, path)) {
25
+ throw new Error(`Invalid cleanup source path: ${item.path}`);
26
+ }
27
+ const local = relative(base, path).split(sep).join('/');
28
+ if (local.split('/').some(part => part.startsWith('.pi-suite-quarantine'))) throw new Error('Invalid nested cleanup batch');
29
+ const valid = item.kind === 'subagents' ? /^[^/]+\.jsonl$/.test(local)
30
+ : item.kind === 'tasks' ? /^\.pi\/tasks\/tasks-[\w-]+\.json$/.test(local)
31
+ : base === agent && (item.kind === 'jobs' ? /^pi-suite\/jobs\/[a-f0-9]{64}\/job_[a-f0-9]{8}$/.test(local)
32
+ : item.kind === 'workflows' ? /^pi-suite\/agents\/workflows\/[\w-]+\/wf_[a-f0-9]{12}$/.test(local)
33
+ : item.kind === 'goals' ? /^pi-suite\/goals\/session-[\w-]+\/state\.json$/.test(local)
34
+ : item.kind === 'schedules' && /^pi-suite\/agents\/schedules\/[\w-]+\.json$/.test(local));
35
+ if (!valid) throw new Error(`Invalid ${item.kind} cleanup path: ${item.path}`);
36
+ paths.add(path);
37
+ }
38
+ return value;
39
+ }
40
+ async function load(agentDir: string, id: string): Promise<Batch> {
41
+ if (!batchId.test(id)) throw new Error('Invalid cleanup batch ID');
42
+ const path = join(logDir(agentDir), `${id}.json`);
43
+ if (!(await inspect(agentDir, path))?.isFile()) throw new Error(`Unknown cleanup batch: ${id}`);
44
+ const batch = validate(agentDir, JSON.parse(await readFile(path, 'utf8')));
45
+ if (batch.id !== id) throw new Error(`Mismatched cleanup batch ID: ${id}`);
46
+ return batch;
47
+ }
48
+
49
+ async function* manifests(agentDir: string) {
50
+ const dir = logDir(agentDir);
51
+ if (!await inspect(agentDir, dir)) return;
52
+ for (const entry of (await readdir(dir)).sort()) {
53
+ const id = basename(entry, '.json');
54
+ if (batchId.test(id) && entry.endsWith('.json')) yield await load(agentDir, id);
55
+ }
56
+ }
57
+
58
+ export async function quarantine(agentDir: string, items: Candidate[], occupied: (owner: string) => boolean): Promise<{ids: string[]; moved: string[]; errors: string[]}> {
59
+ if (!items.length) return {ids: [], moved: [], errors: []};
60
+ const batch = validate(agentDir, {version: 1, id: randomUUID(), items});
61
+ const wanted = new Map(items.map(item => [pathKey(item.path), item]));
62
+ const reserved = new Map<Candidate, string>();
63
+ // A retry uses the original destination for the same item, so the previous manifest
64
+ // can still distinguish a successful retry from lost data.
65
+ for await (const previous of manifests(agentDir)) for (const saved of previous.items) {
66
+ const item = wanted.get(pathKey(saved.path));
67
+ if (item && item.owner === saved.owner && item.kind === saved.kind && pathKey(item.base) === pathKey(saved.base)
68
+ && matches(item.stamp, saved.stamp)) reserved.set(item, previous.id);
69
+ }
70
+ const destination = (item: Candidate) => stash(reserved.get(item) ?? batch.id, item.path);
71
+ const groups = new Map<string, Candidate[]>();
72
+ for (const item of items) {
73
+ const group = groups.get(item.owner) ?? []; group.push(item); groups.set(item.owner, group);
74
+ }
75
+ const errors: string[] = [], eligible: Candidate[][] = [];
76
+ for (const group of groups.values()) {
77
+ if (occupied(group[0]!.owner)) continue;
78
+ try {
79
+ for (const item of group) {
80
+ const dest = destination(item);
81
+ if (!matches(await inspect(item.base, item.path), item.stamp) || await inspect(item.base, dest)) {
82
+ throw new Error(`Cleanup source changed or destination is occupied: ${item.path}`);
83
+ }
84
+ }
85
+ eligible.push(group);
86
+ } catch (error) { errors.push(`${group[0]!.owner}: ${String(error)}`); }
87
+ }
88
+ const movable = eligible.filter(group => !occupied(group[0]!.owner));
89
+ batch.items = movable.flat().filter(item => !reserved.has(item));
90
+ if (batch.items.length) {
91
+ const dir = logDir(agentDir);
92
+ await inspect(agentDir, dir);
93
+ await mkdir(dir, {recursive: true, mode: 0o700});
94
+ const path = join(dir, `${batch.id}.json`), temp = join(dir, `${batch.id}.tmp`);
95
+ const journal = await open(temp, 'wx', 0o600);
96
+ // Publish the complete intent before moving anything. File location and identity record progress.
97
+ try { await journal.writeFile(JSON.stringify(batch)); await journal.sync(); } finally { await journal.close(); }
98
+ if (await inspect(agentDir, path)) throw new Error('Cleanup batch already exists');
99
+ await rename(temp, path);
100
+ }
101
+ const ids = new Set<string>();
102
+ const moved: string[] = [];
103
+ for (const group of movable) {
104
+ for (const item of group) {
105
+ if (occupied(item.owner)) break;
106
+ try {
107
+ const dest = destination(item);
108
+ await mkdir(dirname(dest), {recursive: true, mode: 0o700});
109
+ const parent = await inspect(item.base, dirname(dest));
110
+ if (!parent?.isDirectory() || parent.dev !== item.stamp.dev || await inspect(item.base, dest)
111
+ || !matches(await inspect(item.base, item.path), item.stamp)) throw new Error('Source or destination changed');
112
+ if (occupied(item.owner)) break;
113
+ await rename(item.path, dest);
114
+ moved.push(dest);
115
+ ids.add(reserved.get(item) ?? batch.id);
116
+ } catch (error) { errors.push(`${item.path}: ${String(error)}`); break; }
117
+ }
118
+ }
119
+ return {ids: [...ids], moved, errors};
120
+ }
121
+
122
+ /** Count logical file bytes, not allocated blocks. Never read contents or follow links. */
123
+ export async function quarantinedBytes(paths: readonly string[]): Promise<number> {
124
+ const pending = [...paths];
125
+ let bytes = 0;
126
+ for (let path = pending.pop(); path !== undefined; path = pending.pop()) {
127
+ const info = await lstat(path);
128
+ if (info.isFile()) bytes += info.size;
129
+ else if (info.isDirectory()) for (const name of await readdir(path)) pending.push(join(path, name));
130
+ }
131
+ return bytes;
132
+ }
133
+
134
+ export async function restore(agentDir: string, id: string, occupied: () => ReadonlySet<string>): Promise<{restored: number; errors: string[]}> {
135
+ const {items} = await load(agentDir, id);
136
+ let restored = 0;
137
+ const errors: string[] = [];
138
+ for (const item of items) {
139
+ if (occupied().has(item.owner)) continue;
140
+ const dest = stash(id, item.path);
141
+ try {
142
+ const source = await inspect(item.base, item.path), saved = await inspect(item.base, dest);
143
+ if (!saved && matches(source, item.stamp)) continue; // Never moved, or already restored.
144
+ if (source || !matches(saved, item.stamp)) throw new Error('Restore conflict or quarantined item missing/changed');
145
+ if (occupied().has(item.owner)) continue;
146
+ await rename(dest, item.path); restored++;
147
+ } catch (error) { errors.push(`${item.path}: ${String(error)}`); }
148
+ }
149
+ return {restored, errors};
150
+ }
151
+
152
+ export async function batches(agentDir: string): Promise<string[]> {
153
+ const result: string[] = [];
154
+ for await (const {id, items} of manifests(agentDir)) {
155
+ for (const item of items) {
156
+ if (!matches(await inspect(item.base, item.path), item.stamp) || await inspect(item.base, stash(id, item.path))) {
157
+ result.push(id); break;
158
+ }
159
+ }
160
+ }
161
+ return result.sort();
162
+ }
@@ -0,0 +1,297 @@
1
+ import { readFile, realpath } from 'node:fs/promises';
2
+ import { dirname, isAbsolute, join } from 'node:path';
3
+ import { decodeWorkflowEntry } from '../../agents/workflow/entry.ts';
4
+ import { active, recordWorkspace, type AgentRecord } from '../../agents/types.ts';
5
+ import { goalPath, GoalStore } from '../../goal/store.ts';
6
+ import { schedulePath, ScheduleStore } from '../../agents/schedules/store.ts';
7
+ import { JobStore } from '../../jobs/store.ts';
8
+ import { errnoCode, type JobSummary } from '../../jobs/types.ts';
9
+ import { taskPath } from '../../tasks/index.ts';
10
+ import { cleanupTaskSnapshot } from '../../tasks/store.ts';
11
+ import { contains, inspect, pathKey, referenceKey, stamp } from './paths.ts';
12
+ import { identifyDirectory, locations, SESSION_ID, verifyDirectory, type Home } from './locations.ts';
13
+ import { addId, agentReferences, entries, legacyOwnerPath, readSessions, references, workflowReferences, type References } from './sessions.ts';
14
+ import type { Candidate } from './quarantine.ts';
15
+
16
+ type Group = {id: string; home?: Home; blockers: Set<string>; items: Map<string, Candidate>};
17
+ type ReferenceSource = {path: string; refs: References};
18
+
19
+ type PlannedGroup = {home: Home; items: Candidate[]; sessionIds: Set<string>};
20
+ type SidecarKind = 'tasks' | 'goals' | 'schedules';
21
+ type RecordKind = SidecarKind | 'jobs' | 'workflows';
22
+ type ReferenceTargetKind = 'jobs' | 'subagents' | 'workflows';
23
+ const possibleReferences: Record<RecordKind, readonly ReferenceTargetKind[]> = {
24
+ tasks: ['jobs', 'subagents'], schedules: ['subagents'], goals: ['jobs', 'subagents', 'workflows'],
25
+ jobs: ['jobs', 'subagents', 'workflows'], workflows: ['jobs', 'subagents', 'workflows'],
26
+ };
27
+
28
+ export async function orphanCandidates(directory: string, extraRoot?: string, occupied: ReadonlySet<string> = new Set(),
29
+ liveReferences: readonly {owner: string; refs: References}[] = []): Promise<{groups: PlannedGroup[]; skipped: string[]; warnings: string[]}> {
30
+ const agentDir = await realpath(directory), registry = await locations(agentDir);
31
+ const sessions = await readSessions(agentDir, registry.sessions, registry.childRoots, extraRoot);
32
+ const registryByOwner = new Map(registry.sessions.map(home => [home.id, home]));
33
+ const groups = new Map<string, Group>(), byResource = new Map<string, Set<Group>>(), byPath = new Map<string, Group>();
34
+ const ownersBySession = new Map<string, Group>(), knownIds = new Set(sessions.map(item => item.header.id));
35
+ const sources: ReferenceSource[] = sessions.map(item => ({path: item.path, refs: item.refs}));
36
+ const workspaces = new Set(sessions.map(item => item.header.cwd));
37
+ const runs = new Map<string, AgentRecord>(), workflowOwners = new Map<string, string>();
38
+ const unavailableWorkspaces = new Set<string>();
39
+ const warnings: string[] = [], uncertainKinds = new Set<string>();
40
+
41
+ async function inWorkspace<T>(workspace: string, read: () => Promise<T>): Promise<T | undefined> {
42
+ const key = pathKey(workspace);
43
+ if (unavailableWorkspaces.has(key)) return;
44
+ try { return await read(); }
45
+ catch (error) {
46
+ if (errnoCode(error) !== 'ENOENT') throw error;
47
+ // A removed checkout is not a missing session root. Keep its groups, but don't abort other workspaces.
48
+ unavailableWorkspaces.add(key);
49
+ }
50
+ }
51
+
52
+ async function readSidecar<T>(base: string, file: string, kind: SidecarKind, target: Group | undefined, read: () => Promise<T | null>) {
53
+ try {
54
+ const info = await inspect(base, file);
55
+ if (!info) return;
56
+ if (!info.isFile()) throw new Error(`Not a regular ${kind} file`);
57
+ const data = await read();
58
+ if (data == null) return;
59
+ if (target) addItem(target, {base, path: file, kind, stamp: stamp(info)});
60
+ return data;
61
+ } catch (error) {
62
+ retainUnreadable(kind, file, error, target);
63
+ }
64
+ }
65
+ function retainUnreadable(kind: RecordKind, path: string, error: unknown, target?: Group) {
66
+ // Preserve the owner (if known) and any candidates that may rely on this record for ownership or references.
67
+ target?.blockers.add(`Unverified ${kind} file: ${path}`);
68
+ for (const kindToKeep of possibleReferences[kind]) uncertainKinds.add(kindToKeep);
69
+ warnings.push(`Skipped ${kind} file ${path}: ${error instanceof Error ? error.message : String(error)}`);
70
+ }
71
+
72
+ function group(id: string): Group {
73
+ if (!SESSION_ID.test(id)) throw new Error(`Invalid cleanup owner: ${id}`);
74
+ let result = groups.get(id);
75
+ if (!result) { result = {id, home: registryByOwner.get(id), blockers: new Set(), items: new Map()}; groups.set(id, result); }
76
+ return result;
77
+ }
78
+ function addResource(target: Group, id: string): void {
79
+ const owners = byResource.get(id) ?? new Set(); owners.add(target); byResource.set(id, owners);
80
+ }
81
+ function claim(target: Group, path: string): string {
82
+ const key = pathKey(path), old = byPath.get(key);
83
+ if (old && old !== target) {
84
+ const reason = `Conflicting owners of ${path}`; old.blockers.add(reason); target.blockers.add(reason);
85
+ }
86
+ byPath.set(key, target);
87
+ return key;
88
+ }
89
+ function addItem(target: Group, item: Omit<Candidate, 'owner'>): void {
90
+ target.items.set(claim(target, item.path), {...item, owner: target.id});
91
+ }
92
+ async function sidecar(target: Group, base: string, path: string, kind: string) {
93
+ const info = await inspect(base, path);
94
+ if (!info) return;
95
+ if (kind === 'workflows' ? !info.isDirectory() : !info.isFile()) throw new Error(`Invalid ${kind} resource: ${path}`);
96
+ const item = {base, path, kind, stamp: stamp(info)};
97
+ addItem(target, item);
98
+ return item;
99
+ }
100
+ function saveRun(run: AgentRecord) {
101
+ const old = runs.get(run.runId);
102
+ if (old && old.ownerSessionId !== run.ownerSessionId) throw new Error(`Conflicting owner for ${run.runId}`);
103
+ runs.set(run.runId, run);
104
+ if (!knownIds.has(run.ownerSessionId)) {
105
+ addResource(group(run.ownerSessionId), run.id); addResource(group(run.ownerSessionId), run.runId);
106
+ }
107
+ }
108
+
109
+ for (const home of registry.sessions) {
110
+ // Keep all recorded source paths for fork protection, not just the latest file location.
111
+ if (!knownIds.has(home.id)) claim(group(home.id), home.file);
112
+ await inWorkspace(home.workspace.path, () => verifyDirectory(home.workspace));
113
+ workspaces.add(home.workspace.path);
114
+ }
115
+ for (const item of sessions) {
116
+ for (const run of item.agents.values()) saveRun(run);
117
+ for (const workflow of item.workflows.values()) {
118
+ for (const run of workflow.children) saveRun(run);
119
+ if (!knownIds.has(workflow.ownerSessionId)) addResource(group(workflow.ownerSessionId), workflow.id);
120
+ }
121
+ if (!item.child) continue;
122
+ const self: AgentRecord[] = [];
123
+ for (const run of item.agents.values()) if (run.sessionFile && await referenceKey(run.sessionFile) === pathKey(item.path)) self.push(run);
124
+ const owners = new Set(self.map(run => run.ownerSessionId));
125
+ for (const id of owners) {
126
+ const target = group(id);
127
+ if (owners.size > 1 || registryByOwner.has(item.header.id)) {
128
+ target.blockers.add(`Shared child session: ${item.path}`); continue;
129
+ }
130
+ if (knownIds.has(id)) continue;
131
+ const oldChildOwner = ownersBySession.get(item.header.id);
132
+ if (oldChildOwner && oldChildOwner !== target) {
133
+ const reason = `Conflicting child session ID ${item.header.id}`;
134
+ oldChildOwner.blockers.add(reason); target.blockers.add(reason); continue;
135
+ }
136
+ ownersBySession.set(item.header.id, target);
137
+ if (self.some(run => active(run.state))) target.blockers.add(`Child has unfinished runs: ${item.path}`);
138
+ addItem(target, {kind: 'subagents', path: item.path, base: item.base, stamp: item.stamp});
139
+ // Legacy runs can prove an old default parent through an exact SDK filename and its header link.
140
+ const parent = legacyOwnerPath(item, id);
141
+ if (!target.home && parent && contains(join(agentDir, 'sessions'), parent) && isAbsolute(recordWorkspace(self[0]!))) {
142
+ const root = await identifyDirectory(dirname(parent));
143
+ const cwd = recordWorkspace(self[0]!);
144
+ const workspace = await inWorkspace(cwd, () => identifyDirectory(cwd));
145
+ if (workspace) {
146
+ target.home = {id, file: parent, root, workspace}; claim(target, parent); workspaces.add(workspace.path);
147
+ }
148
+ }
149
+ }
150
+ }
151
+
152
+ const workflowBase = join(agentDir, 'pi-suite', 'agents', 'workflows');
153
+ for (const owner of await entries(agentDir, workflowBase)) {
154
+ if (!SESSION_ID.test(owner.name)) continue;
155
+ const path = join(workflowBase, owner.name);
156
+ for (const run of await entries(agentDir, path)) {
157
+ if (!/^wf_[a-f0-9]{12}$/.test(run.name)) continue;
158
+ const folder = join(path, run.name), file = join(folder, 'run.json');
159
+ let data;
160
+ const refs = references();
161
+ try {
162
+ if (!(await inspect(agentDir, file))?.isFile()) throw new Error('Missing or invalid workflow record');
163
+ data = decodeWorkflowEntry(JSON.parse(await readFile(file, 'utf8')));
164
+ if (data.id !== run.name || data.ownerSessionId !== owner.name || pathKey(data.recordPath) !== pathKey(file)) {
165
+ throw new Error('Mismatched workflow ownership');
166
+ }
167
+ workflowReferences(refs, data);
168
+ } catch (error) {
169
+ retainUnreadable('workflows', file, error, knownIds.has(owner.name) ? undefined : group(owner.name));
170
+ continue;
171
+ }
172
+ if (workflowOwners.has(data.id)) throw new Error(`Duplicate workflow ID: ${data.id}`);
173
+ workflowOwners.set(data.id, owner.name);
174
+ sources.push({path: folder, refs});
175
+ for (const child of data.children) saveRun(child);
176
+ if (!knownIds.has(owner.name)) {
177
+ const target = group(owner.name);
178
+ if (data.status === 'running' || data.status === 'paused') target.blockers.add(`Workflow is not settled: ${data.id}`);
179
+ await sidecar(target, agentDir, folder, 'workflows'); addResource(target, data.id);
180
+ }
181
+ }
182
+ }
183
+
184
+ const jobs = new JobStore(agentDir);
185
+ const jobRecords: JobSummary[] = [];
186
+ const seenJobs = new Set<string>();
187
+ for await (const job of jobs.maintenanceHistory((path, error) => retainUnreadable('jobs', path, error))) {
188
+ if (seenJobs.has(job.id)) throw new Error(`Duplicate job ID: ${job.id}`);
189
+ seenJobs.add(job.id); jobRecords.push(job);
190
+ }
191
+ for (const job of jobRecords) {
192
+ const owner = ownersBySession.get(job.ownerSessionId);
193
+ const creatorRun = job.creator && runs.get(job.creator.runId);
194
+ const creator = job.creator?.workflowId ? workflowOwners.get(job.creator.workflowId)
195
+ : creatorRun && creatorRun.id === job.creator?.agentId ? creatorRun.ownerSessionId : undefined;
196
+ const target = owner ?? (!knownIds.has(job.ownerSessionId) ? group(job.ownerSessionId) : undefined);
197
+ const path = jobs.directory(job);
198
+ if (job.creator) {
199
+ const refs = references(); addId(refs, job.creator.runId); sources.push({path, refs});
200
+ }
201
+ if (!target) continue;
202
+ if (job.creator && creator !== target.id) target.blockers.add(`Unverified job creator: ${job.id}`);
203
+ try { jobs.assertRemovable(job); }
204
+ catch (error) { target.blockers.add(`${job.id}: ${String(error)}`); }
205
+ addItem(target, {kind: 'jobs', base: agentDir, path, stamp: stamp((await inspect(agentDir, path))!)});
206
+ addResource(target, job.id);
207
+ }
208
+
209
+ const actor = (owner: string): Group | undefined => ownersBySession.get(owner) ?? (!knownIds.has(owner) ? group(owner) : undefined);
210
+ const sessionCwds = new Map(sessions.map(session => [session.header.id, session.header.cwd]));
211
+ for (const workspace of workspaces) {
212
+ const listing = await inWorkspace(workspace, async () => {
213
+ const base = await realpath(workspace);
214
+ return {base, items: await entries(base, join(base, '.pi', 'tasks'))};
215
+ });
216
+ if (!listing) continue;
217
+ const {base, items} = listing;
218
+ for (const item of items) {
219
+ const id = /^tasks-(.+)\.json$/.exec(item.name)?.[1];
220
+ if (!id || !SESSION_ID.test(id)) continue;
221
+ const file = taskPath(base, id), target = actor(id);
222
+ const data = await readSidecar(base, file, 'tasks', target, () => cleanupTaskSnapshot(file));
223
+ if (!data) continue;
224
+ const refs = references();
225
+ for (const task of data.tasks) {
226
+ addId(refs, task.owner);
227
+ for (const job of task.jobIds) addId(refs, job);
228
+ }
229
+ sources.push({path: file, refs});
230
+ if (target) {
231
+ const cwd = target.id === id ? target.home?.workspace.path : sessionCwds.get(id);
232
+ const canonical = cwd && await inWorkspace(cwd, () => realpath(cwd));
233
+ if (!canonical || pathKey(canonical) !== pathKey(base)) target.blockers.add(`Unverified task workspace: ${file}`);
234
+ }
235
+ }
236
+ }
237
+ const goals = join(agentDir, 'pi-suite', 'goals');
238
+ for (const item of await entries(agentDir, goals)) {
239
+ if (!item.name.startsWith('session-')) continue;
240
+ const id = item.name.slice('session-'.length);
241
+ if (!SESSION_ID.test(id)) continue;
242
+ const file = goalPath(agentDir, id);
243
+ const data = await readSidecar(agentDir, file, 'goals', actor(id), () => new GoalStore(file, id).snapshot());
244
+ if (!data) continue;
245
+ const refs = references();
246
+ for (const entry of [...data.goal?.waitFor ?? [], ...data.goal?.reason?.wait?.waitFor ?? []]) addId(refs, entry);
247
+ sources.push({path: file, refs});
248
+ }
249
+ const schedules = join(agentDir, 'pi-suite', 'agents', 'schedules');
250
+ for (const item of await entries(agentDir, schedules)) {
251
+ const id = /^(.+)\.json$/.exec(item.name)?.[1]; if (!id || !SESSION_ID.test(id)) continue;
252
+ const file = schedulePath(agentDir, id);
253
+ const data = await readSidecar(agentDir, file, 'schedules', actor(id), () => new ScheduleStore(file).snapshot());
254
+ if (!data) continue;
255
+ const refs = references();
256
+ for (const entry of data.jobs) { addId(refs, entry.lastAgentId); addId(refs, entry.lastRunId); }
257
+ sources.push({path: file, refs});
258
+ }
259
+
260
+ const normalized = new Map<string, string>(), liveProtected = new Set<Group>();
261
+ async function protectReferences(refs: References, protect: (group?: Group) => void) {
262
+ for (const ref of refs.paths) {
263
+ let key = normalized.get(ref);
264
+ if (!key) { key = await referenceKey(ref); normalized.set(ref, key); }
265
+ protect(byPath.get(key) ?? byPath.get(pathKey(dirname(key))));
266
+ }
267
+ for (const ref of refs.ids) for (const target of byResource.get(ref) ?? []) protect(target);
268
+ }
269
+ for (const {owner, refs} of liveReferences) await protectReferences(refs, target => {
270
+ if (target && target.id !== owner) liveProtected.add(target);
271
+ });
272
+ for (const {path, refs} of sources) await protectReferences(refs, target => {
273
+ if (target && byPath.get(pathKey(path)) !== target) target.blockers.add(`Referenced by ${path}`);
274
+ });
275
+ const sessionIds = new Map<Group, Set<string>>();
276
+ for (const [id, target] of ownersBySession) {
277
+ let ids = sessionIds.get(target);
278
+ if (!ids) sessionIds.set(target, ids = new Set([target.id]));
279
+ ids.add(id);
280
+ }
281
+ const eligible: PlannedGroup[] = [], skipped: string[] = [];
282
+ for (const target of groups.values()) {
283
+ const ids = sessionIds.get(target) ?? new Set([target.id]);
284
+ if (!target.items.size || liveProtected.has(target) || knownIds.has(target.id) || [...ids].some(id => occupied.has(id))) continue;
285
+ if ([...target.items.values()].some(item => uncertainKinds.has(item.kind))) continue;
286
+ if (target.home && unavailableWorkspaces.has(pathKey(target.home.workspace.path))) continue;
287
+ if ([...ids].some(id => {
288
+ const cwd = sessionCwds.get(id);
289
+ return cwd && unavailableWorkspaces.has(pathKey(cwd));
290
+ })) continue;
291
+ if (!target.home) { target.blockers.add('No verified location for the missing main session'); }
292
+ else if (await inspect(target.home.root.path, target.home.file)) target.blockers.add(`Owner path still exists: ${target.home.file}`);
293
+ if (target.blockers.size || !target.home) skipped.push(`${target.id}: ${[...target.blockers].join('; ')}`);
294
+ else eligible.push({home: target.home, items: [...target.items.values()], sessionIds: ids});
295
+ }
296
+ return {groups: eligible, skipped, warnings};
297
+ }
@@ -0,0 +1,62 @@
1
+ import { realpath } from 'node:fs/promises';
2
+ import { resolve } from 'node:path';
3
+ import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
4
+ import { assertSessionAvailable, coordinated, SessionUse } from './occupancy.ts';
5
+ import { addPath, assistantReferences, collectReferences, references } from './sessions.ts';
6
+
7
+ const globalKey = Symbol.for('pi-suite.cleanup.handoffs');
8
+ const handoffs = ((globalThis as Record<symbol, unknown>)[globalKey] ??= new Map()) as Map<string, (() => Promise<void>)[]>;
9
+ const handoffKey = (root: string, target: string) => JSON.stringify([root, target]);
10
+ export function handoffSessionUse(use: SessionUse, target: string | undefined, retire: () => Promise<void>): void {
11
+ if (!target) { void retire().catch(report); return; }
12
+ const key = handoffKey(use.root, target), callbacks = handoffs.get(key) ?? [];
13
+ callbacks.push(retire); handoffs.set(key, callbacks);
14
+ }
15
+ const report = (error: unknown) => process.emitWarning(`Cannot release cleanup occupancy: ${String(error)}`);
16
+
17
+ /** Register before binding Suite sidecars. Native Pi may have already read the JSONL. */
18
+ export async function registerSessionUse(root: string, ctx: ExtensionContext, owner?: string): Promise<SessionUse | undefined> {
19
+ root = await realpath(resolve(root));
20
+ if (!await coordinated(root)) return;
21
+ const session = ctx.sessionManager, path = session.getSessionFile(), entries = session.getEntries();
22
+ const sessionId = session.getSessionId(), reloadKey = handoffKey(root, sessionId);
23
+ const use = await SessionUse.register(root, owner ?? sessionId, async refs => {
24
+ if (path && !handoffs.has(reloadKey)) await assertSessionAvailable(path, entries.some(entry => entry.type === 'message'
25
+ && (entry.message.role === 'assistant' || entry.message.role === 'user')));
26
+ addPath(refs, session.getHeader()?.parentSession);
27
+ for (const entry of entries) collectReferences(refs, entry, path ?? 'in-memory session');
28
+ });
29
+ for (const key of [reloadKey, ...path ? [handoffKey(root, path)] : []]) {
30
+ const callbacks = handoffs.get(key);
31
+ if (!callbacks) continue;
32
+ handoffs.delete(key);
33
+ for (const retire of callbacks) void retire().catch(report);
34
+ }
35
+ return use;
36
+ }
37
+
38
+ export function publishSessionReferences(pi: ExtensionAPI, current: () => SessionUse | undefined): void {
39
+ pi.on('message_end', async (event, ctx) => {
40
+ const use = current();
41
+ if (!use || event.message.role !== 'assistant') return;
42
+ const refs = references(); assistantReferences(refs, event.message);
43
+ try { await use.add(refs); }
44
+ catch (error) {
45
+ // Pi reports hook errors but still persists the message. Remove unregistered tool
46
+ // calls on a failed publication, so they cannot create a reference after isolation.
47
+ ctx.ui.notify(`Cannot register session references: ${String(error)}`, 'error');
48
+ return {message: {...event.message, content: event.message.content.filter(block => block.type !== 'toolCall')}};
49
+ }
50
+ });
51
+ }
52
+
53
+ /** Detached owners keep their last binding lease until their lifecycle and final writes settle. */
54
+ export async function retireSessionUse(use: SessionUse, busy: () => boolean, subscribe: (listener: () => void) => (() => void)[]): Promise<void> {
55
+ if (!busy()) { await use.release(); return; }
56
+ const check = () => {
57
+ if (busy()) return;
58
+ for (const stop of subscriptions) stop();
59
+ void use.release().catch(report);
60
+ };
61
+ const subscriptions = subscribe(check);
62
+ }
@@ -0,0 +1,119 @@
1
+ import { createReadStream, type Dirent } from 'node:fs';
2
+ import { readdir, realpath } from 'node:fs/promises';
3
+ import { basename, dirname, isAbsolute, join } from 'node:path';
4
+ import { createInterface } from 'node:readline';
5
+ import { CURRENT_SESSION_VERSION, parseSessionEntries, type SessionEntry, type SessionHeader } from '@earendil-works/pi-coding-agent';
6
+ import { AGENT_ENTRY, decodeAgentRecord } from '../../agents/records.ts';
7
+ import type { AgentRecord } from '../../agents/types.ts';
8
+ import { WORKFLOW_ENTRY_TYPE, decodeWorkflowEntry, type WorkflowEntryData } from '../../agents/workflow/entry.ts';
9
+ import { SESSION_ID, verifyDirectory, type Directory, type Home } from './locations.ts';
10
+ import { inspect, matches, pathKey, stamp, type FileStamp } from './paths.ts';
11
+
12
+ export type References = {paths: Set<string>; ids: Set<string>};
13
+ export const references = (): References => ({paths: new Set(), ids: new Set()});
14
+ export const addId = (refs: References, id: unknown) => {
15
+ if (typeof id === 'string' && /^(?:(?:job|agent|run)_[a-f0-9]{8}|wf_[a-f0-9]{12})$/.test(id)) refs.ids.add(id);
16
+ };
17
+ export function addPath(refs: References, path: string | undefined): void {
18
+ if (!path) return;
19
+ if (!isAbsolute(path)) throw new Error(`Non-absolute history reference: ${path}`);
20
+ refs.paths.add(pathKey(path));
21
+ }
22
+ export function agentReferences(refs: References, record: AgentRecord): void {
23
+ addPath(refs, record.sessionFile); addId(refs, record.parentRunId);
24
+ }
25
+ export function workflowReferences(refs: References, record: WorkflowEntryData): void {
26
+ addPath(refs, record.recordPath); addId(refs, record.resumedFrom);
27
+ for (const child of record.children) agentReferences(refs, child);
28
+ }
29
+
30
+ export async function entries(base: string, path: string): Promise<Dirent[]> {
31
+ const info = await inspect(base, path);
32
+ if (!info) return [];
33
+ if (!info.isDirectory()) throw new Error(`Expected a directory: ${path}`);
34
+ return readdir(path, {withFileTypes: true});
35
+ }
36
+ export type SavedSession = {path: string; base: string; header: SessionHeader; agents: Map<string, AgentRecord>;
37
+ workflows: Map<string, WorkflowEntryData>; refs: References; stamp: FileStamp; child: boolean};
38
+
39
+ const idTools = new Set(['job_get', 'job_read', 'job_stop', 'job_write', 'agent_get', 'agent_read', 'agent_send', 'agent_stop']);
40
+ export function collectReferences(refs: References, entry: SessionEntry, path: string): void {
41
+ if (entry.type === 'custom' && entry.customType === AGENT_ENTRY) agentReferences(refs, decodeAgentRecord(entry.data, path));
42
+ else if (entry.type === 'custom' && entry.customType === WORKFLOW_ENTRY_TYPE) workflowReferences(refs, decodeWorkflowEntry(entry.data));
43
+ else if (entry.type === 'message' && entry.message.role === 'assistant') assistantReferences(refs, entry.message);
44
+ }
45
+ export function assistantReferences(refs: References, message: Extract<Extract<SessionEntry, {type: 'message'}>['message'], {role: 'assistant'}>): void {
46
+ for (const item of message.content) if (item.type === 'toolCall' && item.arguments) {
47
+ const args = item.arguments;
48
+ if (idTools.has(item.name)) { addId(refs, args.id); addId(refs, args.runId); }
49
+ if (item.name === 'agent_workflow') addId(refs, args.resumeFromRunId);
50
+ const ids = item.name === 'wait' ? args.ids : item.name === 'goal_wait' ? args.waitFor : undefined;
51
+ if (Array.isArray(ids)) for (const id of ids) addId(refs, id);
52
+ }
53
+ }
54
+ async function session(base: string, path: string, child: boolean): Promise<SavedSession> {
55
+ const info = await inspect(base, path);
56
+ if (!info?.isFile()) throw new Error(`Not a regular session file: ${path}`);
57
+ const before = stamp(info), refs = references();
58
+ let header: SessionHeader | undefined;
59
+ const agents = new Map<string, AgentRecord>(), workflows = new Map<string, WorkflowEntryData>();
60
+ const input = createReadStream(path, {encoding: 'utf8'});
61
+ try {
62
+ for await (const line of createInterface({input, crlfDelay: Infinity})) {
63
+ if (!line.trim()) continue;
64
+ const entry = parseSessionEntries(line)[0];
65
+ if (!entry || typeof entry.type !== 'string') throw new Error(`Malformed JSONL: ${path}`);
66
+ if (!header) {
67
+ if (entry.type !== 'session' || typeof entry.id !== 'string' || !SESSION_ID.test(entry.id) || typeof entry.cwd !== 'string'
68
+ || !isAbsolute(entry.cwd) || entry.version !== undefined && (!Number.isInteger(entry.version) || entry.version < 1 || entry.version > CURRENT_SESSION_VERSION)
69
+ || entry.parentSession !== undefined && typeof entry.parentSession !== 'string') throw new Error(`Invalid session header: ${path}`);
70
+ header = entry;
71
+ addPath(refs, header.parentSession);
72
+ } else if (entry.type === 'custom' && entry.customType === AGENT_ENTRY) {
73
+ const record = decodeAgentRecord(entry.data, path);
74
+ agentReferences(refs, record); agents.set(record.runId, record);
75
+ } else if (entry.type === 'custom' && entry.customType === WORKFLOW_ENTRY_TYPE) {
76
+ const record = decodeWorkflowEntry(entry.data);
77
+ workflowReferences(refs, record); workflows.set(record.id, record);
78
+ } else if (entry.type === 'message' && entry.message.role === 'assistant') assistantReferences(refs, entry.message);
79
+ }
80
+ } finally { input.destroy(); }
81
+ if (!header || !matches(await inspect(base, path), before)) throw new Error(`Empty or changed session file: ${path}`);
82
+ return {base, path, header, agents, workflows, refs, child, stamp: before};
83
+ }
84
+
85
+ export async function readSessions(agentDir: string, homes: Home[], childRoots: Directory[], extraRoot?: string): Promise<SavedSession[]> {
86
+ const defaults = join(agentDir, 'sessions'), roots = new Map<string, {path: string; child: boolean}>();
87
+ const add = (path: string, child: boolean) => {
88
+ const key = pathKey(path), existing = roots.get(key);
89
+ roots.set(key, {path, child: child || existing?.child === true});
90
+ };
91
+ const locations = [...homes.map(home => home.root), ...childRoots];
92
+ for (const dir of locations) await verifyDirectory(dir);
93
+ for (const item of await entries(agentDir, defaults)) {
94
+ if (!item.isDirectory() && !item.isSymbolicLink() || item.name.startsWith('.')) continue;
95
+ // Pi follows workspace-level aliases. Scan their canonical target once, never move through the alias.
96
+ add(await realpath(join(defaults, item.name)), false);
97
+ }
98
+ for (const home of homes) add(home.root.path, false);
99
+ if (extraRoot) add(await realpath(extraRoot), false);
100
+ for (const item of [...roots.values()]) {
101
+ const child = join(item.path, 'subagents');
102
+ if (await inspect(item.path, child)) add(child, true);
103
+ }
104
+ for (const location of childRoots) add(location.path, true);
105
+ const result: SavedSession[] = [];
106
+ for (const {path, child} of roots.values()) {
107
+ for (const entry of await entries(path, path)) if (entry.name.endsWith('.jsonl')) {
108
+ result.push(await session(path, join(path, entry.name), child));
109
+ }
110
+ }
111
+ return result;
112
+ }
113
+
114
+ /** A legacy child header supplies provenance only for Pi's standard, inspectable layout. */
115
+ export function legacyOwnerPath(child: SavedSession, owner: string): string | undefined {
116
+ const parent = child.header.parentSession;
117
+ if (child.child && parent && basename(child.base) === 'subagents' && pathKey(dirname(child.base)) === pathKey(dirname(parent))
118
+ && basename(parent).endsWith(`_${owner}.jsonl`)) return parent;
119
+ }
@@ -44,6 +44,12 @@ async function unlock(path: string, token: string): Promise<void> {
44
44
  catch (error) { if (code(error) !== 'ENOENT') throw error; }
45
45
  }
46
46
 
47
+ /** Serialize maintenance with other maintenance processes without taking any store's data lock. */
48
+ export async function withJsonFileLock<T>(path: string, prefix: string, action: () => Promise<T>): Promise<T> {
49
+ const token = await lock(path, prefix);
50
+ try { return await action(); } finally { await unlock(path, token); }
51
+ }
52
+
47
53
  export class JsonStore<Data> {
48
54
  protected data: Data;
49
55
  private queue = Promise.resolve();