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,91 @@
1
+ import { realpath } from 'node:fs/promises';
2
+ import { basename, dirname, isAbsolute, join } from 'node:path';
3
+ import type { ExtensionContext } from '@earendil-works/pi-coding-agent';
4
+ import { Type, type Static } from 'typebox';
5
+ import { Value } from 'typebox/value';
6
+ import { JsonStore } from '../json-store.ts';
7
+ import { inspect, pathKey, sameRoot } from './paths.ts';
8
+
9
+ export const SESSION_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
10
+ const directory = Type.Object({path: Type.String(), dev: Type.Number(), ino: Type.Number(), birthtimeMs: Type.Number()});
11
+ const location = Type.Object({id: Type.String({pattern: SESSION_ID.source}), file: Type.String(),
12
+ root: directory, workspace: directory});
13
+ const schema = Type.Object({version: Type.Literal(1), sessions: Type.Array(location), childRoots: Type.Array(directory)});
14
+ type Registry = Static<typeof schema>;
15
+ export type Home = Static<typeof location>;
16
+ export type Directory = Static<typeof directory>;
17
+ export const maintenanceDir = (agentDir: string) => join(agentDir, 'pi-suite', 'cleanup');
18
+
19
+ class LocationStore extends JsonStore<Registry> {
20
+ constructor(agentDir: string) {
21
+ const empty = (): Registry => ({version: 1, sessions: [], childRoots: []});
22
+ super(join(maintenanceDir(agentDir), 'locations.json'), empty(), value => {
23
+ if (!Value.Check(schema, value) || value.sessions.some(home => !isAbsolute(home.file) || !home.file.endsWith('.jsonl')
24
+ || pathKey(dirname(home.file)) !== pathKey(home.root.path)) ||
25
+ [...value.childRoots, ...value.sessions.flatMap(home => [home.root, home.workspace])].some(dir => !isAbsolute(dir.path))) {
26
+ throw new Error('Invalid session location registry');
27
+ }
28
+ return value;
29
+ }, 'CLEANUP_LOCATIONS', {missing: empty, skipUnchanged: true});
30
+ }
31
+ remember(home: Home) {
32
+ return this.mutate(data => {
33
+ if (!data.sessions.some(other => other.id === home.id && pathKey(home.file) === pathKey(other.file)
34
+ && sameRoot(home.root, other.root) && sameRoot(home.workspace, other.workspace))) data.sessions.push(home);
35
+ });
36
+ }
37
+ addChild(root: Directory) {
38
+ return this.mutate(data => {
39
+ if (!data.childRoots.some(other => pathKey(other.path) === pathKey(root.path) && sameRoot(root, other))) data.childRoots.push(root);
40
+ });
41
+ }
42
+ }
43
+ const stores = new Map<string, LocationStore>();
44
+ function store(agentDir: string): LocationStore {
45
+ const key = pathKey(agentDir);
46
+ let current = stores.get(key);
47
+ if (!current) { current = new LocationStore(agentDir); stores.set(key, current); }
48
+ return current;
49
+ }
50
+ export async function locations(agentDir: string): Promise<Registry> {
51
+ await inspect(agentDir, join(maintenanceDir(agentDir), 'locations.json'));
52
+ return store(agentDir).snapshot();
53
+ }
54
+
55
+ export async function identifyDirectory(path: string): Promise<Directory> {
56
+ const canonical = await realpath(path), info = await inspect(canonical, canonical);
57
+ return {path: canonical, dev: info!.dev, ino: info!.ino, birthtimeMs: info!.birthtimeMs};
58
+ }
59
+ export async function verifyDirectory(dir: Directory): Promise<void> {
60
+ const info = await inspect(dir.path, dir.path);
61
+ if (!info || !sameRoot(info, dir)) throw new Error(`Storage directory changed or is unavailable: ${dir.path}`);
62
+ }
63
+
64
+ export async function rememberVerifiedHome(agentDir: string, home: Home): Promise<void> {
65
+ await inspect(agentDir, join(maintenanceDir(agentDir), 'locations.json'));
66
+ await store(agentDir).remember(home);
67
+ }
68
+
69
+ /** Nothing in the registry claims a session that only exists in memory. */
70
+ export async function rememberSession(agentDir: string, session: ExtensionContext['sessionManager']): Promise<boolean> {
71
+ const file = session.getSessionFile(), header = session.getHeader();
72
+ if (!file || !header || !SESSION_ID.test(header.id)) return false;
73
+ const root = await identifyDirectory(dirname(file)), canonical = join(root.path, basename(file));
74
+ const info = await inspect(root.path, canonical);
75
+ if (!info) return false; // Pi writes new sessions only once they have a conversation.
76
+ if (!info.isFile()) throw new Error(`Session path is not a regular file: ${canonical}`);
77
+ const workspace = await identifyDirectory(header.cwd), base = await realpath(agentDir);
78
+ await rememberVerifiedHome(base, {id: header.id, file: canonical, root, workspace});
79
+ return true;
80
+ }
81
+
82
+ const childSeen = new Set<string>();
83
+ export async function rememberChildRoot(agentDir: string, directory: string): Promise<void> {
84
+ const root = await identifyDirectory(directory);
85
+ const key = JSON.stringify([agentDir, root.path, root.dev, root.ino, root.birthtimeMs]);
86
+ if (!childSeen.has(key)) {
87
+ const base = await realpath(agentDir);
88
+ await inspect(base, join(maintenanceDir(base), 'locations.json'));
89
+ await store(base).addChild(root); childSeen.add(key);
90
+ }
91
+ }
@@ -0,0 +1,117 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mkdir, stat } from 'node:fs/promises';
3
+ import { hostname } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import type { DatabaseSync } from 'node:sqlite';
6
+ import { setTimeout as sleep } from 'node:timers/promises';
7
+ import { maintenanceDir, SESSION_ID } from './locations.ts';
8
+ import { inspect } from './paths.ts';
9
+ import { references, type References } from './sessions.ts';
10
+
11
+ const host = hostname();
12
+ const file = (root: string) => join(maintenanceDir(root), 'coordination.sqlite');
13
+ export async function coordinated(root: string): Promise<boolean> {
14
+ const info = await inspect(root, file(root));
15
+ if (info && !info.isFile()) throw new Error('Invalid cleanup coordination store.');
16
+ return Boolean(info);
17
+ }
18
+
19
+ /** SQLite serializes publication and the final scan + move, and releases the gate on process death. */
20
+ export async function withCoordination<T>(root: string, run: (db: DatabaseSync) => Promise<T> | T, create = false): Promise<T> {
21
+ const { DatabaseSync } = await import('node:sqlite');
22
+ if (!await coordinated(root) && !create) throw new Error('Cleanup coordination store is missing.');
23
+ const db = new DatabaseSync(file(root));
24
+ try {
25
+ while (true) {
26
+ try { db.exec('BEGIN IMMEDIATE'); break; }
27
+ catch (error) {
28
+ if ((error as {errcode?: number}).errcode !== 5) throw error; // SQLITE_BUSY
29
+ await sleep(30);
30
+ }
31
+ }
32
+ if (create) {
33
+ db.exec(`CREATE TABLE IF NOT EXISTS host (name TEXT PRIMARY KEY);
34
+ CREATE TABLE IF NOT EXISTS uses (token TEXT PRIMARY KEY, pid INTEGER NOT NULL,
35
+ owner TEXT NOT NULL, paths TEXT NOT NULL, ids TEXT NOT NULL)`);
36
+ if (!db.prepare('SELECT name FROM host').get()) db.prepare('INSERT INTO host VALUES (?)').run(host);
37
+ }
38
+ if (db.prepare('SELECT name FROM host').get()?.name !== host) throw new Error('Cleanup coordination requires storage local to this machine.');
39
+ const result = await run(db);
40
+ db.exec('COMMIT');
41
+ return result;
42
+ } finally { db.close(); }
43
+ }
44
+
45
+ export async function enableCoordination(root: string): Promise<void> {
46
+ await coordinated(root);
47
+ await mkdir(maintenanceDir(root), {recursive: true, mode: 0o700});
48
+ await withCoordination(root, () => {}, true);
49
+ }
50
+
51
+ export function readOccupancy(db: DatabaseSync): {held: Set<string>; local: Set<string>; sources: {owner: string; refs: References}[]} {
52
+ const held = new Set<string>(), local = new Set<string>(), sources: {owner: string; refs: References}[] = [];
53
+ const forget = db.prepare('DELETE FROM uses WHERE token = ?');
54
+ for (const row of db.prepare('SELECT * FROM uses').all()) {
55
+ const {token, pid, owner} = row;
56
+ const decode = (raw: unknown): string[] => {
57
+ const values: unknown = typeof raw === 'string' ? JSON.parse(raw) : undefined;
58
+ if (!Array.isArray(values) || values.some(item => typeof item !== 'string')) throw new Error('Invalid cleanup occupancy references.');
59
+ return values;
60
+ };
61
+ if (typeof token !== 'string' || typeof pid !== 'number' || !Number.isSafeInteger(pid) || pid <= 0
62
+ || typeof owner !== 'string' || !SESSION_ID.test(owner)) throw new Error('Invalid cleanup occupancy record.');
63
+ try { process.kill(pid, 0); }
64
+ catch (error) {
65
+ const code = (error as NodeJS.ErrnoException).code;
66
+ if (code === 'ESRCH') { forget.run(token); continue; }
67
+ if (code !== 'EPERM') throw error; // An unsignalable process may still be alive.
68
+ }
69
+ held.add(owner);
70
+ if (pid === process.pid) local.add(owner);
71
+ sources.push({owner, refs: {paths: new Set(decode(row.paths)), ids: new Set(decode(row.ids))}});
72
+ }
73
+ return {held, local, sources};
74
+ }
75
+
76
+ export class SessionUse {
77
+ private readonly token = randomUUID();
78
+ private refs = references();
79
+ private queue: Promise<void> = Promise.resolve();
80
+ private released = false;
81
+ private constructor(readonly root: string, readonly owner: string) {}
82
+ static async register(root: string, owner: string, prepare: (refs: References) => Promise<void>): Promise<SessionUse> {
83
+ const use = new SessionUse(root, owner);
84
+ await withCoordination(root, async db => {
85
+ await prepare(use.refs);
86
+ db.prepare('INSERT INTO uses VALUES (?, ?, ?, ?, ?)').run(use.token, process.pid, owner,
87
+ JSON.stringify([...use.refs.paths]), JSON.stringify([...use.refs.ids]));
88
+ });
89
+ return use;
90
+ }
91
+ async add(refs: References): Promise<void> {
92
+ const publish = this.queue.then(async () => {
93
+ if (this.released) throw new Error('Session occupancy ended before publishing references.');
94
+ if (![...refs.paths].some(path => !this.refs.paths.has(path)) && ![...refs.ids].some(id => !this.refs.ids.has(id))) return;
95
+ const next = {paths: new Set([...this.refs.paths, ...refs.paths]), ids: new Set([...this.refs.ids, ...refs.ids])};
96
+ await withCoordination(this.root, db => {
97
+ const updated = db.prepare('UPDATE uses SET paths = ?, ids = ? WHERE token = ?').run(JSON.stringify([...next.paths]), JSON.stringify([...next.ids]), this.token);
98
+ if (!updated.changes) throw new Error('Cleanup occupancy was lost before publishing references.');
99
+ });
100
+ this.refs = next;
101
+ });
102
+ this.queue = publish.catch(() => {}); // Keep the queue usable; the caller receives the failure.
103
+ return publish;
104
+ }
105
+ async release(): Promise<void> {
106
+ this.released = true;
107
+ await this.queue;
108
+ await withCoordination(this.root, db => { db.prepare('DELETE FROM uses WHERE token = ?').run(this.token); });
109
+ }
110
+ }
111
+
112
+ export async function assertSessionAvailable(path: string, hadConversation: boolean): Promise<void> {
113
+ if (!hadConversation) return; // Pi intentionally defers creating new session files.
114
+ try { if ((await stat(path)).isFile()) return; }
115
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
116
+ throw new Error('This session file disappeared before Suite could open its data. Restore the main session and retry.');
117
+ }
@@ -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
+ }