@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.
@@ -0,0 +1,492 @@
1
+ /**
2
+ * Loading, parent resolution and the collapsible forest the picker renders.
3
+ *
4
+ * Sessions live in two trees: `<agent>/sessions/` for the live ones and
5
+ * `<agent>/sessions-archive/` for the ones this extension moved. A fork
6
+ * records its parent as one path in its own header, written when the parent
7
+ * happened to be somewhere in particular, so the path can point into the other
8
+ * tree. Parent links are therefore resolved at read time - the recorded path
9
+ * first, then its twin in the other tree - and never rewritten on disk.
10
+ */
11
+ import { existsSync, readdirSync } from "node:fs";
12
+ import {
13
+ basename,
14
+ dirname,
15
+ join,
16
+ resolve,
17
+ } from "node:path";
18
+
19
+ import {
20
+ SessionManager,
21
+ type SessionInfo,
22
+ } from "@earendil-works/pi-coding-agent";
23
+
24
+ import {
25
+ archiveRoot,
26
+ cwdDirName,
27
+ firstEntryId,
28
+ isArchived,
29
+ sessionsRoot,
30
+ twinPaths,
31
+ underRoot,
32
+ } from "./paths.ts";
33
+ import {
34
+ hasName,
35
+ matchScore,
36
+ sortRecords,
37
+ type ParsedQuery,
38
+ } from "./search.ts";
39
+ import {
40
+ readIndex,
41
+ type IndexEntry,
42
+ } from "./state.ts";
43
+ import type {
44
+ ArchiveFilter,
45
+ Scope,
46
+ SessionRecord,
47
+ SessionRelation,
48
+ SortMode,
49
+ } from "./types.ts";
50
+
51
+ /** One row of the picker: a session plus what the tree renderer needs. */
52
+ export interface TreeRow {
53
+ record: SessionRecord;
54
+ /** Nesting level; roots are 0. */
55
+ depth: number;
56
+ /** Nodes in this row's subtree, excluding the row itself (hidden rows included). */
57
+ descendantCount: number;
58
+ /** Nodes below this row that the current view can actually render. */
59
+ visibleDescendantCount: number;
60
+ /** True when no later sibling follows at the same level. */
61
+ isLast: boolean;
62
+ /** Per ancestor level: whether that level's vertical line continues below. */
63
+ ancestorContinues: boolean[];
64
+ }
65
+
66
+ /** One progress update emitted while a scope is loading. */
67
+ export type LoadPhase = "live" | "archive";
68
+
69
+ export interface LoadProgress {
70
+ /** Sessions (live) or archive directories loaded so far. */
71
+ loaded: number;
72
+ /** Total sessions (live) or archive directories. */
73
+ total: number;
74
+ phase: LoadPhase;
75
+ }
76
+
77
+ export interface LoadSessionsOptions {
78
+ signal?: AbortSignal;
79
+ /** Called with the merged records after each batch; safe to render directly. */
80
+ onProgress?: (records: SessionRecord[], progress: LoadProgress) => void;
81
+ }
82
+
83
+ /** `SessionManager.listAll`'s progress callback, without importing its type. */
84
+ type ListProgress = (loaded: number, total: number, partial?: readonly SessionInfo[]) => void;
85
+
86
+ /** Session infos from one directory; a missing or unreadable directory yields none. */
87
+ async function listAllInDir(
88
+ dir: string,
89
+ onProgress?: ListProgress,
90
+ signal?: AbortSignal,
91
+ ): Promise<SessionInfo[]> {
92
+ try {
93
+ return await SessionManager.listAll(dir, onProgress, signal);
94
+ } catch {
95
+ signal?.throwIfAborted();
96
+ return [];
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Immediate subdirectories of the archive root. `listAll` is not recursive, so
102
+ * the `all` scope has to visit them one by one; an unreadable root yields none.
103
+ */
104
+ function archiveDirs(): string[] {
105
+ try {
106
+ return readdirSync(archiveRoot(), { withFileTypes: true })
107
+ .filter((entry) => entry.isDirectory())
108
+ .map((entry) => join(archiveRoot(), entry.name));
109
+ } catch {
110
+ return [];
111
+ }
112
+ }
113
+
114
+ /** Archive index key of a file: its path relative to the archive root. */
115
+ function indexKey(file: string): string {
116
+ return join(basename(dirname(file)), basename(file));
117
+ }
118
+
119
+ /** A stored ISO timestamp, or undefined when it is missing or unparseable. */
120
+ function toDate(value: unknown): Date | undefined {
121
+ if (typeof value !== "string") return undefined;
122
+ const date = new Date(value);
123
+ return Number.isNaN(date.getTime()) ? undefined : date;
124
+ }
125
+
126
+ /**
127
+ * When an archived session was archived. The index is best effort, so a
128
+ * session it does not know about (or an index that failed to parse) falls back
129
+ * to the file's own modification time.
130
+ */
131
+ function archivedAt(index: Record<string, IndexEntry>, info: SessionInfo): Date {
132
+ return toDate(index[indexKey(info.path)]?.archivedAt) ?? info.modified;
133
+ }
134
+
135
+ /**
136
+ * Fork/clone or subagent, from file content. A fork copies the parent's
137
+ * entries, so its first non-header entry keeps the parent's id; a subagent
138
+ * starts a fresh session (even when `inherit_context` feeds it parent text),
139
+ * so its first entry id differs. A missing parent file falls back to
140
+ * `subagent`, which keeps internal sessions out of the default view.
141
+ */
142
+ function relationOf(info: SessionInfo): SessionRelation | undefined {
143
+ const parentPath = info.parentSessionPath;
144
+ if (!parentPath) return undefined;
145
+ const parentFile = twinPaths(parentPath).find((path) => existsSync(path));
146
+ if (parentFile === undefined) return "subagent";
147
+ const childId = firstEntryId(info.path);
148
+ const parentId = firstEntryId(parentFile);
149
+ if (childId === undefined && parentId === undefined) return "fork";
150
+ return childId !== undefined && childId === parentId ? "fork" : "subagent";
151
+ }
152
+
153
+ /** Deduplicate infos into records: live paths win, then session ids. */
154
+ function toRecords(infos: readonly SessionInfo[], index: Record<string, IndexEntry>): SessionRecord[] {
155
+ const records = new Map<string, SessionRecord>();
156
+ const seenIds = new Set<string>();
157
+ for (const info of infos) {
158
+ if (underRoot(sessionsRoot(), info.path) === undefined && underRoot(archiveRoot(), info.path) === undefined) {
159
+ continue;
160
+ }
161
+ const key = resolve(info.path);
162
+ if (records.has(key)) continue;
163
+ if (info.id) {
164
+ if (seenIds.has(info.id)) continue;
165
+ seenIds.add(info.id);
166
+ }
167
+ const archived = isArchived(info.path);
168
+ records.set(key, {
169
+ info,
170
+ archived,
171
+ // A live file has no archive date of its own; a stale archived twin's
172
+ // index entry must not stand in for it.
173
+ archiveDate: archived ? archivedAt(index, info) : info.modified,
174
+ relation: relationOf(info),
175
+ });
176
+ }
177
+ return [...records.values()];
178
+ }
179
+
180
+ function byModified(a: SessionRecord, b: SessionRecord): number {
181
+ return b.info.modified.getTime() - a.info.modified.getTime();
182
+ }
183
+
184
+ /**
185
+ * Load every session the scope covers, live and archived, newest first.
186
+ *
187
+ * Live sessions are published as `SessionManager.listAll` discovers them, then
188
+ * archive directories are merged one at a time, so the picker can render rows
189
+ * while the scope is still loading. Only paths under the live or archive root
190
+ * are kept. A session can exist twice - as a live file and as the archived copy
191
+ * pi kept writing after the archive - and must still be one row, so the live
192
+ * copy (listed first) wins over its archived twin.
193
+ */
194
+ export async function loadSessions(
195
+ scope: Scope,
196
+ cwd: string,
197
+ options: LoadSessionsOptions = {},
198
+ ): Promise<SessionRecord[]> {
199
+ const { signal, onProgress } = options;
200
+ const cwdDir = cwdDirName(cwd);
201
+ const index = readIndex();
202
+ let live: SessionInfo[] = [];
203
+ let archived: SessionInfo[] = [];
204
+
205
+ const publish = (progress: LoadProgress): void => {
206
+ if (!onProgress) return;
207
+ onProgress(toRecords([...live, ...archived], index).sort(byModified), progress);
208
+ };
209
+
210
+ const liveProgress: ListProgress = (loaded, total, partial) => {
211
+ if (partial === undefined) return;
212
+ live = [...partial];
213
+ publish({ loaded, total, phase: "live" });
214
+ };
215
+
216
+ signal?.throwIfAborted();
217
+ if (scope === "current") {
218
+ live = await listAllInDir(join(sessionsRoot(), cwdDir), liveProgress, signal);
219
+ } else {
220
+ try {
221
+ live = await SessionManager.listAll(liveProgress, signal);
222
+ } catch {
223
+ signal?.throwIfAborted();
224
+ live = [];
225
+ }
226
+ }
227
+ publish({ loaded: live.length, total: live.length, phase: "live" });
228
+
229
+ const dirs = scope === "current" ? [join(archiveRoot(), cwdDir)] : archiveDirs();
230
+ for (const [dirIndex, dir] of dirs.entries()) {
231
+ signal?.throwIfAborted();
232
+ archived = [...archived, ...await listAllInDir(dir, undefined, signal)];
233
+ publish({ loaded: dirIndex + 1, total: dirs.length, phase: "archive" });
234
+ }
235
+
236
+ signal?.throwIfAborted();
237
+ return toRecords([...live, ...archived], index).sort(byModified);
238
+ }
239
+
240
+ /**
241
+ * Apply the picker's filters: archive state first (by default only live
242
+ * sessions are shown), then "named only", then the query. A missing query
243
+ * keeps everything; an unusable `re:` query matches nothing.
244
+ */
245
+ export function filterRecords(
246
+ records: SessionRecord[],
247
+ options: { archiveFilter?: ArchiveFilter; namedOnly?: boolean; query?: ParsedQuery } = {},
248
+ ): SessionRecord[] {
249
+ const { archiveFilter = "active", namedOnly = false, query } = options;
250
+ return records.filter((record) => {
251
+ if (archiveFilter === "active" && record.archived) return false;
252
+ if (archiveFilter === "archived" && !record.archived) return false;
253
+ if (namedOnly && !hasName(record.info)) return false;
254
+ return query === undefined || matchScore(record.info, query) !== undefined;
255
+ });
256
+ }
257
+
258
+ /**
259
+ * The record a session hangs off. The recorded path is tried first, then the
260
+ * same file in the other tree, so a live fork keeps its archived parent and an
261
+ * archived fork keeps its restored one. An unresolvable parent makes a root.
262
+ */
263
+ function findParent(
264
+ record: SessionRecord,
265
+ byPath: ReadonlyMap<string, SessionRecord>,
266
+ ): SessionRecord | undefined {
267
+ const parentPath = record.info.parentSessionPath;
268
+ if (!parentPath) return undefined;
269
+ for (const candidate of twinPaths(parentPath)) {
270
+ const parent = byPath.get(resolve(candidate));
271
+ if (parent !== undefined && parent !== record) return parent;
272
+ }
273
+ return undefined;
274
+ }
275
+
276
+ interface SubtreeStats {
277
+ /** Nodes below the record, excluding it. */
278
+ count: number;
279
+ /** Newest `modified` in the subtree, in epoch milliseconds. */
280
+ latest: number;
281
+ }
282
+
283
+ /** Subtree sizes over every loaded record, hidden or not. */
284
+ export function descendantCounts(records: SessionRecord[]): Map<SessionRecord, number> {
285
+ const byPath = new Map<string, SessionRecord>();
286
+ for (const record of records) byPath.set(resolve(record.info.path), record);
287
+ const children = new Map<SessionRecord, SessionRecord[]>();
288
+ for (const record of records) {
289
+ const parent = findParent(record, byPath);
290
+ if (parent === undefined) continue;
291
+ const siblings = children.get(parent);
292
+ if (siblings) siblings.push(record);
293
+ else children.set(parent, [record]);
294
+ }
295
+ const counts = new Map<SessionRecord, number>();
296
+ const onPath = new Set<SessionRecord>();
297
+ const measure = (record: SessionRecord): number => {
298
+ const done = counts.get(record);
299
+ if (done !== undefined) return done;
300
+ onPath.add(record);
301
+ let count = 0;
302
+ for (const child of children.get(record) ?? []) {
303
+ if (onPath.has(child)) continue;
304
+ count += 1 + measure(child);
305
+ }
306
+ onPath.delete(record);
307
+ counts.set(record, count);
308
+ return count;
309
+ };
310
+ for (const record of records) measure(record);
311
+ return counts;
312
+ }
313
+
314
+ /**
315
+ * Every loaded record below `root`, in DFS order, the root excluded.
316
+ *
317
+ * The traversal uses the same parent resolution as `descendantCounts`, so a
318
+ * child whose parent lives in the other tree (the live/archive twin) still
319
+ * hangs off `root`. `onPath` breaks a cycle a corrupt `parentSession` could
320
+ * create.
321
+ */
322
+ export function descendantRecords(records: SessionRecord[], root: SessionRecord): SessionRecord[] {
323
+ const byPath = new Map<string, SessionRecord>();
324
+ for (const record of records) byPath.set(resolve(record.info.path), record);
325
+ const children = new Map<SessionRecord, SessionRecord[]>();
326
+ for (const record of records) {
327
+ const parent = findParent(record, byPath);
328
+ if (parent === undefined) continue;
329
+ const siblings = children.get(parent);
330
+ if (siblings) siblings.push(record);
331
+ else children.set(parent, [record]);
332
+ }
333
+ const result: SessionRecord[] = [];
334
+ const onPath = new Set<SessionRecord>([root]);
335
+ const walk = (record: SessionRecord): void => {
336
+ for (const child of children.get(record) ?? []) {
337
+ if (onPath.has(child)) continue;
338
+ onPath.add(child);
339
+ result.push(child);
340
+ walk(child);
341
+ onPath.delete(child);
342
+ }
343
+ };
344
+ walk(root);
345
+ return result;
346
+ }
347
+
348
+ /** Paths of records that have at least one child in this set. */
349
+ export function parentPaths(records: SessionRecord[]): Set<string> {
350
+ const byPath = new Map<string, SessionRecord>();
351
+ for (const record of records) byPath.set(resolve(record.info.path), record);
352
+ const paths = new Set<string>();
353
+ for (const record of records) {
354
+ const parent = findParent(record, byPath);
355
+ if (parent !== undefined) paths.add(parent.info.path);
356
+ }
357
+ return paths;
358
+ }
359
+
360
+ /** Build the nested forest: roots by the active sort, children only when expanded. */
361
+ function forest(
362
+ ordered: SessionRecord[],
363
+ expand: ReadonlySet<string>,
364
+ sort: SortMode,
365
+ counts?: ReadonlyMap<SessionRecord, number>,
366
+ ): TreeRow[] {
367
+ const byPath = new Map<string, SessionRecord>();
368
+ for (const record of ordered) byPath.set(resolve(record.info.path), record);
369
+
370
+ const children = new Map<SessionRecord, SessionRecord[]>();
371
+ const roots: SessionRecord[] = [];
372
+ for (const record of ordered) {
373
+ const parent = findParent(record, byPath);
374
+ if (parent === undefined) {
375
+ roots.push(record);
376
+ continue;
377
+ }
378
+ const siblings = children.get(parent);
379
+ if (siblings) siblings.push(record);
380
+ else children.set(parent, [record]);
381
+ }
382
+
383
+ const stats = new Map<SessionRecord, SubtreeStats>();
384
+ const onPath = new Set<SessionRecord>();
385
+
386
+ /** Subtree size and newest activity, computed once per record. */
387
+ function measure(record: SessionRecord): SubtreeStats {
388
+ const done = stats.get(record);
389
+ if (done) return done;
390
+ onPath.add(record);
391
+ let count = 0;
392
+ let latest = record.info.modified.getTime();
393
+ for (const child of children.get(record) ?? []) {
394
+ // A parent chain that loops back on itself must not recurse forever.
395
+ if (onPath.has(child)) continue;
396
+ const sub = measure(child);
397
+ count += 1 + sub.count;
398
+ latest = Math.max(latest, sub.latest);
399
+ }
400
+ onPath.delete(record);
401
+ const fresh = { count, latest };
402
+ stats.set(record, fresh);
403
+ return fresh;
404
+ }
405
+
406
+ for (const record of ordered) measure(record);
407
+
408
+ const latestOf = (record: SessionRecord): number =>
409
+ stats.get(record)?.latest ?? record.info.modified.getTime();
410
+ const byLatest = (a: SessionRecord, b: SessionRecord): number => latestOf(b) - latestOf(a);
411
+ const byModified = (a: SessionRecord, b: SessionRecord): number =>
412
+ b.info.modified.getTime() - a.info.modified.getTime();
413
+ // Threaded order is by subtree activity; recent/relevance keep each sibling
414
+ // level in the order `sortRecords` already produced.
415
+ const compare = sort === "threaded" ? byLatest : byModified;
416
+
417
+ const rows: TreeRow[] = [];
418
+ const emitted = new Set<SessionRecord>();
419
+
420
+ function emit(record: SessionRecord, depth: number, isLast: boolean, ancestorContinues: boolean[]): void {
421
+ if (emitted.has(record)) return;
422
+ emitted.add(record);
423
+ const visible = stats.get(record)?.count ?? 0;
424
+ rows.push({
425
+ record,
426
+ depth,
427
+ descendantCount: counts?.get(record) ?? visible,
428
+ visibleDescendantCount: visible,
429
+ isLast,
430
+ ancestorContinues,
431
+ });
432
+ if (!expand.has(record.info.path)) return;
433
+ const kids = [...(children.get(record) ?? [])].sort(compare);
434
+ for (const [index, child] of kids.entries()) {
435
+ // Native flattenSessionTree only draws a continuation column below
436
+ // depth 0; a root's own isLast must not leak into its children.
437
+ emit(child, depth + 1, index === kids.length - 1, [
438
+ ...ancestorContinues,
439
+ depth > 0 ? !isLast : false,
440
+ ]);
441
+ }
442
+ }
443
+
444
+ const orderedRoots = [...roots].sort(compare);
445
+ // A chain that loops back on itself never reaches a root: keep those
446
+ // sessions visible as roots of their own instead of silently dropping them.
447
+ const reached = new Set<SessionRecord>();
448
+ const markReached = (record: SessionRecord): void => {
449
+ if (reached.has(record)) return;
450
+ reached.add(record);
451
+ for (const child of children.get(record) ?? []) markReached(child);
452
+ };
453
+ for (const root of orderedRoots) markReached(root);
454
+ for (const record of ordered) {
455
+ if (!reached.has(record)) orderedRoots.push(record);
456
+ }
457
+
458
+ for (const [index, record] of orderedRoots.entries()) {
459
+ emit(record, 0, index === orderedRoots.length - 1, []);
460
+ }
461
+ return rows;
462
+ }
463
+
464
+ /**
465
+ * Rows for the picker. Without a query the child sessions stay nested under
466
+ * their parent and collapsed, regardless of the sort mode; the sort only
467
+ * reorders each sibling level. A query flattens the list into search results.
468
+ */
469
+ export function buildRows(
470
+ records: SessionRecord[],
471
+ options: {
472
+ query: ParsedQuery;
473
+ sort: SortMode;
474
+ expand: ReadonlySet<string>;
475
+ /** Totals over every loaded record, including rows this view hides. */
476
+ descendantCounts?: ReadonlyMap<SessionRecord, number>;
477
+ },
478
+ ): TreeRow[] {
479
+ const { query, sort, expand, descendantCounts: counts } = options;
480
+ const ordered = sortRecords(records, query, sort);
481
+ if (!query.empty) {
482
+ return ordered.map((record) => ({
483
+ record,
484
+ depth: 0,
485
+ descendantCount: counts?.get(record) ?? 0,
486
+ visibleDescendantCount: 0,
487
+ isLast: true,
488
+ ancestorContinues: [],
489
+ }));
490
+ }
491
+ return forest(ordered, expand, sort, counts);
492
+ }
package/src/state.ts ADDED
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Bookkeeping that must survive the session which wrote it.
3
+ *
4
+ * Two files are involved:
5
+ * - `<agent>/sessions-archive/index.json` remembers the name, cwd and archive
6
+ * time of every session file this extension moved, keyed by its
7
+ * archive-relative path.
8
+ * - `<agent>/pi-sessions-state.json` holds extension-wide state, currently
9
+ * only the sessions whose archiving was deferred until shutdown.
10
+ *
11
+ * Reads are deliberately forgiving: a missing, unreadable or corrupt file
12
+ * yields an empty record so a broken index can never break `/sessions`.
13
+ */
14
+ import {
15
+ mkdirSync,
16
+ readFileSync,
17
+ renameSync,
18
+ writeFileSync,
19
+ } from "node:fs";
20
+ import { dirname, join } from "node:path";
21
+
22
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
23
+
24
+ import { archiveRoot } from "./paths.ts";
25
+
26
+ export interface IndexEntry {
27
+ name: string;
28
+ cwd: string;
29
+ archivedAt: string;
30
+ id?: string;
31
+ }
32
+
33
+ export interface PendingEntry {
34
+ path: string;
35
+ cwd: string;
36
+ requestedAt: string;
37
+ }
38
+
39
+ /**
40
+ * Archive-relative path of a session file maps to the metadata recorded when
41
+ * it was archived.
42
+ */
43
+ export function indexPath(): string {
44
+ return join(archiveRoot(), "index.json");
45
+ }
46
+
47
+ /** Extension-wide state shared by the current and any later session. */
48
+ export function statePath(): string {
49
+ return join(getAgentDir(), "pi-sessions-state.json");
50
+ }
51
+
52
+ function isRecord(value: unknown): value is Record<string, unknown> {
53
+ return typeof value === "object" && value !== null && !Array.isArray(value);
54
+ }
55
+
56
+ /** Parse `file` as a JSON object; anything else becomes an empty record. */
57
+ function readJsonObject(file: string): Record<string, unknown> {
58
+ try {
59
+ const parsed: unknown = JSON.parse(readFileSync(file, "utf8"));
60
+ return isRecord(parsed) ? parsed : {};
61
+ } catch {
62
+ return {};
63
+ }
64
+ }
65
+
66
+ /** Keep only object-valued entries, so one corrupt entry cannot poison the rest. */
67
+ function recordsOf<T extends object>(value: unknown): Record<string, T> {
68
+ if (!isRecord(value)) return {};
69
+ const records: Record<string, T> = {};
70
+ for (const [key, entry] of Object.entries(value)) {
71
+ if (isRecord(entry)) records[key] = entry as unknown as T;
72
+ }
73
+ return records;
74
+ }
75
+
76
+ /** Write `value` as JSON: create parents, write a sibling temp file, rename. */
77
+ export function writeJsonAtomic(file: string, value: unknown): void {
78
+ mkdirSync(dirname(file), { recursive: true });
79
+ const tmp = `${file}.tmp`;
80
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, "utf8");
81
+ renameSync(tmp, file);
82
+ }
83
+
84
+ export function readIndex(): Record<string, IndexEntry> {
85
+ return recordsOf<IndexEntry>(readJsonObject(indexPath()));
86
+ }
87
+
88
+ export function writeIndex(entries: Record<string, IndexEntry>): void {
89
+ writeJsonAtomic(indexPath(), entries);
90
+ }
91
+
92
+ function pendingOf(state: Record<string, unknown>): Record<string, PendingEntry> {
93
+ return recordsOf<PendingEntry>(state.pendingArchive);
94
+ }
95
+
96
+ /** Sessions whose archiving was requested while they were still running. */
97
+ export function readPending(): Record<string, PendingEntry> {
98
+ return pendingOf(readJsonObject(statePath()));
99
+ }
100
+
101
+ /** Record one deferred archive, leaving every other state key untouched. */
102
+ export function setPending(id: string, entry: PendingEntry): void {
103
+ const state = readJsonObject(statePath());
104
+ state.pendingArchive = { ...pendingOf(state), [id]: entry };
105
+ writeJsonAtomic(statePath(), state);
106
+ }
107
+
108
+ /** Forget one deferred archive, leaving every other state key untouched. */
109
+ export function clearPending(id: string): void {
110
+ const state = readJsonObject(statePath());
111
+ const pending = pendingOf(state);
112
+ delete pending[id];
113
+ state.pendingArchive = pending;
114
+ writeJsonAtomic(statePath(), state);
115
+ }
package/src/types.ts ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Types shared by the loader, the search and the picker.
3
+ *
4
+ * They live here rather than beside their main consumer (`sessions.ts`) so
5
+ * `search.ts` and `sessions.ts` can both use them without importing each
6
+ * other.
7
+ */
8
+ import type { SessionInfo } from "@earendil-works/pi-coding-agent";
9
+
10
+ /** Which sessions the picker loads: this working directory or every one. */
11
+ export type Scope = "current" | "all";
12
+
13
+ /**
14
+ * How matched sessions are ordered:
15
+ * - `threaded` nests child sessions under their parent and otherwise ranks by relevance,
16
+ * - `recent` keeps the newest first,
17
+ * - `relevance` ranks by name, then message text, then fuzzy match.
18
+ */
19
+ export type SortMode = "threaded" | "recent" | "relevance";
20
+
21
+ /** Which archive states the picker shows. */
22
+ export type ArchiveFilter = "active" | "archived" | "all";
23
+
24
+ /**
25
+ * How the picker expands the tree:
26
+ * - `collapsed` shows no children,
27
+ * - `children` expands fork/clone subtrees and hides subagent rows,
28
+ * - `all` expands everything, subagents included.
29
+ */
30
+ export type ExpansionMode = "collapsed" | "children" | "all";
31
+
32
+ /**
33
+ * How a child session came to be, from its file content:
34
+ * - `fork`: a clone/fork copied this session's parent entries,
35
+ * - `subagent`: a fresh subagent session (possibly with textual inherited context).
36
+ */
37
+ export type SessionRelation = "fork" | "subagent";
38
+
39
+ /** A loaded session file plus what the archive tree knows about it. */
40
+ export interface SessionRecord {
41
+ info: SessionInfo;
42
+ archived: boolean;
43
+ /** Archive time from the index, falling back to `info.modified`. */
44
+ archiveDate: Date;
45
+ /** Set on child sessions only; a root has no relation. */
46
+ relation?: SessionRelation;
47
+ }