pi-suite 0.3.7 → 0.4.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/package.json +7 -7
- package/src/agents/child.ts +9 -3
- package/src/agents/history.ts +3 -3
- package/src/agents/index.ts +22 -21
- package/src/agents/manager.ts +40 -12
- package/src/agents/records.ts +4 -2
- package/src/agents/runner.ts +15 -4
- package/src/agents/runtime.ts +1 -1
- package/src/agents/schedules/menu.ts +1 -1
- package/src/agents/types.ts +2 -1
- package/src/agents/ui/runs.ts +33 -13
- package/src/agents/viewer.ts +17 -11
- package/src/agents/workflow/index.ts +32 -9
- package/src/agents/workflow/manager.ts +18 -6
- package/src/agents/workflow/ui/menu.ts +2 -2
- package/src/jobs/backends/pipe.ts +5 -5
- package/src/jobs/index.ts +49 -36
- package/src/jobs/manager-record.ts +2 -2
- package/src/jobs/manager.ts +30 -12
- package/src/jobs/monitors/compile.ts +1 -1
- package/src/jobs/monitors/runtime.ts +44 -29
- package/src/jobs/store.ts +49 -10
- package/src/jobs/terminal/session.ts +5 -5
- package/src/jobs/terminal/shell.ts +11 -1
- package/src/jobs/tools.ts +2 -2
- package/src/jobs/types.ts +2 -0
- package/src/jobs/viewer/metadata.ts +6 -0
- package/src/jobs/viewer.ts +30 -25
- package/src/runtime/branch.ts +14 -0
- package/src/runtime/cleanup/command.ts +116 -0
- package/src/runtime/cleanup/locations.ts +91 -0
- package/src/runtime/cleanup/occupancy.ts +117 -0
- package/src/runtime/cleanup/paths.ts +44 -0
- package/src/runtime/cleanup/quarantine.ts +162 -0
- package/src/runtime/cleanup/scan.ts +297 -0
- package/src/runtime/cleanup/session-use.ts +62 -0
- package/src/runtime/cleanup/sessions.ts +119 -0
- package/src/runtime/json-store.ts +6 -0
- package/src/runtime/owner.ts +1 -1
- package/src/runtime/settings/index.ts +9 -1
- package/src/runtime/suite.ts +43 -1
- package/src/tasks/store.ts +18 -1
- package/src/tasks/viewer.ts +14 -12
- package/src/ui/actions.ts +1 -1
- package/src/ui/browser.ts +95 -43
- package/src/ui/scroll.ts +5 -1
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { Stats } from 'node:fs';
|
|
2
|
+
import { lstat, realpath } from 'node:fs/promises';
|
|
3
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
4
|
+
import { errnoCode } from '../../jobs/types.ts';
|
|
5
|
+
|
|
6
|
+
export type FileStamp = Pick<Stats, 'dev' | 'ino' | 'size' | 'mtimeMs' | 'birthtimeMs'>;
|
|
7
|
+
export const stamp = ({dev, ino, size, mtimeMs, birthtimeMs}: Stats): FileStamp => ({dev, ino, size, mtimeMs, birthtimeMs});
|
|
8
|
+
export const matches = (info: FileStamp | undefined, expected: FileStamp): boolean => !!info && sameRoot(info, expected)
|
|
9
|
+
&& info.size === expected.size && info.mtimeMs === expected.mtimeMs;
|
|
10
|
+
export const sameRoot = (info: Pick<Stats, 'dev' | 'ino' | 'birthtimeMs'>, expected: typeof info): boolean =>
|
|
11
|
+
info.dev === expected.dev && info.ino === expected.ino && info.birthtimeMs === expected.birthtimeMs;
|
|
12
|
+
export const pathKey = (path: string): string => process.platform === 'win32' ? resolve(path).toLowerCase() : resolve(path);
|
|
13
|
+
export function contains(base: string, path: string): boolean {
|
|
14
|
+
const rel = relative(base, path);
|
|
15
|
+
return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel);
|
|
16
|
+
}
|
|
17
|
+
export async function statIfPresent(path: string): Promise<Stats | undefined> {
|
|
18
|
+
try { return await lstat(path); } catch (error) { if (errnoCode(error) !== 'ENOENT') throw error; }
|
|
19
|
+
}
|
|
20
|
+
/** References can use Pi's workspace aliases even when moves use only canonical paths. */
|
|
21
|
+
export async function referenceKey(path: string): Promise<string> {
|
|
22
|
+
try { return pathKey(await realpath(path)); }
|
|
23
|
+
catch (error) {
|
|
24
|
+
if (errnoCode(error) !== 'ENOENT') throw error;
|
|
25
|
+
try { return pathKey(join(await realpath(dirname(path)), basename(path))); }
|
|
26
|
+
catch (parentError) { if (errnoCode(parentError) !== 'ENOENT') throw parentError; return pathKey(path); }
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Managed roots are canonical; never traverse a redirected component during a move. */
|
|
31
|
+
export async function inspect(base: string, path: string): Promise<Stats | undefined> {
|
|
32
|
+
if (!contains(base, path)) throw new Error(`Path leaves managed root: ${path}`);
|
|
33
|
+
let current = base;
|
|
34
|
+
let info = await lstat(base);
|
|
35
|
+
if (!info.isDirectory() || pathKey(await realpath(base)) !== pathKey(base)) throw new Error(`Invalid managed root: ${base}`);
|
|
36
|
+
for (const part of relative(base, path).split(sep).filter(Boolean)) {
|
|
37
|
+
current = join(current, part);
|
|
38
|
+
const child = await statIfPresent(current);
|
|
39
|
+
if (!child) return;
|
|
40
|
+
if (child.isSymbolicLink()) throw new Error(`Managed path is a link: ${current}`);
|
|
41
|
+
info = child;
|
|
42
|
+
}
|
|
43
|
+
return info;
|
|
44
|
+
}
|
|
@@ -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
|
+
}
|