pi-suite 0.3.6 → 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 (43) 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 +34 -14
  12. package/src/agents/viewer.ts +69 -43
  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
  43. package/src/ui/ticker.ts +2 -2
@@ -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();
@@ -7,7 +7,7 @@
7
7
  * stays observable but is marked stale so callers refuse new executions until it is idle.
8
8
  */
9
9
  export interface ExecutionOwner { readonly closed: boolean; busy(): boolean; shutdown(): Promise<void> }
10
- type ExistingOwner = Pick<ExecutionOwner, 'closed' | 'shutdown'> & Partial<Pick<ExecutionOwner, 'busy'>>;
10
+ type ExistingOwner = Pick<ExecutionOwner, 'closed' | 'shutdown'> & Partial<Pick<ExecutionOwner, 'busy'>> & {cleanupOwners?(): Iterable<string>};
11
11
  type Slot<T> = { implementation?: symbol; owner: T };
12
12
  export type OwnerHandle<T> = { owner: T; stale?: string };
13
13
 
@@ -14,7 +14,15 @@ export function registerSuiteCommand(pi: ExtensionAPI, dock: Dock, notices: Noti
14
14
  // Types can refresh saved config without re-registering modules or commands.
15
15
  const active = config();
16
16
  if (active.commands.exit) pi.registerCommand('exit', { description: 'Quit Pi', handler: async (_args, ctx) => quit(ctx) });
17
- pi.registerCommand('suite', { description: 'Configure Pi Suite settings', handler: async (_args, ctx) => {
17
+ pi.registerCommand('suite', { description: 'Configure Pi Suite or maintain orphaned session data', handler: async (args, ctx) => {
18
+ const cleanup = /^cleanup(?:\s+|$)(.*)$/s.exec(args.trim());
19
+ if (cleanup) {
20
+ const release = notices.hold();
21
+ try { const { cleanupCommand } = await import('../cleanup/command.ts'); await cleanupCommand(cleanup[1]!, ctx); }
22
+ catch (error) { ctx.ui.notify(error instanceof Error ? error.message : String(error), 'error'); }
23
+ finally { release(); }
24
+ return;
25
+ }
18
26
  const release = notices.hold();
19
27
  try {
20
28
  const { showSuiteSettings } = await import('./view.ts');
@@ -1,4 +1,5 @@
1
1
  import { getAgentDir, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
2
+ import { globals as jobGlobals, key as jobKey } from '../jobs/registry.ts';
2
3
  import { loadConfig } from './config.ts';
3
4
  import { SessionBinding } from './binding.ts';
4
5
  import { Notifications } from './notifications.ts';
@@ -12,6 +13,8 @@ import { registerSuiteCommand } from './settings/index.ts';
12
13
  import { prepareClipboard } from './clipboard.ts';
13
14
  import { CompletionNotifier, type FocusInput } from '../notify/index.ts';
14
15
  import type { SubagentsDeps } from '../agents/commands.ts';
16
+ import { handoffSessionUse, publishSessionReferences, registerSessionUse, retireSessionUse } from './cleanup/session-use.ts';
17
+ import type { SessionUse } from './cleanup/occupancy.ts';
15
18
 
16
19
  export async function createSuite(pi: ExtensionAPI, initial: ExtensionContext, focusInput?: FocusInput) {
17
20
  let config = loadConfig(initial.cwd);
@@ -131,6 +134,24 @@ export async function createSuite(pi: ExtensionAPI, initial: ExtensionContext, f
131
134
  });
132
135
 
133
136
  let firstBinding = true;
137
+ let use: SessionUse | undefined;
138
+ publishSessionReferences(pi, () => use);
139
+ let observedFile: string | undefined;
140
+ let locationWarning = false;
141
+ // Pi assigns a path at session creation but first writes it with conversation data.
142
+ // Remember established storage once per binding, never on token/output updates.
143
+ const rememberLocation = async (ctx: ExtensionContext) => {
144
+ const session = ctx.sessionManager, file = session.getSessionFile();
145
+ if (!file || file === observedFile || locationWarning) return;
146
+ try {
147
+ const { rememberSession } = await import('./cleanup/locations.ts');
148
+ if (await rememberSession(getAgentDir(), session)) observedFile = file;
149
+ } catch (error) {
150
+ locationWarning = true;
151
+ ctx.ui.notify(`Cannot record session location for cleanup: ${String(error)}`, 'warning');
152
+ }
153
+ };
154
+ pi.on('turn_end', async (_event, ctx) => { await rememberLocation(ctx); });
134
155
  const bindSession = async (ctx: Parameters<SessionBinding["bind"]>[0], reason: "startup" | "reload" | "new" | "resume" | "fork", previousSessionFile?: string) => {
135
156
  // Tree navigation has no shutdown event. Revoke the old readers and timers before
136
157
  // rebinding, without appending their state into the branch the host just selected.
@@ -140,8 +161,11 @@ export async function createSuite(pi: ExtensionAPI, initial: ExtensionContext, f
140
161
  if (!firstBinding) config = loadConfig(ctx.cwd);
141
162
  const goalReason = firstBinding ? reason : "tree";
142
163
  firstBinding = false; cachedTypes = undefined;
164
+ if (!use) use = await registerSessionUse(getAgentDir(), ctx);
143
165
  await prepareClipboard(pi, ctx);
144
166
  binding.bind(ctx);
167
+ observedFile = undefined; locationWarning = false;
168
+ await rememberLocation(ctx);
145
169
  notifier.bind(ctx);
146
170
  recovery?.reset(ctx);
147
171
  dock.bind(ctx, config.ui.maxRows);
@@ -176,7 +200,25 @@ export async function createSuite(pi: ExtensionAPI, initial: ExtensionContext, f
176
200
  workflows?.detach(); agents?.detach();
177
201
  recovery?.reset();
178
202
  notifications.detach(); status.detach(); dock.detach(binding.current?.ctx); binding.revoke();
179
- return Promise.all([quit, agentQuit, workflowQuit, scheduleQuit]).then(() => { if (agents) pi.events.emit('subagents:disposed', {}); });
203
+ const outgoing = use;
204
+ const jobRuntime = jobGlobals[jobKey]?.manager;
205
+ use = undefined;
206
+ return Promise.all([quit, agentQuit, workflowQuit, scheduleQuit]).then(async () => {
207
+ if (outgoing) {
208
+ const retire = async () => {
209
+ await schedules?.drain();
210
+ await retireSessionUse(outgoing, () => Boolean(agents?.manager.cleanupOwners?.().has(outgoing.owner)
211
+ || workflows?.manager.cleanupOwners?.().has(outgoing.owner)
212
+ || jobRuntime?.cleanupOwners && [...jobRuntime.cleanupOwners()].includes(outgoing.owner)), listener => [
213
+ agents?.manager.subscribe(listener), workflows?.manager.subscribe(listener), jobRuntime?.subscribe(listener),
214
+ ].filter(callback => callback !== undefined));
215
+ };
216
+ if (event.reason === 'quit') await retire();
217
+ // Keep the outgoing lease until the replacement publishes its own references.
218
+ else handoffSessionUse(outgoing, event.reason === 'reload' ? outgoing.owner : event.targetSessionFile, retire);
219
+ }
220
+ if (agents) pi.events.emit('subagents:disposed', {});
221
+ });
180
222
  });
181
223
  pi.on("agent_before_settle", async event => {
182
224
  const repair = recovery?.beforeSettle(event);
@@ -57,6 +57,23 @@ function decode(value: unknown, generation: string): TaskData {
57
57
  if (!Value.Check(storeSchema, value)) throw new Error('Invalid version or task data');
58
58
  validateHierarchy(value); return value;
59
59
  }
60
+
61
+ // The task directory can also contain unversioned, flat task lists. Recognize the
62
+ // distinct on-disk shape, not just a missing version; malformed Suite files must fail.
63
+ const foreignTaskStore = Type.Object({ nextId: Type.Integer({minimum: 1}), tasks: Type.Array(Type.Object({
64
+ id: Type.String(), subject: Type.String(), description: Type.Optional(Type.String()), activeForm: Type.Optional(Type.String()),
65
+ status: Type.Union([Type.Literal('pending'), Type.Literal('in_progress'), Type.Literal('completed')]),
66
+ blockedBy: Type.Array(Type.String()), blocks: Type.Array(Type.String()),
67
+ owner: Type.Optional(Type.String()), metadata: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
68
+ createdAt: Type.Integer(), updatedAt: Type.Integer(),
69
+ }, {additionalProperties: false}), {minItems: 1}) }, {additionalProperties: false});
70
+
71
+ export function cleanupTaskSnapshot(path: string): Promise<TaskData | null> {
72
+ return new JsonStore<TaskData | null>(path, null, value =>
73
+ Value.Check(foreignTaskStore, value) ? null : decode(value, initialGeneration(path)), 'TASK').snapshot();
74
+ }
75
+
76
+ const initialGeneration = (path: string) => `initial:${createHash('sha256').update(path).digest('hex')}`;
60
77
  const display = (data: TaskData): TaskDisplay[] => taskViews(data).map(({ id, title, parentId, status, updatedAt, progress }) =>
61
78
  ({ id, title, parentId, status, updatedAt, progress }));
62
79
  const complete = (data: TaskData) => data.tasks.length > 0 && taskViews(data).every(task => task.status === 'done');
@@ -68,7 +85,7 @@ export class TaskStore extends JsonStore<TaskData> {
68
85
  constructor(path?: string, legacy?: Promise<unknown>) {
69
86
  // Readers/processes of an uninitialized or v3 file must agree before the first locked
70
87
  // commit. Clear then replaces this capability with a fresh, unpredictable generation.
71
- const initial = emptyTasks(path ? `initial:${createHash('sha256').update(path).digest('hex')}` : undefined);
88
+ const initial = emptyTasks(path ? initialGeneration(path) : undefined);
72
89
  super(path, initial, value => decode(value, initial.generation), 'TASK');
73
90
  this.initialGeneration = initial.generation;
74
91
  this.ready = legacy ? legacy.then(value => { this.data = decode(value, initial.generation); }) : Promise.resolve();