@sion10032/pi-sessions 0.0.0-stage → 0.2.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/src/archive.ts ADDED
@@ -0,0 +1,356 @@
1
+ /**
2
+ * File-level primitives for archiving sessions.
3
+ *
4
+ * A session owns more than its JSONL file: subagent runs and forks live in a
5
+ * sibling directory, agent-browser keeps screenshots per session id, and
6
+ * subagent artifacts are grouped by run. These helpers find and move those
7
+ * companions, fold a late tail back into an archived file, strip the legacy
8
+ * archive tag, and discover derived sessions by their parent chain.
9
+ *
10
+ * Moves are best effort: one failing companion never aborts the rest.
11
+ * `archiveSessionFile` and `restoreSessionFile` compose these primitives into
12
+ * the whole-tree moves the commands, tool and hooks use.
13
+ */
14
+ import {
15
+ appendFileSync,
16
+ existsSync,
17
+ mkdirSync,
18
+ readFileSync,
19
+ readdirSync,
20
+ renameSync,
21
+ unlinkSync,
22
+ writeFileSync,
23
+ } from "node:fs";
24
+ import {
25
+ basename,
26
+ dirname,
27
+ join,
28
+ resolve,
29
+ } from "node:path";
30
+
31
+ import {
32
+ archiveRoot,
33
+ hasArchiveTag,
34
+ isArchived,
35
+ readHeader,
36
+ sessionIdFromFile,
37
+ sessionsRoot,
38
+ stripArchiveTag,
39
+ twinPaths,
40
+ underRoot,
41
+ } from "./paths.ts";
42
+ import { clearPending, readIndex, writeIndex } from "./state.ts";
43
+
44
+ function parentSessionId(metaFile: string): string | undefined {
45
+ try {
46
+ return JSON.parse(readFileSync(metaFile, "utf8")).parentSessionId;
47
+ } catch {
48
+ return undefined;
49
+ }
50
+ }
51
+
52
+ const SUBAGENT_ARTIFACT_SUFFIX = /^_(?:input\.md|output\.md|meta\.json|transcript\.jsonl)$/;
53
+
54
+ /**
55
+ * Paths, relative to a per-cwd sessions dir, that belong to a session beside its
56
+ * file: its `<file>/` dir (subagent runs, forks), its subagent-artifacts runs, and its agent-browser screenshots.
57
+ */
58
+ export function findCompanions(dir: string, file: string): string[] {
59
+ const id = sessionIdFromFile(file);
60
+ const found = [basename(file, ".jsonl"), join(".pi-agent-browser-artifacts", id)].filter((rel) =>
61
+ existsSync(join(dir, rel)),
62
+ );
63
+ const artifactsDir = join(dir, "subagent-artifacts");
64
+ if (!existsSync(artifactsDir)) return found;
65
+ const names = readdirSync(artifactsDir);
66
+ for (const meta of names.filter((name) => name.endsWith("_meta.json"))) {
67
+ if (parentSessionId(join(artifactsDir, meta)) !== id) continue;
68
+ const run = meta.slice(0, -"_meta.json".length);
69
+ for (const name of names) {
70
+ if (name.startsWith(run) && SUBAGENT_ARTIFACT_SUFFIX.test(name.slice(run.length))) {
71
+ found.push(join("subagent-artifacts", name));
72
+ }
73
+ }
74
+ }
75
+ return found;
76
+ }
77
+
78
+ /** Best effort: a companion whose destination already exists stays where it is. */
79
+ export function moveCompanions(fromDir: string, toDir: string, file: string): void {
80
+ for (const rel of findCompanions(fromDir, file)) {
81
+ const target = join(toDir, rel);
82
+ if (existsSync(target)) continue;
83
+ try {
84
+ mkdirSync(dirname(target), { recursive: true });
85
+ renameSync(join(fromDir, rel), target);
86
+ } catch {}
87
+ }
88
+ }
89
+
90
+ function parseEntries(file: string): { id?: string; parentId?: string | null; type?: string }[] {
91
+ return readFileSync(file, "utf8")
92
+ .split("\n")
93
+ .filter(Boolean)
94
+ .map((line) => {
95
+ try {
96
+ return JSON.parse(line);
97
+ } catch {
98
+ return {};
99
+ }
100
+ });
101
+ }
102
+
103
+ /**
104
+ * A headerless file at the live path is the tail pi kept writing after an
105
+ * earlier move: append it to the archived copy when all its entries chain onto it.
106
+ */
107
+ export function appendIfContinuation(fragment: string, archived: string): boolean {
108
+ const tail = parseEntries(fragment);
109
+ if (tail.length === 0 || tail[0].type === "session") return false;
110
+ const archivedIds = new Set(parseEntries(archived).map((entry) => entry.id));
111
+ const tailIds = new Set(tail.map((entry) => entry.id));
112
+ const parents = tail.map((entry) => entry.parentId).filter((id): id is string => typeof id === "string");
113
+ if (!parents.some((id) => archivedIds.has(id))) return false;
114
+ if (!parents.every((id) => archivedIds.has(id) || tailIds.has(id))) return false;
115
+ const separator = readFileSync(archived, "utf8").endsWith("\n") ? "" : "\n";
116
+ appendFileSync(archived, separator + readFileSync(fragment, "utf8"));
117
+ unlinkSync(fragment);
118
+ return true;
119
+ }
120
+
121
+ /**
122
+ * Strip one or more leading [ARCHIVE] tags from the last session_info name,
123
+ * editing the file in place (temp file + rename so a crash cannot truncate
124
+ * it). Restoring needs this: a restored file that keeps the tag would be
125
+ * re-archived on its next close by the self-heal logic. Names without the tag
126
+ * are left byte for byte alone. Best effort; the move already succeeded.
127
+ */
128
+ export function stripLegacyTag(file: string): void {
129
+ try {
130
+ const lines = readFileSync(file, "utf8").split("\n");
131
+ for (let i = lines.length - 1; i >= 0; i--) {
132
+ const line = lines[i];
133
+ if (!line.includes('"type":"session_info"')) continue;
134
+ const match = line.match(/"name":"((?:[^"\\]|\\.)*)"/);
135
+ if (!match) return;
136
+ const decoded = JSON.parse(`"${match[1]}"`);
137
+ if (!hasArchiveTag(decoded)) return;
138
+ const stripped = JSON.stringify(stripArchiveTag(decoded)).slice(1, -1);
139
+ lines[i] = line.replace(`"name":"${match[1]}"`, `"name":"${stripped}"`);
140
+ const tmp = `${file}.pi-sessions-tmp`;
141
+ writeFileSync(tmp, lines.join("\n"));
142
+ renameSync(tmp, file);
143
+ return;
144
+ }
145
+ } catch {
146
+ // best effort: a malformed file must not abort the surrounding operation
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Session files in `dir` whose header names `rootFile` or one of its
152
+ * descendants as their `parentSession`, walking the chain breadth first.
153
+ * Parent headers may point at either the live or archived path of a file,
154
+ * so twin paths are compared as well.
155
+ */
156
+ export function descendantFiles(dir: string, rootFile: string): string[] {
157
+ const parents = new Map<string, string | undefined>();
158
+ for (const name of readdirSync(dir)) {
159
+ if (!name.endsWith(".jsonl")) continue;
160
+ const file = join(dir, name);
161
+ parents.set(file, readHeader(file)?.parentSession);
162
+ }
163
+ const seen = new Set<string>();
164
+ const result: string[] = [];
165
+ const queue = [rootFile];
166
+ while (queue.length > 0) {
167
+ const current = queue.shift()!;
168
+ const keys = new Set(twinPaths(current).map((p) => resolve(p)));
169
+ for (const [path, parent] of parents) {
170
+ if (!parent || seen.has(path)) continue;
171
+ if (!keys.has(resolve(parent))) continue;
172
+ seen.add(path);
173
+ result.push(path);
174
+ queue.push(path);
175
+ }
176
+ }
177
+ return result;
178
+ }
179
+
180
+ export interface ArchiveOptions {
181
+ name?: string;
182
+ now?: Date;
183
+ /**
184
+ * Session files that must not move: the session pi is still writing, or a
185
+ * shutdown's target session. A protected file inside the selected subtree
186
+ * stays where it is, companions included, and so does everything below it.
187
+ * A protected ancestor does not veto the move: the user explicitly selected
188
+ * this subtree.
189
+ */
190
+ protect?: readonly string[];
191
+ }
192
+
193
+ export interface RestoreOptions {
194
+ /**
195
+ * Live session files that must not move, e.g. the current session. As with
196
+ * `ArchiveOptions.protect`, only protection inside the selected subtree
197
+ * blocks a file.
198
+ */
199
+ protect?: readonly string[];
200
+ }
201
+
202
+ /**
203
+ * Resolved keys of the files a move must leave alone, twins included: a
204
+ * protected live file can be targeted through its archived copy and vice
205
+ * versa, and either path names the same session.
206
+ */
207
+ function protectedKeys(protect: readonly string[] | undefined): Set<string> {
208
+ const keys = new Set<string>();
209
+ for (const path of protect ?? []) {
210
+ for (const twin of twinPaths(path)) keys.add(resolve(twin));
211
+ }
212
+ return keys;
213
+ }
214
+
215
+ /**
216
+ * The files of a move that may actually move. `files` is the selected root
217
+ * followed by its discovered descendants. A protected file that lies inside
218
+ * that subtree is dropped together with its own descendants: sweeping them up
219
+ * would move the session pi is still writing, or the fork it is about to
220
+ * write. A protected ancestor - typically the current session while the user
221
+ * archives one of its children - blocks nothing: the root was selected
222
+ * explicitly, and a directly protected root is rejected before this filter
223
+ * runs.
224
+ */
225
+ function movableFiles(files: string[], dir: string, keys: ReadonlySet<string>): string[] {
226
+ if (keys.size === 0) return files;
227
+ const [root, ...descendants] = files;
228
+ const tree = new Set(descendants.map((file) => resolve(file)));
229
+ const blocked = new Set<string>();
230
+ for (const key of keys) {
231
+ const resolved = resolve(key);
232
+ if (!tree.has(resolved)) continue;
233
+ blocked.add(resolved);
234
+ for (const child of descendantFiles(dir, key)) blocked.add(resolve(child));
235
+ }
236
+ if (blocked.size === 0) return files;
237
+ return [root, ...descendants.filter((file) => !blocked.has(resolve(file)))];
238
+ }
239
+
240
+ /** Timestamp suffix that stays valid on every filesystem (no colons). */
241
+ function supersededStamp(now: Date): string {
242
+ return now.toISOString().replace(/[:.]/g, "-");
243
+ }
244
+
245
+ /**
246
+ * Move `source` onto `target`. A target that already exists is folded into the
247
+ * same session when it is only a continuation tail, otherwise it is renamed
248
+ * aside first: a stale copy is never overwritten, only preserved.
249
+ */
250
+ function moveSessionFile(source: string, target: string, now: Date): string {
251
+ mkdirSync(dirname(target), { recursive: true });
252
+ if (existsSync(target)) {
253
+ let merged = false;
254
+ try {
255
+ merged = appendIfContinuation(source, target);
256
+ } catch {
257
+ merged = false;
258
+ }
259
+ if (merged) return target;
260
+ renameSync(target, `${target}.superseded-${supersededStamp(now)}`);
261
+ }
262
+ renameSync(source, target);
263
+ return target;
264
+ }
265
+
266
+ /**
267
+ * Move a live session file, its descendant sessions and their companions into
268
+ * the archive, recording every moved session in the index. Returns the
269
+ * archived paths, root first; a file outside the live sessions root is left
270
+ * alone. The root is mandatory (a failure throws so the caller can keep the
271
+ * request pending); a descendant that fails is skipped.
272
+ *
273
+ * A protected file inside the subtree being moved - the session pi is writing,
274
+ * or the target of the shutdown that is running - never moves, and neither do
275
+ * its descendants: pi would keep appending to the old path and the session
276
+ * would vanish from `/resume`. A protected ancestor does not block the move,
277
+ * so archiving a child of the live session still archives that child.
278
+ */
279
+ export function archiveSessionFile(file: string, options: ArchiveOptions = {}): string[] {
280
+ if (underRoot(sessionsRoot(), file) === undefined) return [];
281
+ const source = resolve(file);
282
+ const protect = protectedKeys(options.protect);
283
+ if (protect.has(source)) return [];
284
+ const dir = dirname(source);
285
+ const archivedDir = join(archiveRoot(), basename(dir));
286
+ const now = options.now ?? new Date();
287
+ const archivedAt = now.toISOString();
288
+ const index = readIndex();
289
+ const moved: string[] = [];
290
+ const sessionFiles = movableFiles([source, ...descendantFiles(dir, source)], dir, protect);
291
+ for (const [position, sessionFile] of sessionFiles.entries()) {
292
+ const header = readHeader(sessionFile);
293
+ let archived: string;
294
+ try {
295
+ archived = moveSessionFile(sessionFile, join(archivedDir, basename(sessionFile)), now);
296
+ } catch (error) {
297
+ if (position === 0) throw error;
298
+ continue;
299
+ }
300
+ moved.push(archived);
301
+ moveCompanions(dir, archivedDir, sessionFile);
302
+ index[join(basename(dir), basename(sessionFile))] = {
303
+ name: position === 0 ? (options.name ?? "") : "",
304
+ cwd: header?.cwd ?? "",
305
+ archivedAt,
306
+ id: header?.id,
307
+ };
308
+ }
309
+ writeIndex(index);
310
+ clearPending(sessionIdFromFile(source));
311
+ return moved;
312
+ }
313
+
314
+ /**
315
+ * Move an archived session file, its descendant sessions and their companions
316
+ * back under the live sessions root and drop their index entries. Returns the
317
+ * live paths, root first; a file outside the archive is left alone. When the
318
+ * live copy of the root already exists - or the root is protected - nothing is
319
+ * restored and the archived copy stays intact; a descendant whose live copy
320
+ * exists is skipped. A protected file inside the subtree is left in the
321
+ * archive, while a protected ancestor does not block the restore.
322
+ */
323
+ export function restoreSessionFile(file: string, options: RestoreOptions = {}): string[] {
324
+ if (!isArchived(file)) return [];
325
+ const source = resolve(file);
326
+ const protect = protectedKeys(options.protect);
327
+ if (protect.has(source)) return [];
328
+ const archivedDir = dirname(source);
329
+ const liveDir = join(sessionsRoot(), basename(archivedDir));
330
+ const index = readIndex();
331
+ const moved: string[] = [];
332
+ const sessionFiles = movableFiles([source, ...descendantFiles(archivedDir, source)], archivedDir, protect);
333
+ for (const [position, sessionFile] of sessionFiles.entries()) {
334
+ const target = join(liveDir, basename(sessionFile));
335
+ if (existsSync(target)) {
336
+ if (position === 0) return [];
337
+ continue;
338
+ }
339
+ try {
340
+ mkdirSync(liveDir, { recursive: true });
341
+ renameSync(sessionFile, target);
342
+ } catch (error) {
343
+ if (position === 0) throw error;
344
+ continue;
345
+ }
346
+ moved.push(target);
347
+ moveCompanions(archivedDir, liveDir, sessionFile);
348
+ stripLegacyTag(target);
349
+ for (const key of Object.keys(index)) {
350
+ if (resolve(join(archiveRoot(), key)) === sessionFile) delete index[key];
351
+ }
352
+ }
353
+ writeIndex(index);
354
+ for (const path of moved) clearPending(sessionIdFromFile(path));
355
+ return moved;
356
+ }