pi-braid 0.43.7 → 0.43.9

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 (64) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/TOOLS.md +1 -1
  3. package/build-info.json +4 -4
  4. package/dist/extensions/core/prompt-builder/tool-guidelines.js +1 -1
  5. package/dist/extensions/core/skills-tool/auto-inject.d.ts +21 -0
  6. package/dist/extensions/core/skills-tool/auto-inject.js +105 -1
  7. package/dist/extensions/core/skills-tool/index.js +20 -2
  8. package/dist/extensions/core/skills-tool/loading-guidance.d.ts +4 -1
  9. package/dist/extensions/core/skills-tool/loading-guidance.js +4 -1
  10. package/dist/extensions/core/skills-tool/session-records.d.ts +107 -9
  11. package/dist/extensions/core/skills-tool/session-records.js +141 -5
  12. package/dist/extensions/enforcement/handlers/analysis/dreamer-handler.js +5 -1
  13. package/dist/extensions/enforcement/handlers/register-tool-call.js +5 -2
  14. package/dist/extensions/enforcement/verification-judge.d.ts +7 -0
  15. package/dist/extensions/enforcement/verification-judge.js +28 -21
  16. package/dist/extensions/memory/session-recall/ask.d.ts +95 -0
  17. package/dist/extensions/memory/session-recall/ask.js +376 -0
  18. package/dist/extensions/memory/session-recall/corpus-index.d.ts +200 -0
  19. package/dist/extensions/memory/session-recall/corpus-index.js +480 -0
  20. package/dist/extensions/memory/session-recall/index.js +173 -21
  21. package/dist/extensions/memory/session-recall/search.d.ts +29 -0
  22. package/dist/extensions/memory/session-recall/search.js +42 -9
  23. package/dist/lib/ai/payload-hygiene.d.ts +3 -0
  24. package/dist/lib/ai/payload-hygiene.js +34 -2
  25. package/dist/lib/config/braid-paths.d.ts +4 -0
  26. package/dist/lib/config/braid-paths.js +6 -0
  27. package/dist/lib/config/braid-settings.d.ts +44 -0
  28. package/dist/lib/config/braid-settings.js +41 -0
  29. package/dist/lib/detection/tool-loop-detector.d.ts +95 -46
  30. package/dist/lib/detection/tool-loop-detector.js +288 -180
  31. package/dist/lib/memory/constants.d.ts +38 -0
  32. package/dist/lib/memory/constants.js +196 -0
  33. package/dist/lib/memory/index.js +49 -10
  34. package/dist/lib/memory/lifecycle.d.ts +8 -0
  35. package/dist/lib/memory/lifecycle.js +43 -18
  36. package/dist/lib/reasoning/dreamer.d.ts +2 -1
  37. package/dist/lib/reasoning/dreamer.js +12 -7
  38. package/docs/LOCAL_DEV.md +1 -1
  39. package/docs/SETUP.md +2 -0
  40. package/package.json +1 -1
  41. package/src/extensions/core/AGENTS.md +3 -2
  42. package/src/extensions/core/prompt-builder/tool-guidelines.ts +1 -1
  43. package/src/extensions/core/skills-tool/auto-inject.ts +118 -1
  44. package/src/extensions/core/skills-tool/index.ts +21 -1
  45. package/src/extensions/core/skills-tool/loading-guidance.ts +4 -1
  46. package/src/extensions/core/skills-tool/session-records.ts +201 -9
  47. package/src/extensions/enforcement/handlers/analysis/dreamer-handler.ts +5 -1
  48. package/src/extensions/enforcement/handlers/register-tool-call.ts +5 -2
  49. package/src/extensions/enforcement/verification-judge.ts +32 -25
  50. package/src/extensions/memory/AGENTS.md +2 -2
  51. package/src/extensions/memory/session-recall/AGENTS.md +92 -18
  52. package/src/extensions/memory/session-recall/ask.ts +435 -0
  53. package/src/extensions/memory/session-recall/corpus-index.ts +609 -0
  54. package/src/extensions/memory/session-recall/index.ts +202 -21
  55. package/src/extensions/memory/session-recall/search.ts +61 -10
  56. package/src/lib/ai/payload-hygiene.ts +47 -3
  57. package/src/lib/config/braid-paths.ts +7 -0
  58. package/src/lib/config/braid-settings.ts +93 -3
  59. package/src/lib/detection/AGENTS.md +8 -7
  60. package/src/lib/detection/tool-loop-detector.ts +339 -195
  61. package/src/lib/memory/constants.ts +202 -0
  62. package/src/lib/memory/index.ts +59 -8
  63. package/src/lib/memory/lifecycle.ts +50 -16
  64. package/src/lib/reasoning/dreamer.ts +13 -6
@@ -0,0 +1,609 @@
1
+ /**
2
+ * Session corpus index - the user's own turns, extracted once and stored as a
3
+ * derived population.
4
+ *
5
+ * The transcript corpus is measured in gigabytes while every user message in it
6
+ * is measured in megabytes: the human's words are a fraction of one percent of
7
+ * the archive, and the rest is the agent's own reasoning and tool output. A
8
+ * grep over the archive therefore drowns that fraction in noise, and no tool
9
+ * reads it as a population. This module is the population: one row per user
10
+ * turn, carrying the session file, the session id, the project label, the entry
11
+ * timestamp, the line number in the session file, and the text as typed.
12
+ *
13
+ * Derived, never authoritative: every shard is rebuildable from the session
14
+ * files alone. One shard per project under `corpusIndexDir()`, so a query can
15
+ * read one project or all of them without walking a transcript tree.
16
+ *
17
+ * Two properties the readers depend on:
18
+ *
19
+ * - **Fail closed.** A shard is accepted whole or not at all. A manifest that
20
+ * does not parse, a format this build does not know, a row count that
21
+ * disagrees with the manifest, or a row that does not parse makes the shard
22
+ * UNREADABLE - the caller must say it cannot answer rather than answer from
23
+ * half a store. `loadCorpusIndex` reports which shard and which defect.
24
+ * - **Excluded by construction.** Only `message` entries with role `user`
25
+ * contribute text. Assistant turns, tool calls, tool results and
26
+ * extension-injected `custom_message` entries never enter a row, so no key,
27
+ * no tool argument and no environment value can be retrieved from the index.
28
+ * Tool results arrive as user-role messages with no text block, so the text
29
+ * filter drops them without a role list.
30
+ *
31
+ * What is NOT indexed: the compaction archives under `<session dir>/archives/`.
32
+ * An envelope there is a second copy of messages the session body already
33
+ * carries (writeOriginalsArchive stores the pre-compaction originals), so
34
+ * indexing both would count the same words twice.
35
+ */
36
+
37
+ import { createHash } from "node:crypto";
38
+ import { readFile, readdir, rename, stat, writeFile, mkdir } from "node:fs/promises";
39
+ import { basename, isAbsolute, join } from "node:path";
40
+ import { corpusIndexDir } from "../../../lib/config/braid-paths.js";
41
+ import { projectFromPath, walkJsonlFiles } from "./search.js";
42
+
43
+ /** Shard layout version. A shard written by another format is unreadable, not
44
+ * migrated: the build regenerates it from the sessions. */
45
+ export const CORPUS_INDEX_FORMAT = 1;
46
+
47
+ /** Directory-name segment that holds compaction envelopes, never session bodies. */
48
+ const ARCHIVE_SEGMENT = /(^|[/\\])archives[/\\]/;
49
+
50
+ /** One user turn. */
51
+ export interface CorpusTurn {
52
+ /** Absolute path of the session file the turn was read from. */
53
+ session: string;
54
+ /** pi's session id, taken from the file name; the short cite handle. */
55
+ session_id: string;
56
+ /** Project label the session ran in (`projectFromPath`). */
57
+ project: string;
58
+ /** Entry timestamp, ISO-8601 (the file's date at midnight when absent). */
59
+ ts: string;
60
+ /** 1-based line number inside the session file. */
61
+ line: number;
62
+ /** The user's words, verbatim. */
63
+ text: string;
64
+ }
65
+
66
+ /** One source session file as the shard's manifest records it. */
67
+ export interface CorpusShardFile {
68
+ path: string;
69
+ /** Source mtime in ms; with `size`, the incremental key. */
70
+ mtimeMs: number;
71
+ size: number;
72
+ turns: number;
73
+ }
74
+
75
+ /** The shard's first line. Everything the reader needs to accept or refuse it. */
76
+ export interface CorpusShardManifest {
77
+ kind: "manifest";
78
+ format: number;
79
+ project: string;
80
+ built_at: string;
81
+ /** Source session files the shard covers. */
82
+ sessions: number;
83
+ /** Rows written; row count must equal this. */
84
+ turns: number;
85
+ /** Summed UTF-8 bytes of the row texts. */
86
+ bytes: number;
87
+ files: CorpusShardFile[];
88
+ }
89
+
90
+ export interface LoadedShard {
91
+ path: string;
92
+ manifest: CorpusShardManifest;
93
+ turns: CorpusTurn[];
94
+ }
95
+
96
+ export type CorpusLoad =
97
+ | { ok: true; dir: string; shards: LoadedShard[] }
98
+ | { ok: false; dir: string; reason: string; shards: string[] };
99
+
100
+ export interface BuildOptions {
101
+ sessionsDir: string;
102
+ indexDir?: string;
103
+ now?: () => Date;
104
+ /** Ignore existing shards and re-parse every session file. */
105
+ rebuild?: boolean;
106
+ /** Structural sink for `scripts/build-corpus-index.mjs --verbose`. */
107
+ progress?: (line: string) => void;
108
+ }
109
+
110
+ export interface BuildReport {
111
+ index_dir: string;
112
+ projects: number;
113
+ shards: number;
114
+ sessions: number;
115
+ turns: number;
116
+ bytes: number;
117
+ /** Session files parsed this run. */
118
+ parsed_files: number;
119
+ /** Session files whose rows were carried over from an unchanged shard. */
120
+ reused_files: number;
121
+ /** Session files the shard dropped because they are gone from disk. */
122
+ removed_files: number;
123
+ /** Unreadable session files, by path. */
124
+ skipped: string[];
125
+ elapsed_ms: number;
126
+ }
127
+
128
+ /** Thrown by the shard reader; the message names the shard and the defect. */
129
+ export class CorpusShardError extends Error {
130
+ constructor(
131
+ readonly shardPath: string,
132
+ readonly defect: string,
133
+ ) {
134
+ super(`${shardPath}: ${defect}`);
135
+ this.name = "CorpusShardError";
136
+ }
137
+ }
138
+
139
+ /** pi's session file name is `<iso-ts>_<session-id>.jsonl`; a shard cites the id. */
140
+ const SESSION_ID_IN_NAME = /_([0-9a-z][0-9a-z-]{7,})\.jsonl$/i;
141
+
142
+ /**
143
+ * File-name stem for one project's shard.
144
+ *
145
+ * The project label is decoded from an encoded directory name, which is lossy
146
+ * (`-` is both a separator and a legal character inside a name), so two
147
+ * different projects can decode to one label and two labels can sanitize to one
148
+ * stem. The digest of the label keeps one shard per project; the readable
149
+ * prefix keeps the directory browsable. Every reader goes through here, so a
150
+ * writer and a reader cannot name different files.
151
+ */
152
+ export function shardSlug(project: string): string {
153
+ const safe =
154
+ project
155
+ .replace(/[^a-zA-Z0-9._-]+/g, "-")
156
+ .replace(/-{2,}/g, "-")
157
+ .replace(/^[-.]+|[-.]+$/g, "")
158
+ .slice(0, 80) || "project";
159
+ const digest = createHash("sha256").update(project).digest("hex").slice(0, 8);
160
+ return `${safe}-${digest}`;
161
+ }
162
+
163
+ /** Absolute path of one project's shard. */
164
+ export function shardPath(indexDir: string, project: string): string {
165
+ return join(indexDir, `${shardSlug(project)}.jsonl`);
166
+ }
167
+
168
+ /** The session id a session file name carries, or the file's stem when it carries none. */
169
+ export function sessionIdFromPath(sessionPath: string): string {
170
+ const name = basename(sessionPath);
171
+ const match = SESSION_ID_IN_NAME.exec(name);
172
+ return match?.[1] ?? name.replace(/\.jsonl$/, "");
173
+ }
174
+
175
+ /** The `YYYY-MM-DD` date a session file name starts with, or null. */
176
+ function dateFromName(sessionPath: string): string | null {
177
+ const match = basename(sessionPath).match(/^(\d{4}-\d{2}-\d{2})T/);
178
+ return match?.[1] ?? null;
179
+ }
180
+
181
+ /** Text of a message's content: a string, or the text blocks joined. */
182
+ function textOfContent(content: unknown): string {
183
+ if (typeof content === "string") return content;
184
+ if (!Array.isArray(content)) return "";
185
+ return content
186
+ .filter(
187
+ (block): block is { type?: unknown; text?: unknown } => !!block && typeof block === "object",
188
+ )
189
+ .filter((block) => block.type === "text" && typeof block.text === "string")
190
+ .map((block) => block.text as string)
191
+ .join(" ");
192
+ }
193
+
194
+ export interface ExtractOptions {
195
+ session: string;
196
+ project: string;
197
+ /** Fallback timestamp for entries that carry none. */
198
+ fileDate: string | null;
199
+ }
200
+
201
+ /**
202
+ * Every user turn in one session body, in file order.
203
+ *
204
+ * A turn is a `message` entry whose role is `user` and whose content carries
205
+ * text. The role alone is not enough: a tool result is delivered as a
206
+ * user-role message with `tool_result` blocks and no text, and a thought or a
207
+ * blank paste carries no words worth indexing. Blank text is dropped here so
208
+ * the corpus holds only what the human actually typed.
209
+ */
210
+ export function extractUserTurns(content: string, opts: ExtractOptions): CorpusTurn[] {
211
+ const sessionId = sessionIdFromPath(opts.session);
212
+ const fallbackTs = opts.fileDate ? `${opts.fileDate}T00:00:00.000Z` : "";
213
+ const turns: CorpusTurn[] = [];
214
+ const lines = content.split("\n");
215
+ for (let i = 0; i < lines.length; i++) {
216
+ const line = lines[i];
217
+ if (!line || !line.includes('"user"')) continue;
218
+ let entry: {
219
+ type?: unknown;
220
+ timestamp?: unknown;
221
+ message?: { role?: unknown; content?: unknown };
222
+ };
223
+ try {
224
+ entry = JSON.parse(line);
225
+ } catch {
226
+ continue;
227
+ }
228
+ if (entry?.type !== "message") continue;
229
+ if (entry.message?.role !== "user") continue;
230
+ const text = textOfContent(entry.message.content);
231
+ if (!text.trim()) continue;
232
+ turns.push({
233
+ session: opts.session,
234
+ session_id: sessionId,
235
+ project: opts.project,
236
+ ts: typeof entry.timestamp === "string" ? entry.timestamp : fallbackTs,
237
+ line: i + 1,
238
+ text,
239
+ });
240
+ }
241
+ return turns;
242
+ }
243
+
244
+ function parseManifest(line: string, shard: string): CorpusShardManifest {
245
+ let parsed: unknown;
246
+ try {
247
+ parsed = JSON.parse(line);
248
+ } catch {
249
+ throw new CorpusShardError(shard, "first line is not JSON (truncated or foreign file)");
250
+ }
251
+ const manifest = parsed as Partial<CorpusShardManifest> | null;
252
+ if (!manifest || typeof manifest !== "object") {
253
+ throw new CorpusShardError(shard, "first line is not an object");
254
+ }
255
+ if (manifest.kind !== "manifest") {
256
+ throw new CorpusShardError(shard, "first line is not a manifest");
257
+ }
258
+ if (manifest.format !== CORPUS_INDEX_FORMAT) {
259
+ throw new CorpusShardError(
260
+ shard,
261
+ `format ${String(manifest.format)} is not the supported format ${CORPUS_INDEX_FORMAT}`,
262
+ );
263
+ }
264
+ if (typeof manifest.project !== "string" || !manifest.project) {
265
+ throw new CorpusShardError(shard, "manifest carries no project");
266
+ }
267
+ if (typeof manifest.built_at !== "string" || Number.isNaN(Date.parse(manifest.built_at))) {
268
+ throw new CorpusShardError(shard, "manifest carries no readable built_at");
269
+ }
270
+ if (typeof manifest.turns !== "number" || !Number.isFinite(manifest.turns)) {
271
+ throw new CorpusShardError(shard, "manifest carries no turn count");
272
+ }
273
+ if (!Array.isArray(manifest.files)) {
274
+ throw new CorpusShardError(shard, "manifest carries no file list");
275
+ }
276
+ return manifest as CorpusShardManifest;
277
+ }
278
+
279
+ function parseRow(line: string, shard: string, manifest: CorpusShardManifest): CorpusTurn {
280
+ let parsed: unknown;
281
+ try {
282
+ parsed = JSON.parse(line);
283
+ } catch {
284
+ throw new CorpusShardError(shard, "a row is not JSON (partial write?)");
285
+ }
286
+ const row = parsed as Partial<CorpusTurn> | null;
287
+ if (!row || typeof row !== "object") {
288
+ throw new CorpusShardError(shard, "a row is not an object");
289
+ }
290
+ if (typeof row.session !== "string" || !isAbsolute(row.session)) {
291
+ throw new CorpusShardError(shard, "a row names no absolute session path");
292
+ }
293
+ if (typeof row.project !== "string" || row.project !== manifest.project) {
294
+ throw new CorpusShardError(shard, "a row names a project the manifest does not");
295
+ }
296
+ if (typeof row.session_id !== "string" || !row.session_id) {
297
+ throw new CorpusShardError(shard, "a row carries no session id");
298
+ }
299
+ if (typeof row.ts !== "string" || Number.isNaN(Date.parse(row.ts))) {
300
+ throw new CorpusShardError(shard, "a row carries no readable timestamp");
301
+ }
302
+ if (typeof row.line !== "number" || !Number.isInteger(row.line) || row.line < 1) {
303
+ throw new CorpusShardError(shard, "a row carries no line number");
304
+ }
305
+ if (typeof row.text !== "string" || !row.text.trim()) {
306
+ throw new CorpusShardError(shard, "a row carries no text");
307
+ }
308
+ return row as CorpusTurn;
309
+ }
310
+
311
+ /** Read and validate one shard. Whole or nothing - see CorpusShardError. */
312
+ export async function readShard(shard: string): Promise<LoadedShard> {
313
+ let raw: string;
314
+ try {
315
+ raw = await readFile(shard, "utf-8");
316
+ } catch (err) {
317
+ throw new CorpusShardError(shard, `unreadable: ${(err as Error).message}`);
318
+ }
319
+ const lines = raw.split("\n").filter((line) => line.trim() !== "");
320
+ if (lines.length === 0) {
321
+ throw new CorpusShardError(shard, "empty file (no manifest)");
322
+ }
323
+ const manifest = parseManifest(lines[0] as string, shard);
324
+ const turns: CorpusTurn[] = [];
325
+ for (let i = 1; i < lines.length; i++) {
326
+ turns.push(parseRow(lines[i] as string, shard, manifest));
327
+ }
328
+ if (turns.length !== manifest.turns) {
329
+ throw new CorpusShardError(
330
+ shard,
331
+ `${turns.length} rows but the manifest records ${manifest.turns} (partial write?)`,
332
+ );
333
+ }
334
+ return { path: shard, manifest, turns };
335
+ }
336
+
337
+ /**
338
+ * Load every shard under the corpus index directory, or refuse.
339
+ *
340
+ * Refusal is the point: a caller that cannot read its evidence must say so.
341
+ * `reason` names the first unreadable shard and its defect; `shards` lists
342
+ * every shard path the directory held, so a refusal can show its population.
343
+ * A `project` filter narrows which shards are read, and a filter that matches
344
+ * nothing is still a refusal - an empty population cannot answer either.
345
+ */
346
+ export async function loadCorpusIndex(
347
+ opts: {
348
+ indexDir?: string;
349
+ project?: string | null;
350
+ } = {},
351
+ ): Promise<CorpusLoad> {
352
+ const dir = opts.indexDir ?? corpusIndexDir();
353
+ let names: string[];
354
+ try {
355
+ names = (await readdir(dir)).filter((name) => name.endsWith(".jsonl")).sort();
356
+ } catch {
357
+ return { ok: false, dir, reason: `no index directory at ${dir}`, shards: [] };
358
+ }
359
+ if (names.length === 0) {
360
+ return { ok: false, dir, reason: `no shards in ${dir}`, shards: [] };
361
+ }
362
+ const paths = names.map((name) => join(dir, name));
363
+ const shards: LoadedShard[] = [];
364
+ for (const path of paths) {
365
+ let shard: LoadedShard;
366
+ try {
367
+ shard = await readShard(path);
368
+ } catch (err) {
369
+ // The reader's contract is a refusal, never a throw: a caller that has to
370
+ // catch to learn "cannot answer" is a caller that will answer anyway.
371
+ const detail = err instanceof CorpusShardError ? err.defect : (err as Error).message;
372
+ return { ok: false, dir, reason: `${path}: ${detail}`, shards: paths };
373
+ }
374
+ const wanted = opts.project ?? null;
375
+ if (wanted && shard.manifest.project !== wanted) continue;
376
+ shards.push(shard);
377
+ }
378
+ if (shards.length === 0) {
379
+ return {
380
+ ok: false,
381
+ dir,
382
+ reason: `no shard matches project "${opts.project}" (shards: ${names.length})`,
383
+ shards: paths,
384
+ };
385
+ }
386
+ return { ok: true, dir, shards };
387
+ }
388
+
389
+ /**
390
+ * How far the index has drifted from the session files.
391
+ *
392
+ * A shard is derived data, so an answer built from it is only as new as the
393
+ * last build. The check is one walk plus one stat per session file: cheap next
394
+ * to the answer, and it lets the result carry its own freshness instead of
395
+ * presenting a stale population as current.
396
+ */
397
+ export interface CorpusFreshness {
398
+ /** Session files the index covers. */
399
+ indexed: number;
400
+ /** Indexed files whose mtime or size moved since the build. */
401
+ changed: number;
402
+ /** Session files present on disk that no shard covers. */
403
+ added: number;
404
+ /** Indexed files that are gone from disk. */
405
+ removed: number;
406
+ /** Newest source mtime seen among changed and added files, ISO-8601. */
407
+ newest_change: string | null;
408
+ }
409
+
410
+ export async function corpusIndexFreshness(
411
+ shards: LoadedShard[],
412
+ sessionsDir: string,
413
+ ): Promise<CorpusFreshness> {
414
+ const indexed = new Map<string, CorpusShardFile>();
415
+ for (const shard of shards) {
416
+ for (const file of shard.manifest.files) indexed.set(file.path, file);
417
+ }
418
+ const onDisk = (await walkJsonlFiles(sessionsDir)).filter((p) => !ARCHIVE_SEGMENT.test(p));
419
+ let changed = 0;
420
+ let added = 0;
421
+ let newest = 0;
422
+ const seen = new Set<string>();
423
+ for (const path of onDisk) {
424
+ seen.add(path);
425
+ const known = indexed.get(path);
426
+ if (!known) {
427
+ added++;
428
+ try {
429
+ newest = Math.max(newest, (await stat(path)).mtimeMs);
430
+ } catch {
431
+ /* vanished between walk and stat */
432
+ }
433
+ continue;
434
+ }
435
+ let info: { mtimeMs: number; size: number };
436
+ try {
437
+ info = await stat(path);
438
+ } catch {
439
+ continue;
440
+ }
441
+ if (info.mtimeMs !== known.mtimeMs || info.size !== known.size) {
442
+ changed++;
443
+ newest = Math.max(newest, info.mtimeMs);
444
+ }
445
+ }
446
+ let removed = 0;
447
+ for (const path of indexed.keys()) if (!seen.has(path)) removed++;
448
+ return {
449
+ indexed: indexed.size,
450
+ changed,
451
+ added,
452
+ removed,
453
+ newest_change: newest > 0 ? new Date(newest).toISOString() : null,
454
+ };
455
+ }
456
+
457
+ interface SourceFile {
458
+ path: string;
459
+ mtimeMs: number;
460
+ size: number;
461
+ }
462
+
463
+ /** Group the session bodies by project label. */
464
+ async function groupByProject(sessionsDir: string): Promise<Map<string, SourceFile[]>> {
465
+ const grouped = new Map<string, SourceFile[]>();
466
+ for (const path of await walkJsonlFiles(sessionsDir)) {
467
+ if (ARCHIVE_SEGMENT.test(path)) continue;
468
+ let info: { mtimeMs: number; size: number };
469
+ try {
470
+ info = await stat(path);
471
+ } catch {
472
+ continue;
473
+ }
474
+ const project = projectFromPath(path);
475
+ const list = grouped.get(project);
476
+ const entry = { path, mtimeMs: info.mtimeMs, size: info.size };
477
+ if (list) list.push(entry);
478
+ else grouped.set(project, [entry]);
479
+ }
480
+ return grouped;
481
+ }
482
+
483
+ function manifestLine(manifest: CorpusShardManifest): string {
484
+ return JSON.stringify(manifest);
485
+ }
486
+
487
+ /** Row text bytes, the figure the shard's manifest records. */
488
+ function textBytes(turns: CorpusTurn[]): number {
489
+ let bytes = 0;
490
+ for (const turn of turns) bytes += Buffer.byteLength(turn.text, "utf8");
491
+ return bytes;
492
+ }
493
+
494
+ /**
495
+ * Walk the session files once and write one shard per project.
496
+ *
497
+ * Incremental by (mtime, size): a session file whose stamp still matches its
498
+ * manifest entry contributes its previous rows without being parsed, so a
499
+ * daily refresh costs what changed rather than the corpus. A shard that cannot
500
+ * be read is not repaired in place - it is rebuilt from its session files,
501
+ * which is the only authority for derived data.
502
+ */
503
+ export async function buildCorpusIndex(opts: BuildOptions): Promise<BuildReport> {
504
+ const started = Date.now();
505
+ const dir = opts.indexDir ?? corpusIndexDir();
506
+ const now = opts.now ?? (() => new Date());
507
+ await mkdir(dir, { recursive: true });
508
+ const grouped = await groupByProject(opts.sessionsDir);
509
+
510
+ const report: BuildReport = {
511
+ index_dir: dir,
512
+ projects: grouped.size,
513
+ shards: 0,
514
+ sessions: 0,
515
+ turns: 0,
516
+ bytes: 0,
517
+ parsed_files: 0,
518
+ reused_files: 0,
519
+ removed_files: 0,
520
+ skipped: [],
521
+ elapsed_ms: 0,
522
+ };
523
+
524
+ for (const [project, files] of grouped) {
525
+ const shard = shardPath(dir, project);
526
+ let previous: LoadedShard | null = null;
527
+ if (!opts.rebuild) {
528
+ try {
529
+ previous = await readShard(shard);
530
+ } catch {
531
+ // A corrupt or absent shard costs a rebuild, never a merge: derived
532
+ // data has one authority, the session files.
533
+ previous = null;
534
+ }
535
+ }
536
+ const previousFiles = new Map<string, CorpusShardFile>();
537
+ const previousRows = new Map<string, CorpusTurn[]>();
538
+ if (previous && previous.manifest.project === project) {
539
+ for (const file of previous.manifest.files) previousFiles.set(file.path, file);
540
+ for (const turn of previous.turns) {
541
+ const rows = previousRows.get(turn.session);
542
+ if (rows) rows.push(turn);
543
+ else previousRows.set(turn.session, [turn]);
544
+ }
545
+ }
546
+
547
+ const turns: CorpusTurn[] = [];
548
+ const manifestFiles: CorpusShardFile[] = [];
549
+ for (const file of files) {
550
+ const known = previousFiles.get(file.path);
551
+ const carried = previousRows.get(file.path);
552
+ if (known && carried && known.mtimeMs === file.mtimeMs && known.size === file.size) {
553
+ for (const turn of carried) turns.push(turn);
554
+ manifestFiles.push({ ...file, turns: carried.length });
555
+ report.reused_files++;
556
+ continue;
557
+ }
558
+ let content: string;
559
+ try {
560
+ content = await readFile(file.path, "utf-8");
561
+ } catch (err) {
562
+ report.skipped.push(`${file.path}: ${(err as Error).message}`);
563
+ continue;
564
+ }
565
+ const extracted = extractUserTurns(content, {
566
+ session: file.path,
567
+ project,
568
+ fileDate: dateFromName(file.path),
569
+ });
570
+ for (const turn of extracted) turns.push(turn);
571
+ manifestFiles.push({ ...file, turns: extracted.length });
572
+ report.parsed_files++;
573
+ }
574
+
575
+ // Files the manifest carried that the walk no longer sees. Counted, not
576
+ // guessed at: a shard that silently kept them would cite a deleted file.
577
+ for (const path of previousFiles.keys()) {
578
+ if (!files.some((file) => file.path === path)) report.removed_files++;
579
+ }
580
+
581
+ turns.sort((a, b) => a.session.localeCompare(b.session) || a.line - b.line);
582
+ const manifest: CorpusShardManifest = {
583
+ kind: "manifest",
584
+ format: CORPUS_INDEX_FORMAT,
585
+ project,
586
+ built_at: now().toISOString(),
587
+ sessions: manifestFiles.length,
588
+ turns: turns.length,
589
+ bytes: textBytes(turns),
590
+ files: manifestFiles,
591
+ };
592
+ const body = [manifestLine(manifest), ...turns.map((turn) => JSON.stringify(turn))].join("\n");
593
+ const temp = `${shard}.tmp-${process.pid}`;
594
+ await writeFile(temp, `${body}\n`, "utf-8");
595
+ await rename(temp, shard);
596
+
597
+ report.shards++;
598
+ report.sessions += manifestFiles.length;
599
+ report.turns += manifest.turns;
600
+ report.bytes += manifest.bytes;
601
+ opts.progress?.(
602
+ `${project}: ${manifest.turns} turns from ${manifestFiles.length} sessions ` +
603
+ `(${(manifest.bytes / 1_048_576).toFixed(2)} MB)`,
604
+ );
605
+ }
606
+
607
+ report.elapsed_ms = Date.now() - started;
608
+ return report;
609
+ }