@theokit/sdk 4.55.0 → 4.57.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/CHANGELOG.md +134 -0
- package/dist/a2a/index.cjs +13 -4
- package/dist/a2a/index.cjs.map +1 -1
- package/dist/a2a/index.d.cts +1 -1
- package/dist/a2a/index.d.ts +1 -1
- package/dist/a2a/index.js +13 -5
- package/dist/a2a/index.js.map +1 -1
- package/dist/a2a/message-bus.d.cts +33 -4
- package/dist/a2a/message-bus.d.ts +33 -4
- package/dist/{agent-R2HOJFZJ.cjs → agent-2T2EJIP6.cjs} +12 -11
- package/dist/{agent-R2HOJFZJ.cjs.map → agent-2T2EJIP6.cjs.map} +1 -1
- package/dist/{agent-HDEVVUBS.js → agent-ZIYCVEZL.js} +11 -10
- package/dist/{agent-HDEVVUBS.js.map → agent-ZIYCVEZL.js.map} +1 -1
- package/dist/agent-session-store-G2BMUZQV.js +7 -0
- package/dist/{agent-session-store-P6V3FINW.js.map → agent-session-store-G2BMUZQV.js.map} +1 -1
- package/dist/agent-session-store-WAKLOKWK.cjs +24 -0
- package/dist/{agent-session-store-ZJ3JSRS4.cjs.map → agent-session-store-WAKLOKWK.cjs.map} +1 -1
- package/dist/{chunk-HLPSLDGL.cjs → chunk-43GFJ5SD.cjs} +7 -7
- package/dist/{chunk-HLPSLDGL.cjs.map → chunk-43GFJ5SD.cjs.map} +1 -1
- package/dist/{chunk-5PHVENFV.js → chunk-7FHZ4VQX.js} +3 -55
- package/dist/chunk-7FHZ4VQX.js.map +1 -0
- package/dist/{chunk-I5BE5M5L.js → chunk-7TCRNXNK.js} +51 -31
- package/dist/chunk-7TCRNXNK.js.map +1 -0
- package/dist/{chunk-JHPGF3FP.cjs → chunk-BUIK7GUA.cjs} +22 -2
- package/dist/chunk-BUIK7GUA.cjs.map +1 -0
- package/dist/{chunk-Q47R5E2X.cjs → chunk-E3WZ6Y4H.cjs} +7 -59
- package/dist/chunk-E3WZ6Y4H.cjs.map +1 -0
- package/dist/{chunk-5UOVYM3P.cjs → chunk-E7JHD6QJ.cjs} +132 -54
- package/dist/chunk-E7JHD6QJ.cjs.map +1 -0
- package/dist/{chunk-DZBSJX6J.js → chunk-FKMUFNQE.js} +21 -4
- package/dist/chunk-FKMUFNQE.js.map +1 -0
- package/dist/{chunk-BMAZLQQ4.js → chunk-G24KZRSA.js} +3 -3
- package/dist/{chunk-BMAZLQQ4.js.map → chunk-G24KZRSA.js.map} +1 -1
- package/dist/{chunk-DAPSQZT4.js → chunk-G6EEYRDD.js} +132 -55
- package/dist/chunk-G6EEYRDD.js.map +1 -0
- package/dist/{chunk-MVAPK2BX.js → chunk-IACR5LEM.js} +3 -3
- package/dist/{chunk-MVAPK2BX.js.map → chunk-IACR5LEM.js.map} +1 -1
- package/dist/{chunk-V2UUGUY4.cjs → chunk-KKK3FZ4A.cjs} +6 -6
- package/dist/{chunk-V2UUGUY4.cjs.map → chunk-KKK3FZ4A.cjs.map} +1 -1
- package/dist/chunk-KRD3GQAA.cjs +71 -0
- package/dist/chunk-KRD3GQAA.cjs.map +1 -0
- package/dist/chunk-KVNWIAO4.js +68 -0
- package/dist/chunk-KVNWIAO4.js.map +1 -0
- package/dist/{chunk-IVNNSANC.js → chunk-LEM2GOMI.js} +3 -3
- package/dist/{chunk-IVNNSANC.js.map → chunk-LEM2GOMI.js.map} +1 -1
- package/dist/{chunk-F5WMX4EA.cjs → chunk-M2JWHKO6.cjs} +107 -87
- package/dist/chunk-M2JWHKO6.cjs.map +1 -0
- package/dist/{chunk-YPJ5NH5N.cjs → chunk-QI7WE46I.cjs} +29 -6
- package/dist/chunk-QI7WE46I.cjs.map +1 -0
- package/dist/{chunk-OHBIUXKM.js → chunk-WG7R5W6R.js} +4 -4
- package/dist/{chunk-OHBIUXKM.js.map → chunk-WG7R5W6R.js.map} +1 -1
- package/dist/{chunk-ITSSOVOB.cjs → chunk-X7O4255I.cjs} +4 -4
- package/dist/{chunk-ITSSOVOB.cjs.map → chunk-X7O4255I.cjs.map} +1 -1
- package/dist/{chunk-GJ6RK75E.js → chunk-YJDH3CKG.js} +29 -6
- package/dist/chunk-YJDH3CKG.js.map +1 -0
- package/dist/{chunk-CTCGWIUD.cjs → chunk-Z4BCLVTI.cjs} +5 -5
- package/dist/{chunk-CTCGWIUD.cjs.map → chunk-Z4BCLVTI.cjs.map} +1 -1
- package/dist/{compact-session-FUJDVF7B.js → compact-session-QGDNP45U.js} +4 -4
- package/dist/{compact-session-FUJDVF7B.js.map → compact-session-QGDNP45U.js.map} +1 -1
- package/dist/{compact-session-LEWF554G.cjs → compact-session-YHFQIXV5.cjs} +12 -12
- package/dist/{compact-session-LEWF554G.cjs.map → compact-session-YHFQIXV5.cjs.map} +1 -1
- package/dist/context/index.cjs +6 -5
- package/dist/context/index.cjs.map +1 -1
- package/dist/context/index.js +3 -2
- package/dist/context/index.js.map +1 -1
- package/dist/cron.cjs +11 -10
- package/dist/cron.js +10 -9
- package/dist/eval.cjs +10 -9
- package/dist/eval.cjs.map +1 -1
- package/dist/eval.js +9 -8
- package/dist/eval.js.map +1 -1
- package/dist/{fs-session-store-IN7JTTXD.js → fs-session-store-4BHGIWRE.js} +4 -4
- package/dist/{fs-session-store-IN7JTTXD.js.map → fs-session-store-4BHGIWRE.js.map} +1 -1
- package/dist/{fs-session-store-3MOJQGP2.cjs → fs-session-store-XZ7ZTB3A.cjs} +5 -5
- package/dist/{fs-session-store-3MOJQGP2.cjs.map → fs-session-store-XZ7ZTB3A.cjs.map} +1 -1
- package/dist/{index-manager-NG5YENWO.cjs → index-manager-AO4LJQZ4.cjs} +5 -4
- package/dist/{index-manager-NG5YENWO.cjs.map → index-manager-AO4LJQZ4.cjs.map} +1 -1
- package/dist/{index-manager-ZMRJ6ZII.js → index-manager-QDPIYIGV.js} +4 -3
- package/dist/{index-manager-ZMRJ6ZII.js.map → index-manager-QDPIYIGV.js.map} +1 -1
- package/dist/index.cjs +40 -39
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +13 -12
- package/dist/index.js.map +1 -1
- package/dist/{inject-session-WQGGMCQY.cjs → inject-session-MLCJMYDG.cjs} +7 -7
- package/dist/{inject-session-WQGGMCQY.cjs.map → inject-session-MLCJMYDG.cjs.map} +1 -1
- package/dist/{inject-session-BJMJH5BX.js → inject-session-RBQZ45UM.js} +5 -5
- package/dist/{inject-session-BJMJH5BX.js.map → inject-session-RBQZ45UM.js.map} +1 -1
- package/dist/internal/memory/storage/markdown-store.d.ts +14 -2
- package/dist/internal/memory/storage/memory-file.d.ts +54 -0
- package/dist/internal/memory/types.d.ts +28 -0
- package/dist/internal/persistence/session-transcript.d.cts +40 -1
- package/dist/internal/persistence/session-transcript.d.ts +40 -1
- package/dist/persistence.cjs +4 -4
- package/dist/persistence.js +1 -1
- package/dist/sandbox/index.cjs +1 -1
- package/dist/sandbox/index.cjs.map +1 -1
- package/dist/sandbox/index.js +1 -1
- package/dist/sandbox/index.js.map +1 -1
- package/dist/session-transcript-HF5GEU5M.cjs +63 -0
- package/dist/{session-transcript-JXHFTB7G.cjs.map → session-transcript-HF5GEU5M.cjs.map} +1 -1
- package/dist/session-transcript-P462ZRHX.js +6 -0
- package/dist/{session-transcript-AKDYYGXQ.js.map → session-transcript-P462ZRHX.js.map} +1 -1
- package/docs/error-codes.md +7 -5
- package/docs/harness-capability-map.md +3 -2
- package/package.json +5 -9
- package/dist/agent-session-store-P6V3FINW.js +0 -7
- package/dist/agent-session-store-ZJ3JSRS4.cjs +0 -24
- package/dist/chunk-5PHVENFV.js.map +0 -1
- package/dist/chunk-5UOVYM3P.cjs.map +0 -1
- package/dist/chunk-DAPSQZT4.js.map +0 -1
- package/dist/chunk-DZBSJX6J.js.map +0 -1
- package/dist/chunk-F5WMX4EA.cjs.map +0 -1
- package/dist/chunk-GJ6RK75E.js.map +0 -1
- package/dist/chunk-I5BE5M5L.js.map +0 -1
- package/dist/chunk-JHPGF3FP.cjs.map +0 -1
- package/dist/chunk-Q47R5E2X.cjs.map +0 -1
- package/dist/chunk-YPJ5NH5N.cjs.map +0 -1
- package/dist/session-transcript-AKDYYGXQ.js +0 -6
- package/dist/session-transcript-JXHFTB7G.cjs +0 -51
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/memory/escape-like-pattern.ts","../src/internal/memory/index-schema.ts","../src/internal/memory/index-db.ts","../src/internal/memory/lance-index.ts","../src/internal/memory/memory-index.ts","../src/internal/memory/lance-memory-adapter.ts","../src/internal/memory/index-manager-dispatch.ts","../src/internal/memory/types.ts","../src/internal/memory/storage/memory-file.ts","../src/internal/memory/storage/markdown-store.ts","../src/internal/memory/storage/session-summary-writer.ts","../src/internal/memory/storage/session-loader.ts","../src/internal/memory/storage/wiki-loader.ts","../src/internal/memory/index-manager-helpers.ts","../src/internal/memory/sqlite-vec-loader.ts","../src/internal/memory/storage/chunk-markdown.ts","../src/internal/memory/vec-index.ts","../src/internal/memory/index-manager.ts"],"names":["openSqliteResilient","join","createRequire","ConfigurationError","mkdirSync","resolvePath","sanitizeIdentifier","safePathJoin","safeFilenameForId","splitFrontmatter","parseSimpleYaml","readdir","readFile","withCwdMutex","redactSecrets","mkdir","replaceFileAtomic","relativeToRoot","relative","stat","createHash","LruEmbeddingCache","sanitizeFts5Query"],"mappings":";;;;;;;;;;;;;;;;;;AAqBO,SAAS,kBAAkB,KAAA,EAAuB;AACvD,EAAA,OAAO,CAAA,CAAA,EAAI,KAAA,CAAM,OAAA,CAAQ,KAAA,EAAO,MAAM,CAAA,CAAE,OAAA,CAAQ,IAAA,EAAM,KAAK,CAAA,CAAE,OAAA,CAAQ,IAAA,EAAM,KAAK,CAAC,CAAA,CAAA,CAAA;AACnF;;;ACPO,IAAM,iBAAA,GAA2C;AAAA,EACtD,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAA,CAAA;AAAA,EAQA,CAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAAA,CAAA;AAAA,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,IAAI,GAAA,CAAI,IAAA,CAAK,IAAI,CAAC,GAAA,KAAQ,CAAC,GAAA,CAAI,IAAA,EAAM,EAAE,EAAA,EAAI,IAAI,EAAA,EAAI,IAAA,EAAM,IAAI,IAAA,EAAM,CAAC,CAAC,CAAA;AAAA,EAC9E;AAAA,EAEQ,WACN,OAAA,EACA,OAAA,EACA,IAAA,EACA,OAAA,EACA,SAAyC,QAAA,EACjC;AACR,IAAA,MAAM,IAAA,GAAO,KAAK,EAAA,CAAG,OAAA;AAAA,MACnB,CAAA;AAAA;AAAA,mBAAA;AAAA,KAGF;AACA,IAAA,MAAM,GAAA,GAAM,IAAA,CAAK,GAAA,CAAI,OAAA,EAAS,OAAA,EAAS,KAAK,KAAA,CAAM,OAAO,CAAA,EAAG,IAAA,EAAM,MAAM,CAAA;AACxE,IAAA,OAAO,GAAA,CAAI,EAAA;AAAA,EACb;AAAA,EAEQ,oBAAoB,MAAA,EAAsB;AAChD,IAAA,IAAA,CAAK,EAAA,CAAG,OAAA,CAAQ,sCAAsC,CAAA,CAAE,IAAI,MAAM,CAAA;AAAA,EACpE;AAAA,EAEQ,WAAA,CACN,MAAA,EACA,SAAA,EACA,OAAA,EACA,MACA,IAAA,EACM;AACN,IAAA,IAAA,CAAK,EAAA,CACF,OAAA;AAAA,MACC;AAAA,MAED,GAAA,CAAI,MAAA,EAAQ,SAAA,EAAW,OAAA,EAAS,MAAM,IAAI,CAAA;AAAA,EAC/C;AAAA,EAEA,KAAA,GAAc;AACZ,IAAA,IAAA,CAAK,GAAG,KAAA,EAAM;AAAA,EAChB;AACF","file":"chunk-E7JHD6QJ.cjs","sourcesContent":["/**\n * Escapes a user query for a SQL `LIKE ... ESCAPE '\\'` clause.\n *\n * The order of the three replacements is the whole correctness argument, so it is its own\n * function rather than a chain inline at the call site.\n *\n * The previous version escaped `%` and `_` but not the escape character itself, which is the\n * defect CodeQL reports as `js/incomplete-sanitization` (alerts #14, #15). Two things went wrong,\n * and the second is the one that matters:\n *\n * \"back\\slash\" -> \"%back\\slash%\" the `\\s` is an escape of `s`, which LIKE does not define\n * \"x\\%y\" -> \"%x\\\\%y%\" the inserted `\\` is consumed escaping the user's `\\`,\n * leaving `%` UNESCAPED — a wildcard the caller did not\n * write, matching anything between `x\\` and `y`\n *\n * The second is wildcard injection: a search for a literal string silently becomes a scan. In a\n * memory index that is both a wrong answer and a way to pull back rows the query never asked for.\n *\n * Escaping the backslash FIRST is what fixes it — afterwards every `\\` in the string is one this\n * function put there, so the later replacements cannot collide with a user-supplied one.\n */\nexport function escapeLikePattern(query: string): string {\n return `%${query.replace(/\\\\/g, \"\\\\\\\\\").replace(/%/g, \"\\\\%\").replace(/_/g, \"\\\\_\")}%`;\n}\n","/**\n * SQLite schema for the memory index.\n *\n * Tables:\n * - files — one row per indexed markdown file (path, mtime, hash).\n * - chunks — one row per chunk produced by `chunkMarkdown`.\n * - chunks_fts — FTS5 virtual table mirroring chunks.text for BM25 search.\n * - meta — key/value store; persists the active embedding identity\n * (provider id, model, dimension) so we detect when the\n * index was built against a different embedding setup.\n * - embeddings — sqlite-vec virtual table holding the chunk vectors\n * (created on demand by `vec-index.ts`).\n *\n * @internal\n */\n\nexport const SCHEMA_STATEMENTS: ReadonlyArray<string> = [\n `CREATE TABLE IF NOT EXISTS files (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n path TEXT UNIQUE NOT NULL,\n rel_path TEXT NOT NULL,\n mtime INTEGER NOT NULL,\n hash TEXT NOT NULL,\n source TEXT NOT NULL DEFAULT 'memory'\n )`,\n `CREATE TABLE IF NOT EXISTS chunks (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,\n start_line INTEGER NOT NULL,\n end_line INTEGER NOT NULL,\n text TEXT NOT NULL,\n hash TEXT NOT NULL,\n session_key TEXT\n )`,\n `CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(\n text,\n content='chunks',\n content_rowid='id'\n )`,\n `CREATE TRIGGER IF NOT EXISTS chunks_fts_insert AFTER INSERT ON chunks BEGIN\n INSERT INTO chunks_fts(rowid, text) VALUES (new.id, new.text);\n END`,\n `CREATE TRIGGER IF NOT EXISTS chunks_fts_delete AFTER DELETE ON chunks BEGIN\n INSERT INTO chunks_fts(chunks_fts, rowid, text) VALUES ('delete', old.id, old.text);\n END`,\n `CREATE TABLE IF NOT EXISTS meta (\n key TEXT PRIMARY KEY,\n value TEXT\n )`,\n `CREATE INDEX IF NOT EXISTS idx_chunks_file_id ON chunks(file_id)`,\n];\n\n/**\n * Non-WAL pragmas. WAL is applied separately via\n * `applyWalWithFallback` (T4.2, ADR D63) so NFS/SMB users get a graceful\n * DELETE fallback instead of crashing.\n */\nexport const PRAGMA_STATEMENTS: ReadonlyArray<string> = [\n \"PRAGMA synchronous=NORMAL\",\n \"PRAGMA foreign_keys=ON\",\n];\n","import { join } from \"node:path\";\n\nimport { openSqliteResilient } from \"../persistence/sqlite-open.js\";\nimport { PRAGMA_STATEMENTS, SCHEMA_STATEMENTS } from \"./index-schema.js\";\n\n/**\n * Memory index DB handle + opener.\n *\n * M0-5 (plan m0-foundation-expose-primitives): the driver-load + WAL +\n * corruption-recovery (EC-7) plumbing is now the shared `openSqliteResilient`\n * primitive in `internal/persistence`; this module only declares the memory\n * schema application (PRAGMA + SCHEMA) via its `onOpen` callback.\n *\n * @internal\n */\n\nexport interface MemoryDb {\n exec(sql: string): void;\n prepare(sql: string): {\n run(...args: unknown[]): { changes: number; lastInsertRowid: number | bigint };\n get(...args: unknown[]): Record<string, unknown> | undefined;\n all(...args: unknown[]): Array<Record<string, unknown>>;\n };\n /** SQLite `pragma()` access (used by `applyWalWithFallback`). */\n pragma(statement: string, options?: { simple?: boolean }): unknown;\n close(): void;\n /** Load a SQLite loadable extension at the given path (used by sqlite-vec). */\n loadExtension(path: string): void;\n}\n\nexport interface OpenDbOptions {\n filePath: string;\n /**\n * When true and opening fails with a corruption error, rename the file aside\n * and create a fresh DB. Default true.\n */\n recoverCorrupt?: boolean;\n}\n\nexport async function openMemoryDb(opts: OpenDbOptions): Promise<MemoryDb> {\n return openSqliteResilient<MemoryDb>({\n filePath: opts.filePath,\n label: \"memory-index\",\n recoverCorrupt: opts.recoverCorrupt,\n onOpen: (db) => {\n // PRAGMA + SCHEMA run after WAL is applied (handled by openSqliteResilient).\n for (const pragma of PRAGMA_STATEMENTS) db.exec(pragma);\n for (const stmt of SCHEMA_STATEMENTS) db.exec(stmt);\n },\n });\n}\n\nexport function defaultIndexPath(cwd: string): string {\n return join(cwd, \".theokit\", \"memory\", \".index\", \"memory.sqlite\");\n}\n","import { existsSync, mkdirSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport type { EmbeddingRuntime } from \"./embedding-adapter.js\";\n\n/**\n * LanceDB-backed memory index (ADR D43). Implements the same logical\n * interface as `IndexManager` but stores embeddings in Lance's columnar\n * vector-aware file format — scalable to 100k+ facts.\n *\n * Opt-in via `Memory.create({ index: { backend: \"lance\" } })`. SQLite\n * remains the default; this code path only activates when explicitly\n * requested AND `@lancedb/lancedb` is installed.\n *\n * EC-1 MUST FIX: filters use Lance structured filter API (object form) —\n * NEVER string interpolation. SQL injection via namespace is impossible.\n *\n * EC-8: embedding dimension is validated when opening an existing table.\n *\n * @internal\n */\n\ninterface LanceModule {\n connect: (uri: string) => Promise<LanceConnection>;\n}\n\ninterface LanceConnection {\n openTable: (name: string) => Promise<LanceTable>;\n createTable: (name: string, data: ReadonlyArray<LanceFactRecord>) => Promise<LanceTable>;\n tableNames: () => Promise<string[]>;\n}\n\ninterface LanceTable {\n add: (rows: ReadonlyArray<LanceFactRecord>) => Promise<void>;\n search: (vector: ReadonlyArray<number>) => LanceQuery;\n delete: (predicate: string) => Promise<void>;\n countRows: () => Promise<number>;\n // EC-8: schema introspection for dimension check.\n schema: () => Promise<{\n fields: ReadonlyArray<{\n name: string;\n // Lance 0.30 returns Apache Arrow Field. FixedSizeList type has\n // `listSize`, not `fixedSize`. typeId=16 = FixedSizeList in Arrow.\n type: { listSize?: number; fixedSize?: number };\n }>;\n }>;\n}\n\ninterface LanceQuery {\n where: (filter: string | Record<string, unknown>) => LanceQuery;\n limit: (n: number) => LanceQuery;\n toArray: () => Promise<ReadonlyArray<LanceFactRecord & { _distance?: number }>>;\n}\n\nexport interface LanceFactRecord {\n id: string;\n text: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n embedding: ReadonlyArray<number>;\n namespace: string;\n scope: string;\n user_id: string;\n timestamp: number;\n}\n\nexport interface OpenLanceOptions {\n cwd: string;\n embedding: EmbeddingRuntime;\n /** Override storage location. Default: `<cwd>/.theokit/memory/lance/`. */\n storagePath?: string;\n}\n\nexport interface LanceSearchOptions {\n namespace: string;\n scope?: string;\n limit?: number;\n sources?: ReadonlyArray<\"memory\" | \"sessions\" | \"wiki\">;\n}\n\nexport interface LanceSearchHit {\n id: string;\n text: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n namespace: string;\n scope: string;\n userId: string;\n score: number;\n}\n\n/**\n * Lazily load `@lancedb/lancedb`. Throws typed error when absent.\n *\n * @internal\n */\nfunction requireLance(): LanceModule {\n try {\n const r = createRequire(import.meta.url);\n return r(\"@lancedb/lancedb\") as LanceModule;\n } catch (cause) {\n throw new ConfigurationError(\n \"Lance backend selected but `@lancedb/lancedb` is not installed. \" +\n 'Install with: `pnpm add @lancedb/lancedb`. SQLite remains available as the default (omit `backend: \"lance\"`).',\n { code: \"lance_backend_unavailable\", cause },\n );\n }\n}\n\n/**\n * Lance-backed memory index. Public API mirrors the SQLite one logically:\n * `addFacts`, `search`, `countFacts`, `removeFacts`, `close`.\n *\n * @internal\n */\nexport class LanceIndex {\n private constructor(\n private readonly table: LanceTable,\n private readonly embedding: EmbeddingRuntime,\n private readonly embeddingDim: number,\n ) {}\n\n static async open(opts: OpenLanceOptions): Promise<LanceIndex> {\n const lance = requireLance();\n const storagePath = opts.storagePath ?? join(opts.cwd, \".theokit\", \"memory\", \"lance\");\n mkdirSync(storagePath, { recursive: true });\n const conn = await lance.connect(storagePath);\n const dim = opts.embedding.dimension;\n const tableName = \"facts\";\n const existing = await conn.tableNames();\n let table: LanceTable;\n if (existing.includes(tableName)) {\n table = await conn.openTable(tableName);\n // EC-8: validate embedding dimension matches what's in storage.\n // Lance 0.30 uses Apache Arrow FixedSizeList type — the size lives\n // in `type.listSize` (older API used `fixedSize`; we read both for\n // forward/backward safety).\n const schema = await table.schema();\n const embField = schema.fields.find((f) => f.name === \"embedding\");\n const existingDim = embField?.type?.listSize ?? embField?.type?.fixedSize;\n if (typeof existingDim === \"number\" && existingDim !== dim) {\n throw new ConfigurationError(\n `Embedding dimension mismatch in Lance index: storage has ${existingDim}-dim vectors, current provider yields ${dim}-dim. Run \\`theokit-migrate-memory\\` after switching providers, or use a different storagePath.`,\n { code: \"embedding_dimension_mismatch\" },\n );\n }\n } else {\n // Create with one bootstrap record. Lance requires an initial row to\n // infer schema; we delete the bootstrap immediately.\n const bootstrap: LanceFactRecord = {\n id: \"__bootstrap__\",\n text: \"\",\n source: \"memory\",\n embedding: new Array(dim).fill(0),\n namespace: \"__bootstrap__\",\n scope: \"__bootstrap__\",\n user_id: \"__bootstrap__\",\n timestamp: 0,\n };\n table = await conn.createTable(tableName, [bootstrap]);\n await table.delete(\"namespace = '__bootstrap__'\");\n }\n return new LanceIndex(table, opts.embedding, dim);\n }\n\n async addFacts(facts: ReadonlyArray<Omit<LanceFactRecord, \"embedding\">>): Promise<void> {\n if (facts.length === 0) return;\n const texts = facts.map((f) => f.text);\n const embeddings = await this.embedding.embed(texts);\n const rows: LanceFactRecord[] = facts.map((f, i) => ({\n ...f,\n embedding: embeddings[i] ?? new Array(this.embeddingDim).fill(0),\n }));\n await this.table.add(rows);\n }\n\n /**\n * Search facts by semantic similarity. EC-1: filters use Lance's\n * structured object filter — NEVER string interpolation.\n */\n async search(query: string, opts: LanceSearchOptions): Promise<LanceSearchHit[]> {\n const [embedding] = await this.embedding.embed([query]);\n if (embedding === undefined) return [];\n // EC-1 (lancedb-backend-ship-v1-1 integration test caught this 2026-05-31):\n // Lance 0.30.0's `.where()` accepts SQL STRING only, NOT object filter —\n // contrary to D43's original assumption. We build the SQL string with\n // single-quote escaping (`'` → `''`) to neutralize injection. This is\n // the standard SQL string-literal escape; bind parameters are not\n // supported in Lance's predicate API. Backed by integration test\n // `injection attempt in namespace does not break filter` (test 7).\n const predicates: string[] = [`namespace = '${escapeSqlValue(opts.namespace)}'`];\n if (opts.scope !== undefined) {\n predicates.push(`scope = '${escapeSqlValue(opts.scope)}'`);\n }\n let q = this.table.search(embedding).where(predicates.join(\" AND \"));\n if (opts.limit !== undefined) q = q.limit(opts.limit);\n const results = await q.toArray();\n return results\n .filter((r) => opts.sources === undefined || opts.sources.includes(r.source))\n .map((r) => ({\n id: r.id,\n text: r.text,\n source: r.source,\n namespace: r.namespace,\n scope: r.scope,\n userId: r.user_id,\n // Lower _distance = better match; normalize to 0..1 (1=best).\n score: 1 / (1 + (r._distance ?? 1)),\n }));\n }\n\n async countFacts(namespace: string): Promise<number> {\n // Total count, regardless of namespace, used by migration validation.\n // For per-namespace count, callers can do a where() + countRows() if\n // Lance supports it; v1.2 ships with global count only.\n void namespace;\n return this.table.countRows();\n }\n\n async removeFacts(ids: ReadonlyArray<string>): Promise<void> {\n if (ids.length === 0) return;\n // Build a parameterized-style delete predicate. Lance's delete still\n // takes a string predicate, so we explicitly quote-escape each id —\n // ids in our system are content-hashed (alphanumeric), so the risk\n // is low, but we belt-and-suspenders.\n const escaped = ids.map((id) => `'${id.replace(/'/g, \"''\")}'`).join(\", \");\n await this.table.delete(`id IN (${escaped})`);\n }\n\n async close(): Promise<void> {\n // Lance auto-closes on GC; no explicit shutdown needed.\n }\n}\n\n/**\n * T5.2 — Harden SQL value escaping for Lance `.where()` predicates.\n *\n * Pre-T5.2 this only escaped single quotes (`'` → `''`). T5.2 adds:\n * - NUL byte rejection (NUL truncates the string in some SQL engines)\n * - C0 control char rejection (prevents invisible payload injection)\n * - Backslash escaping (`\\` → `\\\\` — some engines interpret `\\'` as\n * a single-quote escape, bypassing the `''` defense)\n *\n * Throws `ConfigurationError` on NUL/control to surface the attack\n * honestly rather than silently corrupting the query.\n */\nfunction escapeSqlValue(value: string): string {\n // Reject NUL + C0/DEL control chars (T5.5 pattern adapted for SQL).\n for (let i = 0; i < value.length; i++) {\n const code = value.charCodeAt(i);\n if (code === 0x00 || (code >= 0x01 && code <= 0x1f) || code === 0x7f) {\n throw new ConfigurationError(\n `SQL filter value contains control character at position ${i} (0x${code.toString(16)}). ` +\n \"This may indicate an injection attempt.\",\n { code: \"sql_injection_blocked\" },\n );\n }\n }\n // Escape both single-quote and backslash.\n return value.replace(/\\\\/g, \"\\\\\\\\\").replace(/'/g, \"''\");\n}\n\n/**\n * Test helper for {@link LanceIndex}: indicates whether the Lance module\n * is loadable in the current environment. Allows tests to gracefully skip\n * when the optional dep is absent.\n *\n * @internal\n */\nexport function isLanceAvailable(): boolean {\n try {\n const r = createRequire(import.meta.url);\n r(\"@lancedb/lancedb\");\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Test helper: re-export the storage path computation.\n *\n * @internal\n */\nexport function lanceStoragePath(cwd: string): string {\n return join(cwd, \".theokit\", \"memory\", \"lance\");\n}\n\nvoid existsSync; // imported but only used conditionally via mkdirSync\n","/**\n * Common `MemoryIndex` interface shared between the SQLite-backed\n * `IndexManager` (default) and the Lance-backed adapter (ADR D43, shipped\n * v1.4.0 via lancedb-backend-ship-v1-1 plan).\n *\n * Consumers (`local-agent-memory.ts`, `active-memory.ts`, `tools.ts`,\n * `runActiveMemory`) only ever call `sync()`, `search()`, `status()`,\n * `close()` — the union of those four methods is the portable surface.\n *\n * Why a separate file (vs declaring inline in `index-manager.ts`)? D43\n * promised \"extract an abstract `MemoryIndex` interface in\n * `internal/memory/index-interface.ts`\". Keeping the contract physically\n * separated from one of its implementations preserves OCP — future\n * backends (Qdrant, PGVector) can land without touching IndexManager.\n *\n * @internal\n */\n\nimport type { IndexStatus, MemorySearchHit, SearchOptions } from \"./index-manager-contract.js\";\n\n// Re-export consumer-facing shapes for stable internal import paths.\nexport type { IndexStatus, MemorySearchHit, SearchOptions };\n\nexport interface SyncResult {\n filesScanned: number;\n filesUpdated: number;\n chunksWritten: number;\n chunksEmbedded: number;\n}\n\n/**\n * Common search-options parser used by both `IndexManager.search` and\n * `LanceMemoryAdapter.search`. Returns the normalized cap + minimum-score\n * floor — eliminates jscpd duplication while keeping per-backend search\n * logic distinct.\n */\nexport function parseSearchOptions(options: SearchOptions = {}): {\n maxResults: number;\n minScore: number;\n} {\n return {\n maxResults: Math.max(1, options.maxResults ?? 10),\n minScore: options.minScore ?? 0,\n };\n}\n\nexport interface MemoryIndex {\n /**\n * Walk the memory corpus + reindex changed files. Lance backend has no\n * markdown corpus to walk — its adapter returns zero counts (no-op) and\n * relies on explicit `addFact` calls instead.\n */\n sync(): Promise<SyncResult>;\n\n /**\n * Semantic + textual search over the indexed corpus. Both backends\n * return the same `MemorySearchHit[]` shape; Lance leaves `textScore`\n * undefined (vector-only — no FTS5 layer).\n */\n search(query: string, options?: SearchOptions): Promise<MemorySearchHit[]>;\n\n /** Snapshot of the index health (backend type + counts). */\n status(): IndexStatus;\n\n /** Release native handles. Idempotent. */\n close(): Promise<void> | void;\n}\n","/**\n * `LanceMemoryAdapter` — wraps `LanceIndex` to expose the common\n * `MemoryIndex` interface (sync/search/status/close) so consumers of\n * `IndexManager.open({ backend: \"lance\" })` get a drop-in replacement\n * for the SQLite-backed `IndexManager`.\n *\n * Semantic deltas vs SQLite (documented so callers know what to expect):\n *\n * - `sync()` is a NO-OP. Lance is a pure vector store — there is no\n * markdown corpus to crawl. Returns zero counts. Consumers writing\n * facts use `LanceIndex.addFacts` directly (exposed via the index\n * object returned to advanced callers).\n * - `search()` performs vector-only retrieval. `MemorySearchHit.textScore`\n * is undefined (no FTS5 layer); `vectorScore === score`.\n * - `status()` reports `backend: \"hybrid\"` only when an embedding runtime\n * is wired (always the case for Lance — embedding is required at open).\n * `chunksIndexed` reflects total Lance row count; `filesIndexed` is 0\n * because Lance does not track file provenance per-row.\n *\n * Ships with the lancedb-backend-ship-v1-1 plan (close D12, supersede via\n * D43). v1.4.0 of `@theokit/sdk`.\n *\n * @internal\n */\n\nimport type { IndexStatus, MemorySearchHit, SearchOptions } from \"./index-manager-contract.js\";\nimport type { LanceIndex } from \"./lance-index.js\";\nimport { type MemoryIndex, parseSearchOptions, type SyncResult } from \"./memory-index.js\";\n\n/**\n * Default namespace used when consumers call `search()` without specifying\n * one. The SQLite `IndexManager` does not surface namespace in its public\n * `search()` signature either — both backends therefore behave consistently\n * under the \"single-workspace, single-namespace\" assumption that v1.4 ships.\n *\n * v1.5 candidate: surface `namespace` in `SearchOptions` (additive — no\n * breaking change) so multi-tenant Lance consumers can scope queries.\n */\nconst DEFAULT_NAMESPACE = \"default\";\n\n/** Empty sync result — Lance has no corpus to walk. */\nconst EMPTY_SYNC_RESULT: SyncResult = Object.freeze({\n filesScanned: 0,\n filesUpdated: 0,\n chunksWritten: 0,\n chunksEmbedded: 0,\n});\n\nexport class LanceMemoryAdapter implements MemoryIndex {\n constructor(private readonly inner: LanceIndex) {}\n\n /**\n * No-op for Lance — see file header. Returns zero counts so callers'\n * existing logging (`filesScanned: X`) does not break.\n */\n async sync(): Promise<SyncResult> {\n return EMPTY_SYNC_RESULT;\n }\n\n // jscpd:ignore-start — search signature + early-out is idiomatic\n // overlap with IndexManager.search; further factoring would hurt\n // readability (the bodies diverge sharply right after).\n async search(query: string, options: SearchOptions = {}): Promise<MemorySearchHit[]> {\n if (query.trim().length === 0) return [];\n const { maxResults, minScore } = parseSearchOptions(options);\n // jscpd:ignore-end\n const lanceHits = await this.inner.search(query, {\n namespace: DEFAULT_NAMESPACE,\n limit: maxResults * 2,\n ...(options.sources !== undefined ? { sources: options.sources } : {}),\n });\n return lanceHits\n .filter((h) => h.score >= minScore)\n .slice(0, maxResults)\n .map((h) => translateLanceHit(h, query));\n }\n\n status(): IndexStatus {\n // chunksIndexed via a synchronous best-effort — Lance API is async so\n // we surface zero here and document that consumers needing exact counts\n // should call `inner.countFacts()` directly.\n return {\n backend: \"hybrid\",\n filesIndexed: 0,\n chunksIndexed: 0,\n };\n }\n\n async close(): Promise<void> {\n await this.inner.close();\n }\n\n /**\n * Escape hatch for advanced callers (migration tool, benchmark script)\n * that need direct access to addFacts/countFacts/removeFacts.\n */\n unwrap(): LanceIndex {\n return this.inner;\n }\n}\n\n/**\n * Translate `LanceSearchHit` to `MemorySearchHit`. Field mapping:\n *\n * - `id` → `path` (Lance has no file-system provenance; use opaque id)\n * - `text` → `snippet` (truncated to 200 chars matching IndexManager convention)\n * - `score` → combined (0.7 × vectorScore + 0.3 × textScore)\n * - `vectorScore` → from Lance's distance metric\n * - `textScore` → T4.5 client-side term-overlap ratio (removes ADR D43 vector-only caveat)\n * - `source` → `source`\n * - synthetic `startLine: 0, endLine: 0` (Lance has no line info)\n * - synthetic `citation: id` (no path:line citation available)\n */\nfunction translateLanceHit(\n hit: { id: string; text: string; source: \"memory\" | \"sessions\" | \"wiki\"; score: number },\n query?: string,\n): MemorySearchHit {\n const textScore = query !== undefined ? computeTermOverlapScore(query, hit.text) : 0;\n const vectorScore = hit.score;\n // Hybrid combination: 70% vector (semantic) + 30% text (lexical).\n const combined = 0.7 * vectorScore + 0.3 * textScore;\n return {\n path: hit.id,\n startLine: 0,\n endLine: 0,\n score: combined,\n textScore,\n vectorScore,\n snippet: hit.text.slice(0, 200),\n source: hit.source,\n citation: hit.id,\n };\n}\n\n/**\n * T4.5 — Client-side term-overlap score for Lance hybrid search.\n * Counts what fraction of query terms appear in the text (case-insensitive).\n * Simple but effective for re-ranking vector hits by lexical relevance.\n * Returns 0..1 where 1 = all query terms present.\n */\nfunction computeTermOverlapScore(query: string, text: string): number {\n const queryTerms = query\n .toLowerCase()\n .split(/\\s+/)\n .filter((t) => t.length > 1);\n if (queryTerms.length === 0) return 0;\n const textLower = text.toLowerCase();\n const matched = queryTerms.filter((term) => textLower.includes(term)).length;\n return matched / queryTerms.length;\n}\n","/**\n * Dispatch helpers for `IndexManager.open`. Extracted to keep\n * `index-manager.ts` under the G8 400-LoC budget (lancedb-backend-ship-v1-1).\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport type { MemoryBackend, OpenIndexOptions } from \"./index-manager-contract.js\";\nimport { LanceIndex } from \"./lance-index.js\";\nimport { LanceMemoryAdapter } from \"./lance-memory-adapter.js\";\nimport type { MemoryIndex } from \"./memory-index.js\";\n\n/** Valid backend identifiers — runtime guard against TS-narrowing escapes (EC-1). */\nexport const VALID_BACKENDS: readonly MemoryBackend[] = [\"sqlite-vec\", \"lance\"];\n\n/**\n * EC-1: runtime guard for `opts.backend`. TS union is compile-time only;\n * consumers passing JS `as any` typos must hit a typed error, not silent\n * SQLite fallback.\n */\nexport function assertValidBackend(backend: string): asserts backend is MemoryBackend {\n if (!VALID_BACKENDS.includes(backend as MemoryBackend)) {\n throw new ConfigurationError(\n `Invalid memory backend \"${backend}\". Valid values: ${VALID_BACKENDS.join(\", \")}.`,\n { code: \"invalid_memory_backend\" },\n );\n }\n}\n\n/**\n * Lance-path open. Throws `lance_requires_embedding` when no embedding\n * runtime is provided (Lance is vector-only — no FTS fallback).\n * Surfaces `lance_backend_unavailable` from LanceIndex.open when peer\n * dep is absent.\n */\nexport async function openLanceIndex(opts: OpenIndexOptions): Promise<MemoryIndex> {\n if (opts.embedding === undefined) {\n throw new ConfigurationError(\n \"Lance backend requires an embedding runtime. Pass `embedding: { provider, model, apiKey }` in Memory.create options (or omit `backend` to use SQLite default).\",\n { code: \"lance_requires_embedding\" },\n );\n }\n const lance = await LanceIndex.open({\n cwd: opts.cwd,\n embedding: opts.embedding,\n ...(opts.filePath !== undefined ? { storagePath: opts.filePath } : {}),\n });\n return new LanceMemoryAdapter(lance);\n}\n","/**\n * Public memory types (used by runtime + storage + migration + future index).\n *\n * Leaf module — only depends on `node:path` — so neither `runtime/memory-store.ts`\n * nor `internal/memory/markdown-store.ts` introduces a dependency cycle.\n *\n * @internal\n */\nimport { resolve as resolvePath } from \"node:path\";\n\nimport { safePathJoin, sanitizeIdentifier } from \"../security/path-guard.js\";\n\nexport interface MemoryConfig {\n enabled: boolean;\n namespace?: string;\n userId?: string;\n scope?: \"agent\" | \"user\" | \"team\";\n storePath?: string;\n}\n\n/**\n * What a fact IS, which is what decides whether it ages (#389).\n *\n * The four are the distinctions that matter for retention and recall: a preference stays true until\n * the user changes their mind, a project fact goes stale when the code moves, a reference either\n * resolves or 404s, and feedback records a correction that was given. Without them, recall ranks one\n * undifferentiated corpus and pruning has no basis to prefer a durable fact over a transient one.\n *\n * A kind is never INFERRED. A wrong kind is worse than none, because it makes retention and recall\n * confident about the wrong thing — so a fact whose author did not say stays untyped.\n */\nexport type MemoryKind = \"user\" | \"feedback\" | \"project\" | \"reference\";\n\n/** The four values {@link MemoryKind} admits, for runtime validation at the storage boundary. */\nexport const MEMORY_KINDS: readonly MemoryKind[] = [\"user\", \"feedback\", \"project\", \"reference\"];\n\nexport interface MemoryFact {\n text: string;\n /**\n * What this fact is (#389). Absent means untyped, which is what a hand-written bullet under\n * `## Facts` stays — those files are already on disk in consumers' repositories and the store's\n * own header invites editing them.\n */\n kind?: MemoryKind;\n /**\n * ISO 8601 instant this fact was last written, stamped BY THE SDK.\n *\n * Supplying it does nothing: a timestamp a caller can set is a timestamp that can lie about when\n * something was learned, and the whole point is to weigh a note from this morning against one\n * from four months ago. Absent on a fact written before this existed, or hand-added.\n */\n modified?: string;\n}\n\n// `redactSecrets` is now re-exported from the canonical security module\n// (ADR D68). Pre-T0.2 it was a 3-pattern local fn; consolidated to avoid\n// drift with the central 12-pattern list.\nexport { redactSecrets } from \"../security/index.js\";\n\n/**\n * Resolve the legacy JSON memory path used pre-ADR-D8 (kept for migration\n * helpers + tests). Centralized here so `migration.ts` and the legacy-aware\n * `runtime/memory-store.ts` don't duplicate the path logic (jscpd cleanup).\n */\nexport function legacyMemoryJsonPath(cwd: string, config: MemoryConfig): string {\n // ADRs D79-D81: storePath is programmatic (trusted); namespace/scope/userId\n // are user-shaped and pass sanitizeIdentifier. EC-7 (edge-case review):\n // realistic userIds (UUIDs, hash IDs, \"default\") pass; \"user@example.com\"\n // and similar need to be normalized by the caller before passing.\n if (config.storePath !== undefined) {\n return resolvePath(cwd, config.storePath);\n }\n const namespace = sanitizeIdentifier(config.namespace ?? \"default\");\n const scope = sanitizeIdentifier(config.scope ?? \"agent\", { maxLen: 16 });\n const userId = sanitizeIdentifier(config.userId ?? \"default\");\n return safePathJoin(cwd, \".theokit\", \"memory\", namespace, `${scope}-${userId}.json`);\n}\n\n/**\n * A semantically meaningful slice of a markdown memory file, produced by\n * `chunkMarkdown`. Each chunk carries stable line numbers + a content hash\n * used downstream by the embedding cache.\n *\n * Mirrors peer-project's `MemoryChunk` shape\n * (`reference/peer-project/packages/memory-host-sdk/src/host/engine-storage.ts`).\n *\n * @internal\n */\nexport interface MemoryChunk {\n /** 1-indexed starting line in the source file. */\n startLine: number;\n /** 1-indexed ending line (inclusive). */\n endLine: number;\n /** Slice of markdown source text. */\n text: string;\n /** sha256 of `text`; stable across runs for identical inputs. */\n hash: string;\n /** Optional nearest heading text (without the `#` markers). */\n heading?: string;\n}\n\n/**\n * Result of `reader.readFile`. Contains the bounded slice plus truncation\n * + provenance info.\n *\n * Mirrors peer-project's `MemoryReadResult` shape.\n *\n * @internal\n */\nexport interface MemoryReadResult {\n path: string;\n /** Requested starting line (1-indexed, defaults to 1). */\n from: number;\n /** Number of lines actually returned (may be less than `lines` near EOF). */\n linesReturned: number;\n /** Total lines in the file (after the read). */\n totalLines: number;\n /** True when fewer lines were returned than the requested `lines` AND EOF was hit. */\n truncated: boolean;\n /** Lines past the returned slice that remain in the file. */\n remainingLines: number;\n /** Slice text (joined with `\\n`). */\n text: string;\n}\n","/**\n * One memory as a file, in the shape the Claude Code CLI reads.\n *\n * `@theokit/sdk` already writes native Claude Code `.jsonl` sessions — the README's differentiator\n * is \"point `local.sessionDir` at `~/.claude` and the Claude Code CLI can `--continue` a session\n * your agent wrote\". Memory had no such convergence: a fact was a bullet under `## Facts` with its\n * kind in an HTML comment (#389), which that CLI reads as prose. Pointing a memory directory at\n * `~/.claude/projects/<project>/memory/` produced nothing it could open.\n *\n * The contract here was measured against a real store rather than inferred from documentation. Of\n * nine files, all nine carry `name`, `description` and `metadata.type`; six also carry\n * `node_type`, `originSessionId` and `modified`, which the runtime stamps on write. So the minimum\n * a reader must accept is the first three — refusing the rest would refuse memories the CLI itself\n * accepts.\n *\n * `originSessionId` is deliberately not written. It identifies the session that learned the fact,\n * and the append path has no session in scope; inventing one would be worse than omitting a field\n * the format already treats as optional.\n *\n * @internal\n */\n\nimport { parseSimpleYaml, splitFrontmatter } from \"../../runtime/context/context-yaml-lite.js\";\nimport { safeFilenameForId } from \"../../security/path-guard.js\";\nimport { MEMORY_KINDS, type MemoryKind } from \"../types.js\";\n\n/** The fields one memory file carries. */\nexport interface MemoryFileFields {\n /** Slug, and the file's basename. */\n readonly name: string;\n /** One-line summary — what the index shows and what recall ranks. */\n readonly description: string;\n /** `metadata.type`, absent when the file does not declare one this contract admits. */\n readonly kind?: MemoryKind;\n /** `metadata.modified`, an ISO 8601 instant stamped by whoever wrote the file. */\n readonly modified?: string;\n /** The markdown after the frontmatter. */\n readonly body: string;\n}\n\n/** The safe filename grammar a slug must satisfy before it is used as one. */\nconst SAFE_SLUG = /^[a-z0-9][a-z0-9_-]*$/;\n/** Long enough to stay readable, short enough to survive every filesystem's component limit. */\nconst MAX_SLUG_LENGTH = 64;\n\n/**\n * A readable, filesystem-safe slug for `text`.\n *\n * Readability is the goal — a directory of `h-3f2a…` files is a directory nobody browses — but it\n * is not the floor. The text comes from whatever a caller learned, so anything that fails the safe\n * grammar falls back to {@link safeFilenameForId}, which is total and always yields a valid\n * component.\n */\nexport function slugForFact(text: string): string {\n const slug = text\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, MAX_SLUG_LENGTH)\n .replace(/-+$/, \"\");\n return SAFE_SLUG.test(slug) ? slug : safeFilenameForId(text);\n}\n\n/** Render one memory file. `description` is quoted so a colon in the text cannot break the block. */\nexport function renderMemoryFile(fields: MemoryFileFields): string {\n const metadata = [\" node_type: memory\"];\n if (fields.kind !== undefined) metadata.push(` type: ${fields.kind}`);\n if (fields.modified !== undefined) metadata.push(` modified: ${fields.modified}`);\n return [\n \"---\",\n `name: ${fields.name}`,\n `description: ${JSON.stringify(fields.description)}`,\n \"metadata:\",\n ...metadata,\n \"---\",\n \"\",\n fields.body,\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * Read one memory file, or `undefined` when the content is not one.\n *\n * `undefined` rather than a throw, and rather than a best-effort object: the directory holds\n * hand-written notes and a `MEMORY.md` index alongside the memories, and turning any of those into\n * a fact would put text into recall that nobody recorded as one.\n */\nexport function parseMemoryFile(raw: string): MemoryFileFields | undefined {\n const { yaml, body } = splitFrontmatter(raw);\n if (yaml === undefined) return undefined;\n\n let fields: Record<string, unknown>;\n try {\n fields = parseSimpleYaml(yaml);\n } catch {\n return undefined; // malformed frontmatter is not a memory\n }\n\n const name = fields.name;\n const description = fields.description;\n if (typeof name !== \"string\" || typeof description !== \"string\") return undefined;\n\n const metadata = (fields.metadata ?? {}) as Record<string, unknown>;\n const rawKind = metadata.type;\n // An unknown `type` reads as untyped rather than as a fifth kind: the file is hand-editable and\n // recall must not act on a value this contract does not admit.\n const kind =\n typeof rawKind === \"string\" && MEMORY_KINDS.includes(rawKind as MemoryKind)\n ? (rawKind as MemoryKind)\n : undefined;\n const modified = typeof metadata.modified === \"string\" ? metadata.modified : undefined;\n\n return {\n name,\n description,\n ...(kind !== undefined ? { kind } : {}),\n ...(modified !== undefined ? { modified } : {}),\n body: body.trim(),\n };\n}\n","import { mkdir, readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\nimport { replaceFileAtomic } from \"../../persistence/atomic-write.js\";\nimport { withCwdMutex } from \"../../persistence/cwd-mutex.js\";\nimport { MEMORY_KINDS, type MemoryConfig, type MemoryFact, redactSecrets } from \"../types.js\";\nimport { parseMemoryFile, renderMemoryFile, slugForFact } from \"./memory-file.js\";\n\n/**\n * Markdown-first memory storage (ADR D1 of memory-system-peer-project-parity).\n *\n * Layout, converged with the one the Claude Code CLI reads:\n * <memoryDir>/\n * ├── MEMORY.md # INDEX — one `- [text](slug.md)` line per memory\n * ├── <slug>.md # one memory, frontmatter carrying `metadata.type` + `modified`\n * └── notes/\n * └── <slug>.md # hand-written per-topic notes (read by the indexer, never written here)\n *\n * The SDK already emits native Claude Code `.jsonl` sessions, so a consumer can point\n * `local.sessionDir` at `~/.claude` and `--continue` a session its agent wrote. Memory did not hold\n * that line: a fact was a bullet under `## Facts` with its kind in an HTML comment (#389), which\n * that CLI reads as prose. Pointing a memory directory at `~/.claude/projects/<project>/memory/`\n * produced nothing it could open.\n *\n * `## Facts` bullets are still READ. They are already on disk in consumers' repositories, and a\n * format change that stopped reading them would delete what someone recorded — worse than the\n * format it replaces.\n *\n * All writes go through `replaceFileAtomic` + a per-cwd mutex (EC-4 of the\n * edge-case review) so concurrent `appendFact` calls within the same process\n * serialize. Multi-process safety is NOT provided.\n *\n * @internal\n */\n\nconst MEMORY_MD_HEADER =\n \"# Memory\\n\\n> Auto-managed by @theokit/sdk. Edit freely — the SDK reads from here.\\n\";\nconst FACTS_HEADING = \"## Facts\";\n\nexport function memoryDir(cwd: string): string {\n return join(cwd, \".theokit\", \"memory\");\n}\n\nexport function memoryMdPath(cwd: string): string {\n return join(memoryDir(cwd), \"MEMORY.md\");\n}\n\nexport function notesDir(cwd: string): string {\n return join(memoryDir(cwd), \"notes\");\n}\n\n/**\n * Every memory in the store: the per-memory files, plus any legacy `## Facts` bullets still in\n * `MEMORY.md`. Returns `[]` when the directory does not exist.\n *\n * Reading both is not transitional politeness. Those bullets are already on disk in consumers'\n * repositories, and the store's own header invites editing them by hand — a converged writer that\n * stopped reading them would delete what someone recorded, which is worse than the format it fixes.\n */\nexport async function readFactsFromMarkdown(cwd: string): Promise<MemoryFact[]> {\n let entries: string[];\n try {\n entries = await readdir(memoryDir(cwd));\n } catch {\n return [];\n }\n\n const facts: MemoryFact[] = [];\n for (const entry of entries.sort()) {\n const fact = await readMemoryFileAt(cwd, entry);\n if (fact !== undefined) facts.push(fact);\n }\n\n try {\n facts.push(...parseFactsSection(await readFile(memoryMdPath(cwd), \"utf8\")));\n } catch {\n // no index yet — the per-memory files above are the whole store\n }\n return facts;\n}\n\n/**\n * One directory entry as a fact, or `undefined` when it is not one.\n *\n * `MEMORY.md` is the index, not a memory; a non-markdown entry is not a memory; and a markdown file\n * without the frontmatter is a note somebody wrote by hand. Turning any of those into a fact would\n * put text into recall that nobody recorded as one.\n */\nasync function readMemoryFileAt(cwd: string, entry: string): Promise<MemoryFact | undefined> {\n if (!entry.endsWith(\".md\") || entry === \"MEMORY.md\") return undefined;\n let raw: string;\n try {\n raw = await readFile(join(memoryDir(cwd), entry), \"utf8\");\n } catch {\n return undefined; // vanished between readdir and read\n }\n const parsed = parseMemoryFile(raw);\n if (parsed === undefined) return undefined;\n return {\n text: parsed.description,\n ...(parsed.kind !== undefined ? { kind: parsed.kind } : {}),\n ...(parsed.modified !== undefined ? { modified: parsed.modified } : {}),\n };\n}\n\n/**\n * Write a fact as its own memory file and point the `MEMORY.md` index at it. Atomic + serialized.\n *\n * `modified` is stamped HERE and never read from `fact`: a timestamp a caller can set is a\n * timestamp that can lie about when something was learned, and weighing recency is the point.\n */\nexport function appendFactToMarkdown(cwd: string, fact: MemoryFact): Promise<void> {\n return withCwdMutex(memoryDir(cwd), async () => {\n // Validate at the boundary (`error-handling.md` § 2): a kind outside the four would be written\n // to a file recall later trusts, so it is refused here rather than stored and believed.\n if (fact.kind !== undefined && !MEMORY_KINDS.includes(fact.kind)) {\n throw new ConfigurationError(\n `Unknown memory fact kind \"${fact.kind}\". Expected one of: ${MEMORY_KINDS.join(\", \")}.`,\n { code: \"invalid_memory_kind\" },\n );\n }\n const text = redactSecrets(fact.text);\n const name = slugForFact(text);\n await mkdir(memoryDir(cwd), { recursive: true });\n await replaceFileAtomic(\n join(memoryDir(cwd), `${name}.md`),\n renderMemoryFile({\n name,\n description: text,\n ...(fact.kind !== undefined ? { kind: fact.kind } : {}),\n modified: new Date().toISOString(),\n body: text,\n }),\n );\n await replaceFileAtomic(memoryMdPath(cwd), await nextIndex(cwd, text, name));\n });\n}\n\n/**\n * The `MEMORY.md` index with `name` present exactly once.\n *\n * Rewriting the same memory replaces its line rather than adding a second: the index is a map from\n * memory to file, and two lines for one file is a map that disagrees with itself.\n */\nasync function nextIndex(cwd: string, text: string, name: string): Promise<string> {\n let existing = \"\";\n try {\n existing = await readFile(memoryMdPath(cwd), \"utf8\");\n } catch {\n existing = \"\";\n }\n const entry = `- [${text}](${name}.md)`;\n const kept = existing\n .split(\"\\n\")\n .filter((line) => !line.startsWith(`- [`) || !line.includes(`](${name}.md)`));\n const body = kept.join(\"\\n\").trimEnd();\n const head = body.length > 0 ? body : MEMORY_MD_HEADER.trimEnd();\n return `${head}\\n${entry}\\n`;\n}\n\n/** A `MEMORY.md` index entry: a link whose target is a sibling `.md` file. */\nconst INDEX_ENTRY = /^\\[[^\\]]*\\]\\([^)]+\\.md\\)$/;\n\n/**\n * Facts from a legacy `## Facts` section — the shape every released version wrote.\n *\n * Kept for reading only. The converged writer puts each memory in its own file, and this parser\n * exists so a store written by an earlier version keeps answering.\n *\n * There is no metadata to recover from a bullet: `kind` and `modified` are absent, which is exactly\n * right, since nothing recorded them. A brief encoding that carried them in a trailing HTML comment\n * (#389) never reached a published version — 4.55.0 was published at 17:23Z and that commit landed\n * at 20:06Z — so there is no store in the wild to migrate from it.\n */\nfunction parseFactsSection(raw: string): MemoryFact[] {\n const idx = raw.indexOf(FACTS_HEADING);\n if (idx === -1) return [];\n const tail = raw.slice(idx + FACTS_HEADING.length);\n // Stop at the next top-level or h2 heading.\n const nextHeading = tail.search(/\\n#{1,2}\\s/);\n const block = nextHeading === -1 ? tail : tail.slice(0, nextHeading);\n return (\n block\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.startsWith(\"- \"))\n .map((line) => line.slice(2).trim())\n // An index entry is a POINTER to a memory, not a memory. Both are `- ` bullets, and when a\n // legacy `## Facts` heading is present the appended index lines land under it — counting them\n // here would report every converged memory twice, once from its file and once from its link.\n .filter((body) => !INDEX_ENTRY.test(body))\n .map((body) => ({ text: body }))\n );\n}\n\n/** Configuration-aware accessors honoring the existing MemoryConfig contract. */\nexport async function readFacts(cwd: string, config: MemoryConfig): Promise<MemoryFact[]> {\n if (!config.enabled) return [];\n return readFactsFromMarkdown(cwd);\n}\n\nexport async function appendFact(\n cwd: string,\n config: MemoryConfig,\n fact: MemoryFact,\n): Promise<void> {\n if (!config.enabled) return;\n await appendFactToMarkdown(cwd, fact);\n}\n","import { mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { replaceFileAtomic } from \"../../persistence/atomic-write.js\";\nimport { safeFilenameForId } from \"../../security/path-guard.js\";\nimport { redactSecrets } from \"../types.js\";\nimport { memoryDir } from \"./markdown-store.js\";\n\n/**\n * Per-run session summary writer (ADR D20).\n *\n * After every finished run, write a markdown summary to\n * `.theokit/memory/sessions/<runId>.md`. IndexManager picks these up with\n * `source=\"sessions\"` so `memory_search({ corpus: \"sessions\" })` can recall\n * past conversations.\n *\n * EC-9: only `status === \"finished\"` runs trigger a write. Cancelled/errored\n * runs would otherwise pollute the recall corpus with partial transcripts.\n *\n * @internal\n */\n\nexport interface SessionSummaryInput {\n cwd: string;\n runId: string;\n agentId: string;\n userText: string;\n assistantText: string;\n status: \"finished\" | \"running\" | \"error\" | \"cancelled\";\n at: number;\n}\n\nconst MAX_TURN_CHARS = 2000;\n\nexport function sessionsDir(cwd: string): string {\n return join(memoryDir(cwd), \"sessions\");\n}\n\nexport function sessionSummaryPath(cwd: string, runId: string): string {\n // M0-4: total id->filename helper. UUID runIds (the production case, from\n // randomUUID) pass through to the identical name; non-conforming ids get a\n // deterministic sha256 token instead of the old lossy replace-collapse.\n return join(sessionsDir(cwd), `${safeFilenameForId(runId, { maxLen: 128 })}.md`);\n}\n\nfunction truncate(text: string): string {\n if (text.length <= MAX_TURN_CHARS) return text;\n return `${text.slice(0, MAX_TURN_CHARS)}…`;\n}\n\n/**\n * Write a session summary file. EC-9: a non-finished status returns early\n * without touching disk. Secrets in both user and assistant text are\n * redacted via the shared `redactSecrets` pattern.\n *\n * @internal\n */\nexport async function writeSessionSummary(input: SessionSummaryInput): Promise<void> {\n if (input.status !== \"finished\") return;\n const path = sessionSummaryPath(input.cwd, input.runId);\n await mkdir(sessionsDir(input.cwd), { recursive: true });\n\n const safeUser = redactSecrets(truncate(input.userText));\n const safeAssistant = redactSecrets(truncate(input.assistantText));\n const iso = new Date(input.at).toISOString();\n\n const body = [\n \"---\",\n `runId: ${input.runId}`,\n `agentId: ${input.agentId}`,\n `at: ${iso}`,\n `status: ${input.status}`,\n \"---\",\n \"\",\n \"## User\",\n \"\",\n safeUser,\n \"\",\n \"## Assistant\",\n \"\",\n safeAssistant,\n \"\",\n ].join(\"\\n\");\n\n await replaceFileAtomic(path, body);\n}\n","import { readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { memoryDir } from \"./markdown-store.js\";\nimport { sessionsDir } from \"./session-summary-writer.js\";\n\n/**\n * Session summary discovery (ADR D20).\n *\n * Mirrors `wiki-loader.ts:discoverWikiFiles`: scans\n * `.theokit/memory/sessions/*.md` and returns `SessionFile` records —\n * `{ absolutePath, relPath }`. IndexManager tags each chunk with\n * `source=\"sessions\"` so `memory_search({ corpus: \"sessions\" })` filters\n * them in.\n *\n * B-140: this said \"returns `MemoryFileEntry`-shaped records\" and that was\n * not true — `MemoryFileEntry` carried four fields (`path`, `relPath`,\n * `mtime`, `hash`) against this function's two, and even the path field was\n * named differently. Nothing consumed the interface, so it was removed and\n * the sentence now names the type the function actually returns. A docblock\n * asserting agreement between two shapes is worth no more than the agreement.\n *\n * @internal\n */\n\nexport interface SessionFile {\n absolutePath: string;\n relPath: string;\n}\n\nexport async function discoverSessionFiles(cwd: string): Promise<SessionFile[]> {\n let entries: string[];\n try {\n entries = await readdir(sessionsDir(cwd));\n } catch {\n return [];\n }\n const root = memoryDir(cwd);\n return entries\n .filter((entry) => entry.endsWith(\".md\"))\n .map((entry) => {\n const absolutePath = join(sessionsDir(cwd), entry);\n return {\n absolutePath,\n relPath: relativeToRoot(root, absolutePath),\n };\n });\n}\n\nfunction relativeToRoot(root: string, absolutePath: string): string {\n if (absolutePath.startsWith(`${root}/`)) return absolutePath.slice(root.length + 1);\n return absolutePath;\n}\n","import { readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { memoryDir } from \"./markdown-store.js\";\n\n/**\n * Wiki supplement discovery (ADR Phase 10 of memory-system-peer-project-parity).\n *\n * Wiki files live under `.theokit/memory/wiki/*.md`. They are READ-ONLY —\n * the SDK never writes here. Each indexed chunk carries `source=\"wiki\"` so\n * `memory_search { corpus: \"wiki\" }` and `corpus: \"all\"` can scope hits.\n *\n * @internal\n */\n\nexport interface WikiFile {\n absolutePath: string;\n relPath: string;\n}\n\nexport function wikiDir(cwd: string): string {\n return join(memoryDir(cwd), \"wiki\");\n}\n\nexport async function discoverWikiFiles(cwd: string): Promise<WikiFile[]> {\n let entries: string[];\n try {\n entries = await readdir(wikiDir(cwd));\n } catch {\n return [];\n }\n const root = memoryDir(cwd);\n return entries\n .filter((entry) => entry.endsWith(\".md\"))\n .map((entry) => ({\n absolutePath: join(wikiDir(cwd), entry),\n relPath: join(\"wiki\", entry),\n }))\n .map((file) => ({\n absolutePath: file.absolutePath,\n relPath: relativeToRoot(root, file.absolutePath),\n }));\n}\n\nfunction relativeToRoot(root: string, absolutePath: string): string {\n // memory root is e.g. /tmp/x/.theokit/memory; wiki file is /tmp/x/.theokit/memory/wiki/foo.md\n // Strip the root + \"/\" prefix to get \"wiki/foo.md\".\n if (absolutePath.startsWith(`${root}/`)) return absolutePath.slice(root.length + 1);\n return absolutePath;\n}\n","import { createHash } from \"node:crypto\";\nimport { readdir, stat } from \"node:fs/promises\";\nimport { join, relative } from \"node:path\";\n\nimport type { MemorySearchHit, SearchOptions } from \"./index-manager-contract.js\";\nimport { memoryDir, memoryMdPath, notesDir } from \"./storage/markdown-store.js\";\nimport { discoverSessionFiles } from \"./storage/session-loader.js\";\nimport { discoverWikiFiles } from \"./storage/wiki-loader.js\";\n\n// ───── hybrid scoring helpers ─────────────────────────────────────────\n\n/** @internal */\nexport interface HybridWeights {\n vectorWeight: number;\n textWeight: number;\n total: number;\n}\n\n/** @internal */\nexport function resolveWeights(options: SearchOptions): HybridWeights {\n const vectorWeight = options.vectorWeight ?? 0.6;\n const textWeight = options.textWeight ?? 0.4;\n const total = vectorWeight + textWeight || 1;\n return { vectorWeight, textWeight, total };\n}\n\n/** @internal */\nexport function blendScores(\n hit: MemorySearchHit & { chunkId: number },\n vectorScore: number,\n weights: HybridWeights,\n): MemorySearchHit {\n const score =\n (vectorScore * weights.vectorWeight + hit.textScore * weights.textWeight) / weights.total;\n return {\n path: hit.path,\n startLine: hit.startLine,\n endLine: hit.endLine,\n score,\n textScore: hit.textScore,\n snippet: hit.snippet,\n source: hit.source,\n citation: hit.citation,\n ...(vectorScore > 0 ? { vectorScore } : {}),\n };\n}\n\n// ───── file discovery ─────────────────────────────────────────────────\n\n/** @internal */\nexport interface DiscoveredFile {\n absolutePath: string;\n relPath: string;\n source: \"memory\" | \"wiki\" | \"sessions\";\n}\n\n/**\n * Every `*.md` in `dir` as a discovered memory file, minus `skip`. A directory that does not exist\n * yet contributes nothing — the store is created lazily, and its absence is not an error.\n */\nasync function markdownFilesIn(\n dir: string,\n root: string,\n skip: readonly string[] = [],\n): Promise<DiscoveredFile[]> {\n let entries: string[];\n try {\n entries = await readdir(dir);\n } catch {\n return [];\n }\n return entries\n .filter((entry) => entry.endsWith(\".md\") && !skip.includes(entry))\n .map((entry) => ({\n absolutePath: join(dir, entry),\n relPath: relative(root, join(dir, entry)),\n source: \"memory\" as const,\n }));\n}\n\n/** @internal */\nexport async function collectMarkdownFiles(cwd: string): Promise<DiscoveredFile[]> {\n const root = memoryDir(cwd);\n const results: DiscoveredFile[] = [];\n // MEMORY.md\n try {\n await stat(memoryMdPath(cwd));\n results.push({\n absolutePath: memoryMdPath(cwd),\n relPath: relative(root, memoryMdPath(cwd)),\n source: \"memory\",\n });\n } catch {\n // skip\n }\n // <memoryDir>/*.md — one file per memory, the converged layout. MEMORY.md is the index and is\n // discovered above; picking it up twice would index every memory's link alongside its text.\n results.push(...(await markdownFilesIn(memoryDir(cwd), root, [\"MEMORY.md\"])));\n results.push(...(await markdownFilesIn(notesDir(cwd), root)));\n // wiki/*.md (Phase 10 — read-only supplements)\n const wikiFiles = await discoverWikiFiles(cwd);\n for (const wiki of wikiFiles) {\n results.push({\n absolutePath: wiki.absolutePath,\n relPath: wiki.relPath,\n source: \"wiki\",\n });\n }\n // sessions/*.md (ADR D20 — per-run summaries for corpus=\"sessions\" recall)\n const sessionFiles = await discoverSessionFiles(cwd);\n for (const session of sessionFiles) {\n results.push({\n absolutePath: session.absolutePath,\n relPath: session.relPath,\n source: \"sessions\",\n });\n }\n return results;\n}\n\n// ───── misc helpers ───────────────────────────────────────────────────\n\n/** @internal */\nexport function sha256(text: string): string {\n return createHash(\"sha256\").update(text).digest(\"hex\");\n}\n\n/** @internal */\nexport function truncateSnippet(text: string): string {\n const max = 500;\n return text.length <= max ? text : `${text.slice(0, max)}…`;\n}\n","import { ConfigurationError } from \"../../errors.js\";\nimport type { MemoryDb } from \"./index-db.js\";\n\n/**\n * Load the `sqlite-vec` extension into an opened SQLite connection.\n *\n * Wraps the native `load(db)` call from the `sqlite-vec` npm package with a\n * typed error path (EC-8 of the edge-case review) so callers see a\n * `sqlite_vec_unavailable` ConfigurationError instead of a raw native error.\n *\n * @internal\n */\nexport async function loadSqliteVecExtension(db: MemoryDb): Promise<void> {\n try {\n const mod = await import(\"sqlite-vec\");\n const loadFn = (mod as { load?: (db: unknown) => void }).load;\n if (typeof loadFn !== \"function\") {\n throw new Error(\"sqlite-vec module exposes no `load` export\");\n }\n loadFn(db);\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n throw new ConfigurationError(\n `sqlite-vec extension unavailable. Install \\`sqlite-vec\\` and ensure the native binary matches your Node + OS. Cause: ${message}`,\n { code: \"sqlite_vec_unavailable\", cause },\n );\n }\n}\n","import { createHash } from \"node:crypto\";\n\nimport type { MemoryChunk } from \"../types.js\";\n\n/**\n * Split a markdown document into semantically meaningful chunks (ADR D1 of\n * memory-system-peer-project-parity).\n *\n * Algorithm:\n * 1. Walk lines tracking the current heading (latest `^#+ ` line).\n * 2. Split chunks at the next heading boundary AND on blank-line paragraph\n * boundaries.\n * 3. If a single paragraph exceeds `maxChars`, split it at the nearest\n * whitespace ≤ maxChars (word-aligned per edge-case review EC-6) —\n * never mid-word.\n *\n * Mirrors peer-project's `chunkMarkdown` from\n * `packages/memory-host-sdk/src/host/chunk-markdown.ts`.\n *\n * @internal\n */\n\nexport interface ChunkMarkdownOptions {\n /** Maximum chars per chunk. Default 800. */\n maxChars?: number;\n /** Minimum chars per chunk (avoids splintering tiny lines). Default 80. */\n minChars?: number;\n}\n\nconst HEADING_RE = /^(#{1,6})\\s+(.+?)\\s*$/;\n\ninterface ChunkAccumulator {\n chunks: MemoryChunk[];\n lines: string[];\n start: number;\n heading: string | undefined;\n}\n\nexport function chunkMarkdown(text: string, options: ChunkMarkdownOptions = {}): MemoryChunk[] {\n const maxChars = options.maxChars ?? 800;\n if (text.length === 0) return [];\n const lines = text.split(\"\\n\");\n const acc: ChunkAccumulator = { chunks: [], lines: [], start: 1, heading: undefined };\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] ?? \"\";\n const lineNumber = i + 1;\n processLine(acc, line, lineNumber, maxChars);\n }\n flushAccumulator(acc, lines.length, maxChars);\n return acc.chunks;\n}\n\nfunction processLine(\n acc: ChunkAccumulator,\n line: string,\n lineNumber: number,\n maxChars: number,\n): void {\n const headingMatch = HEADING_RE.exec(line);\n const isBlank = line.trim().length === 0;\n if (headingMatch !== null && acc.lines.length > 0) {\n flushAccumulator(acc, lineNumber - 1, maxChars);\n }\n if (headingMatch !== null) acc.heading = headingMatch[2];\n acc.lines.push(line);\n if (isBlank && acc.lines.length > 1) {\n const joined = acc.lines.join(\"\\n\");\n if (joined.trim().length > 0) flushAccumulator(acc, lineNumber, maxChars);\n }\n}\n\nfunction flushAccumulator(acc: ChunkAccumulator, endLineExclusive: number, maxChars: number): void {\n if (acc.lines.length === 0) return;\n const chunkText = acc.lines.join(\"\\n\");\n if (chunkText.trim().length === 0) {\n acc.lines = [];\n acc.start = endLineExclusive + 1;\n return;\n }\n if (chunkText.length > maxChars) {\n pushOversizedSlices(acc.chunks, chunkText, acc.start, acc.heading, maxChars);\n } else {\n acc.chunks.push(buildChunk(chunkText, acc.start, endLineExclusive, acc.heading));\n }\n acc.lines = [];\n acc.start = endLineExclusive + 1;\n}\n\nfunction buildChunk(\n text: string,\n startLine: number,\n endLine: number,\n heading: string | undefined,\n): MemoryChunk {\n return {\n startLine,\n endLine,\n text,\n hash: createHash(\"sha256\").update(text).digest(\"hex\"),\n ...(heading !== undefined ? { heading } : {}),\n };\n}\n\nfunction pushOversizedSlices(\n chunks: MemoryChunk[],\n text: string,\n startLine: number,\n heading: string | undefined,\n maxChars: number,\n): void {\n let remaining = text;\n let lineCursor = startLine;\n while (remaining.length > maxChars) {\n const splitAt = findWordBoundarySplit(remaining, maxChars);\n const slice = remaining.slice(0, splitAt);\n const sliceLines = slice.split(\"\\n\").length;\n chunks.push(buildChunk(slice, lineCursor, lineCursor + sliceLines - 1, heading));\n remaining = remaining.slice(splitAt).replace(/^\\s+/, \"\");\n lineCursor += sliceLines - 1;\n }\n if (remaining.length > 0) {\n const sliceLines = remaining.split(\"\\n\").length;\n chunks.push(buildChunk(remaining, lineCursor, lineCursor + sliceLines - 1, heading));\n }\n}\n\n/**\n * Find a split point ≤ maxChars that lands on a whitespace boundary so we\n * don't slice a word in half. Falls back to maxChars if no whitespace is\n * within range (very rare — a single token > maxChars).\n */\nfunction findWordBoundarySplit(text: string, maxChars: number): number {\n if (text.length <= maxChars) return text.length;\n // Walk backward from maxChars looking for whitespace.\n for (let i = maxChars; i > Math.max(0, maxChars - 200); i--) {\n if (/\\s/.test(text[i] ?? \"x\")) return i;\n }\n // No whitespace within 200 chars of the cap — accept a hard split.\n return maxChars;\n}\n","import type { EmbeddingRuntime } from \"./embedding-adapter.js\";\nimport type { MemoryDb } from \"./index-db.js\";\n\n/**\n * Vector index helpers (ADR D2 + D4 of memory-system-peer-project-parity).\n *\n * Embeddings live in `embeddings(chunk_id, vec)` — a `vec0` virtual table\n * provided by the sqlite-vec extension. Embedding identity (providerId +\n * model + dimension) lives in the `meta` table; mismatches force a full\n * re-embed sweep (EC-1).\n *\n * @internal\n */\n\nexport const META_KEY_PROVIDER_ID = \"embedding.providerId\";\nexport const META_KEY_MODEL = \"embedding.model\";\nexport const META_KEY_DIMENSION = \"embedding.dimension\";\n\nexport interface EmbeddingIdentity {\n providerId: string;\n model: string;\n dimension: number;\n}\n\nexport function readEmbeddingIdentity(db: MemoryDb): EmbeddingIdentity | undefined {\n const get = (key: string): string | undefined => {\n const row = db.prepare(\"SELECT value FROM meta WHERE key = ?\").get(key);\n return row !== undefined ? String(row.value) : undefined;\n };\n const providerId = get(META_KEY_PROVIDER_ID);\n const model = get(META_KEY_MODEL);\n const dimRaw = get(META_KEY_DIMENSION);\n if (providerId === undefined || model === undefined || dimRaw === undefined) return undefined;\n const dimension = Number(dimRaw);\n if (!Number.isFinite(dimension) || dimension <= 0) return undefined;\n return { providerId, model, dimension };\n}\n\nexport function writeEmbeddingIdentity(db: MemoryDb, identity: EmbeddingIdentity): void {\n const stmt = db.prepare(\n \"INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value\",\n );\n stmt.run(META_KEY_PROVIDER_ID, identity.providerId);\n stmt.run(META_KEY_MODEL, identity.model);\n stmt.run(META_KEY_DIMENSION, String(identity.dimension));\n}\n\nexport function identityMatches(a: EmbeddingIdentity, b: EmbeddingIdentity): boolean {\n return a.providerId === b.providerId && a.model === b.model && a.dimension === b.dimension;\n}\n\nexport function dropVectorIndex(db: MemoryDb): void {\n db.exec(\"DROP TABLE IF EXISTS embeddings\");\n}\n\nexport function createVectorIndex(db: MemoryDb, dimension: number): void {\n db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS embeddings USING vec0(\n chunk_id INTEGER PRIMARY KEY,\n vec FLOAT[${dimension}]\n )`);\n}\n\n/** Pack a Float32Array into a Buffer suitable for sqlite-vec BLOB binding. */\nexport function packVector(vec: ReadonlyArray<number>): Buffer {\n const f32 = new Float32Array(vec.length);\n for (let i = 0; i < vec.length; i++) f32[i] = vec[i] ?? 0;\n return Buffer.from(f32.buffer);\n}\n\nexport function upsertEmbedding(db: MemoryDb, chunkId: number, vec: ReadonlyArray<number>): void {\n // sqlite-vec vec0 virtual tables don't support UPSERT — emulate via\n // DELETE-then-INSERT. vec0 REJECTS JS Number for chunk_id columns; it\n // requires BigInt binding. Verified via repro against vec0 v0.1.9.\n const id = BigInt(chunkId);\n db.prepare(\"DELETE FROM embeddings WHERE chunk_id = ?\").run(id);\n db.prepare(\"INSERT INTO embeddings (chunk_id, vec) VALUES (?, ?)\").run(id, packVector(vec));\n}\n\nexport interface VectorHitRow {\n chunk_id: number;\n distance: number;\n}\n\nexport function vectorSearch(\n db: MemoryDb,\n query: ReadonlyArray<number>,\n k: number,\n): VectorHitRow[] {\n // sqlite-vec returns distance (lower = closer). Use KNN syntax. k needs\n // a BigInt-typed binding too.\n const rows = db\n .prepare(\n `SELECT chunk_id, distance FROM embeddings\n WHERE vec MATCH ? AND k = ?\n ORDER BY distance`,\n )\n .all(packVector(query), BigInt(k));\n return rows.map((row) => ({ chunk_id: Number(row.chunk_id), distance: Number(row.distance) }));\n}\n\nexport interface EmbedAllArgs {\n db: MemoryDb;\n runtime: EmbeddingRuntime;\n}\n\n/** Embed every chunk that doesn't yet have a vector. */\nexport async function embedMissingChunks(args: EmbedAllArgs): Promise<number> {\n const rows = args.db\n .prepare(\n `SELECT chunks.id as id, chunks.text as text\n FROM chunks\n LEFT JOIN embeddings ON embeddings.chunk_id = chunks.id\n WHERE embeddings.chunk_id IS NULL`,\n )\n .all();\n if (rows.length === 0) return 0;\n const normalized = rows.map((row) => ({ id: Number(row.id), text: String(row.text ?? \"\") }));\n const vectors = await args.runtime.embed(normalized.map((r) => r.text));\n for (let i = 0; i < normalized.length; i++) {\n const row = normalized[i];\n const vector = vectors[i];\n if (row === undefined || vector === undefined) continue;\n upsertEmbedding(args.db, row.id, vector);\n }\n return normalized.length;\n}\n","import { createHash } from \"node:crypto\";\nimport { readFile, stat } from \"node:fs/promises\";\nimport { sanitizeFts5Query } from \"../persistence/fts5-sanitize.js\";\nimport type { EmbeddingRuntime } from \"./embedding-adapter.js\";\nimport { LruEmbeddingCache } from \"./embedding-cache.js\";\nimport { escapeLikePattern } from \"./escape-like-pattern.js\";\nimport { defaultIndexPath, type MemoryDb, openMemoryDb } from \"./index-db.js\";\nimport { assertValidBackend, openLanceIndex } from \"./index-manager-dispatch.js\";\nimport {\n blendScores,\n collectMarkdownFiles,\n resolveWeights,\n sha256,\n truncateSnippet,\n} from \"./index-manager-helpers.js\";\nimport { type MemoryIndex, parseSearchOptions } from \"./memory-index.js\";\nimport { loadSqliteVecExtension } from \"./sqlite-vec-loader.js\";\nimport { chunkMarkdown } from \"./storage/chunk-markdown.js\";\n\n// T4.1 — query-vector LRU cache (DR4 finding #1). Keyed by\n// sha256(query); caches the embedding vector so repeated search\n// queries skip the HTTP round-trip (p99 1.5-3s → ~0ms on hit).\n// Process-wide singleton with bounded capacity (default 2000 queries).\nconst queryVectorCache = new LruEmbeddingCache(2000);\n\nimport {\n createVectorIndex,\n dropVectorIndex,\n embedMissingChunks,\n identityMatches,\n readEmbeddingIdentity,\n vectorSearch,\n writeEmbeddingIdentity,\n} from \"./vec-index.js\";\n\n/**\n * Memory index manager (ADR D2). FTS5-only at Phase 3; vector index lands in\n * Phase 5.\n *\n * Lifecycle:\n * const idx = await IndexManager.open({ cwd });\n * await idx.sync();\n * const hits = await idx.search(\"query\");\n * idx.close();\n *\n * @internal\n */\n\n// T2.1 / ADR D433 — these types now live in `index-manager-contract.ts`\n// to break the 3-cycle memory cluster. Re-exported here for back-compat\n// with downstream importers that historically pulled from this file.\nexport type {\n IndexStatus,\n MemoryBackend,\n MemorySearchHit,\n OpenIndexOptions,\n SearchOptions,\n} from \"./index-manager-contract.js\";\n\nimport type {\n IndexStatus,\n MemorySearchHit,\n OpenIndexOptions,\n SearchOptions,\n} from \"./index-manager-contract.js\";\n\nexport class IndexManager implements MemoryIndex {\n private lastSyncMs: number | undefined;\n private vectorReady = false;\n\n private constructor(\n private readonly cwd: string,\n private readonly db: MemoryDb,\n private readonly embedding: EmbeddingRuntime | undefined,\n ) {}\n\n /**\n * Open a memory index. Dispatches to SQLite (default) or Lance (opt-in\n * via `backend: \"lance\"`). See `openLanceInternal` for Lance-specific\n * preconditions + typed errors.\n */\n static async open(opts: OpenIndexOptions & { backend: \"lance\" }): Promise<MemoryIndex>;\n static async open(\n opts: Omit<OpenIndexOptions, \"backend\"> | (OpenIndexOptions & { backend?: \"sqlite-vec\" }),\n ): Promise<IndexManager>;\n static async open(opts: OpenIndexOptions): Promise<MemoryIndex> {\n const backend = opts.backend ?? \"sqlite-vec\";\n assertValidBackend(backend);\n if (backend === \"lance\") return await openLanceIndex(opts);\n return await IndexManager.openSqliteInternal(opts);\n }\n\n /** Internal SQLite-path open. Renamed from previous public `open`. */\n private static async openSqliteInternal(opts: OpenIndexOptions): Promise<IndexManager> {\n const filePath = opts.filePath ?? defaultIndexPath(opts.cwd);\n const db = await openMemoryDb({ filePath });\n const manager = new IndexManager(opts.cwd, db, opts.embedding);\n if (opts.embedding !== undefined) await manager.initVectorBackend(opts.embedding);\n return manager;\n }\n\n private async initVectorBackend(runtime: EmbeddingRuntime): Promise<void> {\n await loadSqliteVecExtension(this.db);\n const currentIdentity = {\n providerId: runtime.id,\n model: runtime.model,\n dimension: runtime.dimension,\n };\n const persisted = readEmbeddingIdentity(this.db);\n if (persisted !== undefined && !identityMatches(persisted, currentIdentity)) {\n // EC-1: dimension/model/provider changed — drop the vector index and\n // force a full re-embed on next sync.\n dropVectorIndex(this.db);\n }\n createVectorIndex(this.db, runtime.dimension);\n writeEmbeddingIdentity(this.db, currentIdentity);\n this.vectorReady = true;\n }\n\n /** Walk the memory corpus + (re)index changed files. */\n async sync(): Promise<{\n filesScanned: number;\n filesUpdated: number;\n chunksWritten: number;\n chunksEmbedded: number;\n }> {\n const files = await collectMarkdownFiles(this.cwd);\n let filesUpdated = 0;\n let chunksWritten = 0;\n const existingByPath = this.loadFilesIndex();\n for (const entry of files) {\n const raw = await readFile(entry.absolutePath, \"utf8\");\n const hash = sha256(raw);\n const existing = existingByPath.get(entry.absolutePath);\n if (existing !== undefined && existing.hash === hash) continue;\n const stats = await stat(entry.absolutePath);\n const fileId = this.upsertFile(\n entry.absolutePath,\n entry.relPath,\n hash,\n stats.mtimeMs,\n entry.source,\n );\n this.deleteChunksForFile(fileId);\n const chunks = chunkMarkdown(raw);\n for (const chunk of chunks) {\n this.insertChunk(fileId, chunk.startLine, chunk.endLine, chunk.text, chunk.hash);\n }\n filesUpdated += 1;\n chunksWritten += chunks.length;\n }\n let chunksEmbedded = 0;\n if (this.vectorReady && this.embedding !== undefined) {\n chunksEmbedded = await embedMissingChunks({ db: this.db, runtime: this.embedding });\n }\n this.lastSyncMs = Date.now();\n return { filesScanned: files.length, filesUpdated, chunksWritten, chunksEmbedded };\n }\n\n async search(query: string, options: SearchOptions = {}): Promise<MemorySearchHit[]> {\n if (query.trim().length === 0) return [];\n const { maxResults, minScore } = parseSearchOptions(options);\n const textHits = this.ftsSearch(query, maxResults * 2);\n const vectorHitsById = await this.vectorSearchById(query, maxResults * 2);\n const combined = this.combineHybridScores(textHits, vectorHitsById, options);\n return combined\n .filter((h) => h.score >= minScore)\n .filter((h) => options.sources === undefined || options.sources.includes(h.source))\n .slice(0, maxResults);\n }\n\n status(): IndexStatus {\n const files = this.db.prepare(\"SELECT COUNT(*) as n FROM files\").get() ?? { n: 0 };\n const chunks = this.db.prepare(\"SELECT COUNT(*) as n FROM chunks\").get() ?? { n: 0 };\n const status: IndexStatus = {\n backend: this.vectorReady ? \"hybrid\" : \"fts-only\",\n filesIndexed: Number(files.n ?? 0),\n chunksIndexed: Number(chunks.n ?? 0),\n };\n if (this.lastSyncMs !== undefined) status.lastSyncMs = this.lastSyncMs;\n return status;\n }\n\n // ───── search internals ──────────────────────────────────────────────\n\n private ftsSearch(query: string, limit: number): Array<MemorySearchHit & { chunkId: number }> {\n // EC-3: short-circuit when sanitizer reduces input to empty string.\n // Calling `MATCH ''` would error inside FTS5 on some SQLite versions.\n const sanitized = sanitizeFts5Query(query);\n if (sanitized.length === 0) return [];\n const stmt = this.db.prepare(\n `SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,\n chunks.start_line as start_line, chunks.end_line as end_line,\n chunks.text as text, bm25(chunks_fts) as bm25_score\n FROM chunks_fts\n JOIN chunks ON chunks_fts.rowid = chunks.id\n JOIN files ON chunks.file_id = files.id\n WHERE chunks_fts MATCH ?\n ORDER BY bm25_score\n LIMIT ?`,\n );\n let rows: Array<Record<string, unknown>> = [];\n try {\n rows = stmt.all(sanitized, limit);\n } catch {\n // T4.8 — CJK fallback: FTS5's default tokenizer chokes on CJK\n // characters (no word boundaries). Instead of returning empty,\n // fall back to a LIKE search which handles CJK correctly (slower\n // but correct). ADR D64 documents the trigram-routing deferral.\n return this.likeSearchFallback(query, limit);\n }\n return rows.map((row) => {\n const bm25 = Number(row.bm25_score ?? 0);\n const textScore = bm25 < 0 ? 1 / (1 + Math.abs(bm25)) : 1 / (1 + bm25);\n const startLine = Number(row.start_line ?? 0);\n const endLine = Number(row.end_line ?? 0);\n const path = String(row.rel_path);\n return {\n path,\n startLine,\n endLine,\n score: textScore,\n textScore,\n snippet: truncateSnippet(String(row.text ?? \"\")),\n source: String(row.source) as \"memory\" | \"sessions\" | \"wiki\",\n citation: `${path}:${startLine}-${endLine}`,\n // sneak the chunk id through for the hybrid join below\n // (cast away later)\n chunkId: Number(row.id),\n } as MemorySearchHit & { chunkId: number };\n });\n }\n\n /**\n * T4.8 — LIKE-based fallback for CJK and other scripts that FTS5's\n * default tokenizer cannot segment. Slower than FTS5 (full table scan)\n * but correct for any Unicode input. Returns the same shape as\n * `ftsSearch` so callers are unaware of the fallback.\n */\n private likeSearchFallback(\n query: string,\n limit: number,\n ): Array<MemorySearchHit & { chunkId: number }> {\n const pattern = escapeLikePattern(query);\n const stmt = this.db.prepare(\n `SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,\n chunks.start_line as start_line, chunks.end_line as end_line,\n chunks.text as text\n FROM chunks\n JOIN files ON chunks.file_id = files.id\n WHERE chunks.text LIKE ? ESCAPE '\\\\'\n LIMIT ?`,\n );\n const rows = stmt.all(pattern, limit) as Array<Record<string, unknown>>;\n return rows.map((row) => {\n const path = String(row.rel_path ?? \"\");\n const startLine = Number(row.start_line ?? 0);\n const endLine = Number(row.end_line ?? 0);\n return {\n path,\n startLine,\n endLine,\n score: 0.5, // LIKE has no relevance score — use a neutral midpoint\n textScore: 0.5,\n snippet: truncateSnippet(String(row.text ?? \"\")),\n source: String(row.source) as \"memory\" | \"sessions\" | \"wiki\",\n citation: `${path}:${startLine}-${endLine}`,\n chunkId: Number(row.id),\n } as MemorySearchHit & { chunkId: number };\n });\n }\n\n private async vectorSearchById(\n query: string,\n limit: number,\n ): Promise<Map<number, { vectorScore: number; snippet?: string }>> {\n if (!this.vectorReady || this.embedding === undefined) return new Map();\n // T4.1 — query-vector LRU cache. The embed call is the p99 hottest\n // path (1.5-3s per hit). Cache by sha256(query) so repeated queries\n // skip the HTTP round-trip entirely. The embedding cache (T4.4\n // globalEmbeddingCache) catches text-level dedup; this catches the\n // query-level search-result dedup on top.\n const cacheKey = createHash(\"sha256\").update(query).digest(\"hex\");\n const cached = queryVectorCache.get(cacheKey);\n const queryVec = cached ?? (await this.embedding.embed([query]))[0];\n if (queryVec === undefined) return new Map();\n if (cached === undefined) queryVectorCache.set(cacheKey, queryVec);\n const rows = vectorSearch(this.db, queryVec, limit);\n // sqlite-vec distance: lower = closer. Normalize to 0..1 with higher = better.\n const out = new Map<number, { vectorScore: number }>();\n for (const row of rows) {\n const score = 1 / (1 + Math.max(0, row.distance));\n out.set(row.chunk_id, { vectorScore: score });\n }\n return out;\n }\n\n private combineHybridScores(\n textHits: Array<MemorySearchHit & { chunkId: number }>,\n vectorHitsById: Map<number, { vectorScore: number }>,\n options: SearchOptions,\n ): MemorySearchHit[] {\n const weights = resolveWeights(options);\n const merged = this.mergeHits(textHits, vectorHitsById);\n const combined = [...merged.values()].map((hit) =>\n blendScores(hit, vectorHitsById.get(hit.chunkId)?.vectorScore ?? 0, weights),\n );\n return combined.sort((a, b) => b.score - a.score);\n }\n\n private mergeHits(\n textHits: Array<MemorySearchHit & { chunkId: number }>,\n vectorHitsById: Map<number, { vectorScore: number }>,\n ): Map<number, MemorySearchHit & { chunkId: number }> {\n const merged = new Map<number, MemorySearchHit & { chunkId: number }>();\n for (const hit of textHits) merged.set(hit.chunkId, hit);\n const missingIds = [...vectorHitsById.keys()].filter((id) => !merged.has(id));\n if (missingIds.length > 0) {\n for (const hit of this.fetchChunksByIds(missingIds)) {\n merged.set(hit.chunkId, { ...hit, score: 0, textScore: 0 });\n }\n }\n return merged;\n }\n\n private fetchChunksByIds(\n ids: ReadonlyArray<number>,\n ): Array<MemorySearchHit & { chunkId: number }> {\n if (ids.length === 0) return [];\n const placeholders = ids.map(() => \"?\").join(\",\");\n const rows = this.db\n .prepare(\n `SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,\n chunks.start_line as start_line, chunks.end_line as end_line,\n chunks.text as text\n FROM chunks JOIN files ON chunks.file_id = files.id\n WHERE chunks.id IN (${placeholders})`,\n )\n .all(...ids);\n return rows.map((row) => {\n const startLine = Number(row.start_line ?? 0);\n const endLine = Number(row.end_line ?? 0);\n const path = String(row.rel_path);\n return {\n chunkId: Number(row.id),\n path,\n startLine,\n endLine,\n score: 0,\n textScore: 0,\n snippet: truncateSnippet(String(row.text ?? \"\")),\n source: String(row.source) as \"memory\" | \"sessions\" | \"wiki\",\n citation: `${path}:${startLine}-${endLine}`,\n };\n });\n }\n\n // ───── persistence helpers ─────────────────────────────────────────\n\n private loadFilesIndex(): Map<string, { id: number; hash: string }> {\n const rows = this.db.prepare(\"SELECT id, path, hash FROM files\").all() as Array<{\n id: number;\n path: string;\n hash: string;\n }>;\n return new Map(rows.map((row) => [row.path, { id: row.id, hash: row.hash }]));\n }\n\n private upsertFile(\n absPath: string,\n relPath: string,\n hash: string,\n mtimeMs: number,\n source: \"memory\" | \"wiki\" | \"sessions\" = \"memory\",\n ): number {\n const stmt = this.db.prepare(\n `INSERT INTO files (path, rel_path, mtime, hash, source) VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(path) DO UPDATE SET hash = excluded.hash, mtime = excluded.mtime, source = excluded.source\n RETURNING id`,\n );\n const row = stmt.get(absPath, relPath, Math.floor(mtimeMs), hash, source) as { id: number };\n return row.id;\n }\n\n private deleteChunksForFile(fileId: number): void {\n this.db.prepare(\"DELETE FROM chunks WHERE file_id = ?\").run(fileId);\n }\n\n private insertChunk(\n fileId: number,\n startLine: number,\n endLine: number,\n text: string,\n hash: string,\n ): void {\n this.db\n .prepare(\n \"INSERT INTO chunks (file_id, start_line, end_line, text, hash) VALUES (?, ?, ?, ?, ?)\",\n )\n .run(fileId, startLine, endLine, text, hash);\n }\n\n close(): void {\n this.db.close();\n }\n}\n\n// Replaced by `sanitizeFts5Query` from `internal/persistence/fts5-sanitize.ts`\n// (T5.2, ADR D64). The new sanitizer is the 6-step port of Hermes'\n// `_sanitize_fts5_query` and handles hyphens/dots/underscores correctly\n// without quoting every token.\n"]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { replaceFileAtomic } from './chunk-VF7EWVDG.js';
|
|
2
2
|
import { redactSecrets } from './chunk-T7XEKOVW.js';
|
|
3
|
-
import { randomUUID } from 'crypto';
|
|
3
|
+
import { randomUUID, createHash } from 'crypto';
|
|
4
4
|
import { mkdir, readFile } from 'fs/promises';
|
|
5
5
|
import { homedir } from 'os';
|
|
6
6
|
import { join, dirname } from 'path';
|
|
@@ -215,7 +215,24 @@ function expandTilde(p) {
|
|
|
215
215
|
if (p.startsWith("~/")) return join(homedir(), p.slice(2));
|
|
216
216
|
return p;
|
|
217
217
|
}
|
|
218
|
+
var SESSION_NAMESPACE = Buffer.from("b7a1f0c94e3d4a1b8f26d05c3a91e7d2", "hex");
|
|
219
|
+
var UUID_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
220
|
+
function isSessionUuid(id) {
|
|
221
|
+
return UUID_SHAPE.test(id);
|
|
222
|
+
}
|
|
223
|
+
function sessionUuidFor(id) {
|
|
224
|
+
if (isSessionUuid(id)) return id.toLowerCase();
|
|
225
|
+
const hash = createHash("sha256").update(Buffer.concat([SESSION_NAMESPACE, Buffer.from(id, "utf8")])).digest();
|
|
226
|
+
const bytes = Buffer.from(hash.subarray(0, 16));
|
|
227
|
+
bytes[6] = bytes[6] & 15 | 128;
|
|
228
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
229
|
+
const hex = bytes.toString("hex");
|
|
230
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
231
|
+
}
|
|
218
232
|
function transcriptPath(baseDir, cwd, sessionId) {
|
|
233
|
+
return join(baseDir, "projects", encodeProjectDir(cwd), `${sessionUuidFor(sessionId)}.jsonl`);
|
|
234
|
+
}
|
|
235
|
+
function legacyTranscriptPath(baseDir, cwd, sessionId) {
|
|
219
236
|
return join(baseDir, "projects", encodeProjectDir(cwd), `${safeSessionId(sessionId)}.jsonl`);
|
|
220
237
|
}
|
|
221
238
|
async function writeTranscript(path, records) {
|
|
@@ -246,6 +263,6 @@ async function readTranscript(path) {
|
|
|
246
263
|
return raw.split("\n").map(parseRecordLine).filter((r) => r !== void 0);
|
|
247
264
|
}
|
|
248
265
|
|
|
249
|
-
export { SessionTranscript, defaultBaseDir, encodeProjectDir, expandTilde, readTranscript, reconstructMessages, safeSessionId, transcriptPath, transcriptRoot, writeTranscript };
|
|
250
|
-
//# sourceMappingURL=chunk-
|
|
251
|
-
//# sourceMappingURL=chunk-
|
|
266
|
+
export { SessionTranscript, defaultBaseDir, encodeProjectDir, expandTilde, isSessionUuid, legacyTranscriptPath, readTranscript, reconstructMessages, safeSessionId, sessionUuidFor, transcriptPath, transcriptRoot, writeTranscript };
|
|
267
|
+
//# sourceMappingURL=chunk-FKMUFNQE.js.map
|
|
268
|
+
//# sourceMappingURL=chunk-FKMUFNQE.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/persistence/session-transcript.ts"],"names":[],"mappings":";;;;;;;AAkDO,SAAS,iBAAiB,GAAA,EAAqB;AACpD,EAAA,OAAO,GAAA,CAAI,OAAA,CAAQ,eAAA,EAAiB,GAAG,CAAA;AACzC;AAGO,SAAS,cAAc,EAAA,EAAoB;AAChD,EAAA,OAAO,EAAA,CAAG,OAAA,CAAQ,iBAAA,EAAmB,GAAG,CAAA;AAC1C;AAEA,IAAM,GAAA,GAAM,CAAC,CAAA,KAAsB,aAAA,CAAc,CAAC,CAAA;AAGlD,SAAS,YAAY,KAAA,EAAyB;AAC5C,EAAA,I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,EAC9E,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,MAAA;AAAA,EACT;AACF;AAGA,eAAsB,eAAe,IAAA,EAAwC;AAC3E,EAAA,IAAI,GAAA;AACJ,EAAA,IAAI;AACF,IAAA,GAAA,GAAM,MAAM,QAAA,CAAS,IAAA,EAAM,MAAM,CAAA;AAAA,EACnC,SAAS,KAAA,EAAO;AACd,IAAA,IAAK,KAAA,CAAgC,IAAA,KAAS,QAAA,EAAU,OAAO,EAAC;AAChE,IAAA,MAAM,KAAA;AAAA,EACR;AACA,EAAA,OAAO,GAAA,CACJ,KAAA,CAAM,IAAI,CAAA,CACV,GAAA,CAAI,eAAe,CAAA,CACnB,MAAA,CAAO,CAAC,CAAA,KAA0B,CAAA,KAAM,MAAS,CAAA;AACtD","file":"chunk-FKMUFNQE.js","sourcesContent":["/**\n * SE40 — native session transcript (Claude-Code-compatible on-disk shape, theokit-native names).\n *\n * The theokit session format IS the Claude Code record shape (a `uuid`/`parentUuid` DAG of records with\n * structured `text`/`tool_use`/`tool_result`/`thinking` blocks) — so the ecosystem's read-side tools\n * parse our sessions AND, pointed at `~/.claude`, the Claude Code CLI can `--continue` them. This module\n * is the PURE core: append-per-turn record builders + the DAG reader that rebuilds `LlmMessage[]` for\n * resume. File I/O + loop wiring + append-only compaction live in the FS store.\n *\n * Reader mirrors `claude-code-log` dag.py: leaf = a uuid never used as a parentUuid; walk parentUuid to a\n * root (cycle-break); dedup a uuid across sessions keeping the earliest; a `compact_boundary` root\n * terminates the walk so a resume-after-compaction replays only the post-boundary continuation.\n *\n * reference: knowledge-base/references/claude-code-log/claude_code_log/dag.py + models.py\n */\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { mkdir, readFile } from \"node:fs/promises\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport type { SessionRecord, TranscriptBlock } from \"../../types/session-record.js\";\nimport type { LlmContentPart, LlmMessage, LlmToolResultPart } from \"../llm/types.js\";\nimport { redactSecrets } from \"../security/redact.js\";\nimport { replaceFileAtomic } from \"./atomic-write.js\";\n\n// The `SessionRecord` contract now lives in the domain `types/` layer (SE46 DIP\n// direction). Re-exported here so existing importers of this DAG-core module\n// keep resolving the same name.\nexport type { SessionRecord } from \"../../types/session-record.js\";\n\nexport interface SessionTranscriptOptions {\n cwd: string;\n sessionId: string;\n model: string;\n version?: string;\n}\n\nexport interface AssistantTurn {\n text?: string;\n thinking?: string;\n /**\n * theokit#122 — the provider's signature for the thinking block. Written into the `thinking`\n * record block (`Block` already declared `signature?`), so a resumed session can replay the block\n * exactly as the provider issued it.\n */\n thinkingSignature?: string;\n toolCalls?: Array<{ id: string; name: string; input: Record<string, unknown> }>;\n}\n\n/** Claude Code path convention: cwd with every non-alphanumeric replaced by `-`. */\nexport function encodeProjectDir(cwd: string): string {\n return cwd.replace(/[^a-zA-Z0-9]/g, \"-\");\n}\n\n/** Make a caller-supplied session id safe as a path component (no traversal). */\nexport function safeSessionId(id: string): string {\n return id.replace(/[^a-zA-Z0-9_-]/g, \"-\");\n}\n\nconst red = (s: string): string => redactSecrets(s);\n\n/** Deep-redact a structured value (tool input) preserving object shape. */\nfunction redactValue(value: unknown): unknown {\n try {\n return JSON.parse(redactSecrets(JSON.stringify(value ?? null)));\n } catch {\n return redactSecrets(String(value));\n }\n}\n\n// M94 — it was `Record<string, unknown>`. The published type describes the same shape this file\n// has always produced; the local alias now points at it so writer and reader cannot\n// diverge silently.\ntype Block = TranscriptBlock;\n\n/**\n * Builds a session transcript append-by-append, maintaining the `parentUuid` chain. Each turn mints a\n * fresh `uuid` and parents on the previous record; `appendCompactBoundary` starts a NEW ROOT.\n */\nexport class SessionTranscript {\n #records: SessionRecord[] = [];\n #last: string | null = null;\n #opts: SessionTranscriptOptions;\n\n constructor(opts: SessionTranscriptOptions) {\n this.#opts = opts;\n }\n\n /**\n * Seed a transcript from records already on disk so a subsequent append parents\n * on the existing DAG leaf (the last record in file order). Prior records are\n * re-emitted verbatim by {@link records}, so the whole file rewrites atomically\n * as one append-only line set — never shrinking (SE40 compaction is append-only).\n */\n static fromRecords(\n prior: readonly SessionRecord[],\n opts: SessionTranscriptOptions,\n ): SessionTranscript {\n const t = new SessionTranscript(opts);\n t.#records = [...prior];\n t.#last = prior.length > 0 ? (prior[prior.length - 1]?.uuid ?? null) : null;\n return t;\n }\n\n #push(\n rec: Omit<SessionRecord, \"uuid\" | \"parentUuid\" | \"sessionId\" | \"timestamp\">,\n ): SessionRecord {\n const full: SessionRecord = {\n ...rec,\n uuid: randomUUID(),\n parentUuid: this.#last,\n sessionId: this.#opts.sessionId,\n timestamp: new Date().toISOString(),\n isSidechain: false,\n userType: \"external\",\n cwd: this.#opts.cwd,\n version: this.#opts.version ?? \"1.0.0-theokit\",\n };\n this.#records.push(full);\n this.#last = full.uuid;\n return full;\n }\n\n appendUserTurn(text: string): SessionRecord {\n return this.#push({\n type: \"user\",\n message: { role: \"user\", content: [{ type: \"text\", text: red(text) }] },\n });\n }\n\n appendAssistantTurn(turn: AssistantTurn): SessionRecord {\n const content: Block[] = [];\n if (turn.thinking) {\n // theokit#122 — the signature is computed by the provider over the ORIGINAL text, so it is\n // only valid while the text is byte-identical. Redaction rewrites the text; keeping the\n // signature next to a masked body persists a pair that Anthropic rejects with\n // `400 \"thinking blocks cannot be modified\"` — the very failure this issue exists to remove.\n //\n // So redaction WINS and the signature is dropped. The block survives as display-only history\n // (`thinkingToWireBlock` already refuses to replay an unsigned block), which loses one block\n // of context; keeping a signature that cannot verify would lose the whole turn.\n //\n // The signature itself is never redacted — it is an opaque provider token with no user\n // content — but that was only half the reasoning the first version of this fix wrote down.\n const redactedThinking = red(turn.thinking);\n const signatureStillValid =\n turn.thinkingSignature !== undefined && redactedThinking === turn.thinking;\n content.push({\n type: \"thinking\",\n thinking: redactedThinking,\n ...(signatureStillValid ? { signature: turn.thinkingSignature } : {}),\n });\n }\n if (turn.text) content.push({ type: \"text\", text: red(turn.text) });\n for (const c of turn.toolCalls ?? []) {\n content.push({ type: \"tool_use\", id: c.id, name: c.name, input: redactValue(c.input) });\n }\n return this.#push({\n type: \"assistant\",\n message: {\n id: randomUUID(),\n type: \"message\",\n role: \"assistant\",\n model: this.#opts.model,\n content,\n },\n });\n }\n\n appendToolResults(\n results: Array<{ toolUseId: string; content: string; isError?: boolean }>,\n ): SessionRecord {\n const content: Block[] = results.map((r) => ({\n type: \"tool_result\",\n tool_use_id: r.toolUseId,\n content: red(r.content),\n is_error: r.isError === true,\n }));\n return this.#push({ type: \"user\", message: { role: \"user\", content } });\n }\n\n /** Append-only compaction: a `compact_boundary` system record becomes a NEW ROOT (parentUuid null). */\n appendCompactBoundary(meta: { preTokens: number; trigger: string }): SessionRecord {\n const rec: SessionRecord = {\n type: \"system\",\n uuid: randomUUID(),\n parentUuid: null,\n sessionId: this.#opts.sessionId,\n timestamp: new Date().toISOString(),\n subtype: \"compact_boundary\",\n compactMetadata: meta,\n isSidechain: false,\n userType: \"external\",\n cwd: this.#opts.cwd,\n version: this.#opts.version ?? \"1.0.0-theokit\",\n };\n this.#records.push(rec);\n this.#last = rec.uuid;\n return rec;\n }\n\n records(): readonly SessionRecord[] {\n return this.#records;\n }\n}\n\n// ─── Reader (DAG → LlmMessage[]) ──────────────────────────────────────────────────────────────────\n\n/** Earliest timestamp seen per session id. */\nfunction sessionFirstTimestamps(records: readonly SessionRecord[]): Map<string, string> {\n const first = new Map<string, string>();\n for (const r of records) {\n const cur = first.get(r.sessionId);\n if (cur === undefined || r.timestamp < cur) first.set(r.sessionId, r.timestamp);\n }\n return first;\n}\n\n/** Dedup a uuid across sessions: keep the record whose session's earliest timestamp is smallest. */\nfunction dedupByUuid(records: readonly SessionRecord[]): Map<string, SessionRecord> {\n const firstTs = sessionFirstTimestamps(records);\n const byUuid = new Map<string, SessionRecord>();\n for (const r of records) {\n const existing = byUuid.get(r.uuid);\n const wins =\n existing === undefined ||\n (firstTs.get(r.sessionId) ?? \"\") < (firstTs.get(existing.sessionId) ?? \"\");\n if (wins) byUuid.set(r.uuid, r);\n }\n return byUuid;\n}\n\n/**\n * Map one structured block to an `LlmContentPart`.\n *\n * theokit#122 — thinking blocks used to be DROPPED here, which is why an extended-thinking session\n * could not be resumed: the block never made it back into the replayed messages, so the provider saw\n * a conversation whose assistant turn had lost its thinking. They are now reconstructed with their\n * signature; the Anthropic wire re-serializes signed blocks and skips unsigned ones.\n */\nfunction thinkingBlockToPart(b: Extract<Block, { type: \"thinking\" }>): LlmContentPart {\n return {\n type: \"thinking\",\n text: String(b.thinking ?? \"\"),\n ...(b.signature !== undefined ? { signature: String(b.signature) } : {}),\n };\n}\n\nfunction blockToPart(b: Block): LlmContentPart | undefined {\n if (b.type === \"text\") return { type: \"text\", text: String(b.text ?? \"\") };\n if (b.type === \"thinking\") return thinkingBlockToPart(b);\n if (b.type === \"tool_use\") {\n return {\n type: \"tool_use\",\n id: String(b.id),\n name: String(b.name),\n input: (b.input as Record<string, unknown>) ?? {},\n };\n }\n if (b.type === \"tool_result\") {\n const tr: LlmToolResultPart = {\n type: \"tool_result\",\n toolUseId: String(b.tool_use_id),\n content: typeof b.content === \"string\" ? b.content : JSON.stringify(b.content),\n isError: b.is_error === true,\n };\n return tr;\n }\n return undefined;\n}\n\n/** Map one record to an LlmMessage; `undefined` for non-conversational (system) records. */\nfunction recordToMessage(rec: SessionRecord): LlmMessage | undefined {\n if (rec.type !== \"user\" && rec.type !== \"assistant\") return undefined;\n const blocks = rec.message?.content ?? [];\n const parts = blocks.map(blockToPart).filter((p): p is LlmContentPart => p !== undefined);\n return { role: rec.type, content: parts };\n}\n\n/** The most-recent leaf: the LAST record (in input order) whose uuid is never used as a parentUuid. */\nfunction findLatestLeaf(\n records: readonly SessionRecord[],\n byUuid: Map<string, SessionRecord>,\n parents: Set<string>,\n): SessionRecord | undefined {\n let leaf: SessionRecord | undefined;\n for (const r of records) {\n if (byUuid.get(r.uuid) === r && !parents.has(r.uuid)) leaf = r;\n }\n return leaf;\n}\n\n/** Walk parentUuid from a leaf to a root (cycle-safe), returning root→leaf order. */\nfunction walkToRoot(leaf: SessionRecord, byUuid: Map<string, SessionRecord>): SessionRecord[] {\n const chain: SessionRecord[] = [];\n const seen = new Set<string>();\n let cur: SessionRecord | undefined = leaf;\n while (cur !== undefined && !seen.has(cur.uuid)) {\n seen.add(cur.uuid);\n chain.push(cur);\n cur = cur.parentUuid !== null ? byUuid.get(cur.parentUuid) : undefined;\n }\n return chain.reverse();\n}\n\n/**\n * Rebuild the resumable `LlmMessage[]` from transcript records: dedup → find the most-recent leaf →\n * walk `parentUuid` to a root (a `compact_boundary` root terminates the walk) → map to LlmMessages.\n * Returns them in root→leaf (chronological replay) order.\n */\nexport function reconstructMessages(records: readonly SessionRecord[]): LlmMessage[] {\n const byUuid = dedupByUuid(records);\n const parents = new Set<string>();\n for (const r of byUuid.values()) if (r.parentUuid) parents.add(r.parentUuid);\n const leaf = findLatestLeaf(records, byUuid, parents);\n if (leaf === undefined) return [];\n\n const msgs: LlmMessage[] = [];\n for (const rec of walkToRoot(leaf, byUuid)) {\n const m = recordToMessage(rec);\n if (m !== undefined) msgs.push(m);\n }\n return msgs;\n}\n\n// ─── File I/O (the on-disk Claude layout) ─────────────────────────────────────────────────────────\n\n/**\n * Root of the transcript state.\n *\n * `THEOKIT_HOME` wins; the fallback is `~/.theokit`. Home-anchored on purpose, and NOT\n * `paths.ts`'s `getTheokitHome(cwd)`: that one falls back to `<cwd>/.theokit`, and switching\n * by it would move the transcript of everyone who does **not** set the variable. The sibling with the\n * right shape is `catalog-source-models-dev.ts` (M94 ADR-2).\n *\n * Before M94 this function ignored the env var, so whoever set it had their state split in\n * two silently — sessions stayed in `~/.theokit` while the rest of the SDK migrated.\n */\nexport function transcriptRoot(): string {\n const override = process.env.THEOKIT_HOME?.trim();\n if (override !== undefined && override.length > 0) return override;\n return join(homedir(), \".theokit\");\n}\n\n/** @deprecated Use {@link transcriptRoot}. Kept as an alias — same value. */\nexport function defaultBaseDir(): string {\n return transcriptRoot();\n}\n\n/**\n * Expand a leading `~` / `~/` to the user's home dir. `node:path` does NOT expand `~`, so a\n * `baseDir: \"~/.claude\"` (the documented Claude Code CLI interop path) would otherwise resolve to a\n * literal `./~/.claude` under cwd and the CLI would never find the session. Absolute or relative\n * paths without a leading tilde pass through untouched.\n */\nexport function expandTilde(p: string): string {\n if (p === \"~\") return homedir();\n if (p.startsWith(\"~/\")) return join(homedir(), p.slice(2));\n return p;\n}\n\n/**\n * The fixed namespace for deriving a session UUID from an agent id (RFC 9562 § 5.8, version 8).\n *\n * A constant, because the derivation must be STABLE FOREVER: it is what lets the SDK find the\n * session it wrote last week without storing an id-to-filename map anywhere. Changing this value\n * orphans every transcript ever written.\n */\nconst SESSION_NAMESPACE = Buffer.from(\"b7a1f0c94e3d4a1b8f26d05c3a91e7d2\", \"hex\");\n\nconst UUID_SHAPE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n/** Is this id already a canonical UUID, and therefore usable as a filename verbatim? */\nexport function isSessionUuid(id: string): boolean {\n return UUID_SHAPE.test(id);\n}\n\n/**\n * The transcript filename for an agent id — always a UUID.\n *\n * #400: the Claude Code CLI resumes a transcript ONLY when its basename is a UUID. Measured against\n * CLI 2.1.236: `<uuid>.jsonl` resumes; `agent-<uuid>.jsonl` and `billing-bot.jsonl` are both ignored,\n * with no error — the session simply is not offered. So a session written under a human-readable\n * agent id was invisible to `claude --continue`, which is the interoperability this project claims\n * as its difference from a proprietary session store.\n *\n * An id that is ALREADY a UUID passes through verbatim, so a transcript Claude Code wrote keeps its\n * own name and the two directions stay symmetric. Anything else is derived with a UUIDv8, which is\n * deterministic: the same agent id always yields the same filename, so nothing has to be persisted\n * to map one back to the other.\n *\n * A DERIVED name is version 8 — RFC 9562's slot for a UUID whose bits come from an\n * implementation-defined scheme, which is exactly what this is. The obvious alternative was v5, but\n * RFC 4122 fixes v5's hash to SHA-1, and reaching for SHA-1 in 2026 means either shipping a weak\n * primitive or arguing with every scanner that flags it, forever. v8 lets the hash be SHA-256 and\n * lets the version nibble say honestly that this is our scheme rather than a standard one.\n *\n * There is no security claim here either way — no secret, no signature, and nothing an attacker\n * gains by colliding two agent ids inside one consumer's own directory. The hash is a naming\n * function. The point of preferring SHA-256 is not that SHA-1 was exploitable here; it is that a\n * weak primitive in the tree costs a permanent argument with every scanner that sees it.\n *\n * The version nibble was measured, not assumed: CLI 2.1.236 resumes a v8-named transcript exactly as\n * it does a v4 one.\n */\nexport function sessionUuidFor(id: string): string {\n if (isSessionUuid(id)) return id.toLowerCase();\n const hash = createHash(\"sha256\")\n .update(Buffer.concat([SESSION_NAMESPACE, Buffer.from(id, \"utf8\")]))\n .digest();\n const bytes = Buffer.from(hash.subarray(0, 16));\n bytes[6] = ((bytes[6] as number) & 0x0f) | 0x80; // version 8 — RFC 9562 custom\n bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80; // RFC 9562 variant\n const hex = bytes.toString(\"hex\");\n return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;\n}\n\n/** The `.jsonl` path for a session: `<baseDir>/projects/<encoded-cwd>/<session-uuid>.jsonl`. */\nexport function transcriptPath(baseDir: string, cwd: string, sessionId: string): string {\n return join(baseDir, \"projects\", encodeProjectDir(cwd), `${sessionUuidFor(sessionId)}.jsonl`);\n}\n\n/**\n * The path this session used BEFORE #400 made transcript filenames UUIDs.\n *\n * Kept so an existing transcript is never orphaned: {@link FsSessionStore} prefers this file when it\n * exists, so history written under the old scheme keeps accumulating in the same file instead of\n * being silently abandoned for a fresh one under the new name.\n */\nexport function legacyTranscriptPath(baseDir: string, cwd: string, sessionId: string): string {\n return join(baseDir, \"projects\", encodeProjectDir(cwd), `${safeSessionId(sessionId)}.jsonl`);\n}\n\n/** Write records as one JSONL line each (atomic; parent dir created). Returns the path. */\nexport async function writeTranscript(\n path: string,\n records: readonly SessionRecord[],\n): Promise<string> {\n await mkdir(dirname(path), { recursive: true });\n const body = records.map((r) => JSON.stringify(r)).join(\"\\n\");\n await replaceFileAtomic(path, records.length > 0 ? `${body}\\n` : \"\");\n return path;\n}\n\n/** Parse one JSONL line to a record; `undefined` for blank/torn/invalid lines (skipped on read). */\nfunction parseRecordLine(line: string): SessionRecord | undefined {\n const trimmed = line.trim();\n if (trimmed.length === 0) return undefined;\n try {\n const rec = JSON.parse(trimmed) as SessionRecord;\n return typeof rec.uuid === \"string\" && typeof rec.type === \"string\" ? rec : undefined;\n } catch {\n return undefined; // a torn last line (crash mid-write) — the rest of the DAG still reconstructs\n }\n}\n\n/** Parse a transcript `.jsonl` into records; a missing file yields `[]`; malformed lines are skipped. */\nexport async function readTranscript(path: string): Promise<SessionRecord[]> {\n let raw: string;\n try {\n raw = await readFile(path, \"utf8\");\n } catch (cause) {\n if ((cause as NodeJS.ErrnoException).code === \"ENOENT\") return [];\n throw cause;\n }\n return raw\n .split(\"\\n\")\n .map(parseRecordLine)\n .filter((r): r is SessionRecord => r !== undefined);\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { reconstructMessages, SessionTranscript } from './chunk-
|
|
1
|
+
import { reconstructMessages, SessionTranscript } from './chunk-FKMUFNQE.js';
|
|
2
2
|
|
|
3
3
|
// src/internal/session/agent-session-store.ts
|
|
4
4
|
function seedTranscript(prior, opts) {
|
|
@@ -101,5 +101,5 @@ async function appendCompactBoundaryRecord(store, loc, sessionId, meta) {
|
|
|
101
101
|
}
|
|
102
102
|
|
|
103
103
|
export { appendCompactBoundaryRecord, persistTurn, readSessionMessages };
|
|
104
|
-
//# sourceMappingURL=chunk-
|
|
105
|
-
//# sourceMappingURL=chunk-
|
|
104
|
+
//# sourceMappingURL=chunk-G24KZRSA.js.map
|
|
105
|
+
//# sourceMappingURL=chunk-G24KZRSA.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/session/agent-session-store.ts"],"names":[],"mappings":";;;AA+B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Q4.js","sourcesContent":["/**\n * SE40 — native session store over the Claude-shaped `.jsonl` transcript.\n *\n * The theokit session format IS the Claude Code record shape (see\n * `../../persistence/session-transcript.ts`). This module owns the FS lifecycle:\n * read existing records, seed a {@link SessionTranscript}'s parent chain, append\n * the new turn (user + assistant/tool blocks), and write append-only. Compaction\n * appends a `compact_boundary` record (a new root) — it NEVER shrinks the line\n * set (that would break the DAG). Reads reconstruct `LlmMessage[]` via\n * {@link reconstructMessages}, narrowed to the in-memory {@link SessionMessage}.\n *\n * @internal\n */\n\nimport type { ToolResultContentBlock } from \"../../types/content-blocks.js\";\nimport type { ConversationStep, ConversationTurn } from \"../../types/conversation.js\";\nimport type { SessionStore } from \"../../types/session-store.js\";\nimport {\n type AssistantTurn,\n reconstructMessages,\n type SessionRecord,\n SessionTranscript,\n} from \"../persistence/session-transcript.js\";\nimport type { SessionMessage, SessionMessagePart } from \"./session-types.js\";\n\n/**\n * Seed a {@link SessionTranscript} from the already-on-disk records so a new\n * append parents correctly on the existing DAG leaf. The transcript re-emits the\n * seeded records verbatim before the new turn, so the whole file rewrites atomically\n * as one append-only line set. Returns the transcript primed with the prior records.\n */\nfunction seedTranscript(\n prior: readonly SessionRecord[],\n opts: { cwd: string; sessionId: string; model: string },\n): SessionTranscript {\n return SessionTranscript.fromRecords(prior, opts);\n}\n\n/** The turn to persist: the user's text plus the rich per-turn conversation view. */\nexport interface PersistTurnInput {\n userText: string;\n conversation: readonly ConversationTurn[];\n /**\n * M50 — when supplied, size-driven auto-compaction runs in the SAME write chain after the turn\n * persists (usage real vs the model's context window; summarizer injected by the caller).\n */\n autoCompact?: {\n usageTotal?: number | undefined;\n contextWindow?: number | undefined;\n summarize: (\n messages: readonly import(\"../../compaction.js\").CompressibleMessage[],\n ) => Promise<string>;\n };\n}\n\ninterface MappedTurn {\n assistant: AssistantTurn;\n toolResults: Array<{ toolUseId: string; content: string; isError?: boolean }>;\n}\n\n/**\n * theokit#122 — record the turn's thinking block, signature included.\n *\n * The signature is what makes the block replayable: without it the resumed turn is rejected by\n * Anthropic with `400 \"thinking blocks cannot be modified\"`.\n */\nfunction applyThinkingStep(\n assistant: AssistantTurn,\n message: { text: string; signature?: string },\n): void {\n assistant.thinking = message.text;\n if (message.signature !== undefined) assistant.thinkingSignature = message.signature;\n}\n\n/** Fold one agent turn's steps into an assistant record + paired tool results. */\nfunction mapAgentTurn(steps: readonly ConversationStep[]): MappedTurn {\n const assistant: AssistantTurn = {};\n const toolResults: MappedTurn[\"toolResults\"] = [];\n const toolCalls: NonNullable<AssistantTurn[\"toolCalls\"]> = [];\n for (const step of steps) {\n if (step.type === \"thinkingMessage\") applyThinkingStep(assistant, step.message);\n else if (step.type === \"assistantMessage\") assistant.text = step.message.text;\n else if (step.type === \"toolCall\")\n toolCalls.push({\n id: step.message.callId,\n name: step.message.name,\n input: (step.message.args as Record<string, unknown> | undefined) ?? {},\n });\n else\n toolResults.push({\n toolUseId: step.message.callId,\n content: step.message.result,\n isError: step.message.isError,\n });\n }\n if (toolCalls.length > 0) assistant.toolCalls = toolCalls;\n return { assistant, toolResults };\n}\n\n/** True when the assistant record carries any content worth emitting. */\nfunction hasAssistantContent(a: AssistantTurn): boolean {\n return a.text !== undefined || a.thinking !== undefined || (a.toolCalls?.length ?? 0) > 0;\n}\n\n/**\n * Map the rich `ConversationTurn[]` (from `run.conversation()`) into the native\n * assistant/tool records. One transcript turn is: an `assistant` record carrying\n * thinking + text + tool_use blocks, then (when present) a `user` record carrying\n * the paired tool_result blocks. Tool results pair with tool_use by `callId`.\n */\nfunction appendConversation(\n transcript: SessionTranscript,\n conversation: readonly ConversationTurn[],\n): void {\n for (const ct of conversation) {\n if (ct.type !== \"agentConversationTurn\") continue;\n const { assistant, toolResults } = mapAgentTurn(ct.turn.steps);\n if (hasAssistantContent(assistant)) transcript.appendAssistantTurn(assistant);\n if (toolResults.length > 0) transcript.appendToolResults(toolResults);\n }\n}\n\n/**\n * The per-agent transcript metadata used to seed a {@link SessionTranscript}. The\n * actual record I/O goes through the injected {@link SessionStore} (SE41), so this\n * no longer carries a `baseDir` — the store is already bound to its location.\n */\nexport interface TranscriptLocation {\n cwd: string;\n agentId: string;\n model: string;\n}\n\n/**\n * Read the session's records via the {@link SessionStore} and reconstruct the\n * resumable history, narrowed to the in-memory {@link SessionMessage} shape\n * (user/assistant text). Tool turns fold into assistant-role context so resume\n * keeps tool history. Works identically for the FS default and an external store.\n */\nexport async function readSessionMessages(\n store: SessionStore,\n agentId: string,\n): Promise<SessionMessage[]> {\n const records = await store.readRecords(agentId);\n return reconstructMessages(records).map(narrowToSessionMessage);\n}\n\ntype NarrowPart = {\n type: string;\n text?: string;\n content?: unknown;\n name?: string;\n id?: string;\n toolUseId?: string;\n input?: unknown;\n isError?: boolean;\n};\n\n/** Render one reconstructed content part as folded session text. */\nfunction partToText(p: NarrowPart): string {\n if (p.type === \"text\") return p.text ?? \"\";\n if (p.type === \"tool_use\") return `[tool call] ${p.name ?? \"\"}`;\n if (p.type === \"tool_result\") {\n const body = typeof p.content === \"string\" ? p.content : JSON.stringify(p.content);\n return `[tool result] ${body}`;\n }\n return \"\";\n}\n\n/**\n * theokit#146 — the same part, kept as STRUCTURE.\n *\n * `partToText` above is what the model replay wants; a host rendering tool cards needs the call id,\n * the tool name and the arguments, none of which survive `[tool call] NAME`. Both projections are\n * produced from the one reconstructed part, so they cannot drift apart.\n *\n * Returns `undefined` for a part with no display meaning (e.g. an image placeholder the session\n * projection does not model), which the caller filters out.\n */\nfunction partToStructured(p: NarrowPart): SessionMessagePart | undefined {\n if (p.type === \"text\") return { type: \"text\", text: p.text ?? \"\" };\n if (p.type === \"tool_use\") {\n return {\n type: \"tool_use\",\n id: p.id ?? \"\",\n name: p.name ?? \"\",\n input: (p.input ?? {}) as Record<string, unknown>,\n };\n }\n if (p.type === \"tool_result\") {\n return {\n type: \"tool_result\",\n toolUseId: p.toolUseId ?? \"\",\n // Reconstructed tool results carry either a string or the SE7 content blocks; both are\n // already the session shape, so this narrows `unknown` rather than converting anything.\n content: p.content as string | ReadonlyArray<ToolResultContentBlock>,\n ...(p.isError === true ? { isError: true } : {}),\n };\n }\n return undefined;\n}\n\n/** Flatten a reconstructed `LlmMessage` to the narrowed in-memory `SessionMessage`. */\nfunction narrowToSessionMessage(m: {\n role: \"system\" | \"user\" | \"assistant\";\n content: NarrowPart[];\n}): SessionMessage {\n const role = m.role === \"user\" ? \"user\" : \"assistant\";\n const text = m.content\n .map(partToText)\n .filter((s) => s.length > 0)\n .join(\"\\n\");\n const parts = m.content\n .map(partToStructured)\n .filter((p): p is SessionMessagePart => p !== undefined);\n return { role, text, parts };\n}\n\n/** The records appended by the last turn (the delta beyond the seeded prior). */\nfunction deltaRecords(\n transcript: SessionTranscript,\n priorLength: number,\n): readonly SessionRecord[] {\n return transcript.records().slice(priorLength);\n}\n\n/**\n * Persist one conversation turn (user + assistant/tool records) to the session\n * store, append-only. Reads the prior records to seed the parent chain, folds the\n * new turn, and appends ONLY the delta via {@link SessionStore.appendRecords}\n * (the store owns the append atomicity — the FS default serializes under a file\n * lock). Within one process, turns for an agent are already chained upstream, so\n * the read→append is ordered; cross-host ordering is the external store's contract.\n */\nexport async function persistTurn(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n turn: PersistTurnInput,\n): Promise<void> {\n const prior = await store.readRecords(loc.agentId);\n const transcript = seedTranscript(prior, { cwd: loc.cwd, sessionId, model: loc.model });\n transcript.appendUserTurn(turn.userText);\n appendConversation(transcript, turn.conversation);\n await store.appendRecords(loc.agentId, deltaRecords(transcript, prior.length));\n}\n\n/**\n * Append-only compaction: add a `compact_boundary` system record (a new root) so\n * resume replays only the post-boundary continuation. Appends only the boundary\n * record via the store — NEVER rewrites or shrinks the prior records.\n */\nexport async function appendCompactBoundaryRecord(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n meta: { preTokens: number; trigger: string },\n): Promise<void> {\n const prior = await store.readRecords(loc.agentId);\n const transcript = seedTranscript(prior, { cwd: loc.cwd, sessionId, model: loc.model });\n transcript.appendCompactBoundary(meta);\n await store.appendRecords(loc.agentId, deltaRecords(transcript, prior.length));\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/session/agent-session-store.ts"],"names":[],"mappings":";;;AA+BA,SAAS,cAAA,CACP,OACA,IAAA,EACmB;AACnB,EAAA,OAAO,iBAAA,CAAkB,WAAA,CAAY,KAAA,EAAO,IAAI,CAAA;AAClD;AA8BA,SAAS,iBAAA,CACP,WACA,OAAA,EACM;AACN,EAAA,SAAA,CAAU,WAAW,OAAA,CAAQ,IAAA;AAC7B,EAAA,IAAI,OAAA,CAAQ,SAAA,KAAc,MAAA,EAAW,SAAA,CAAU,oBAAoB,OAAA,CAAQ,SAAA;AAC7E;AAGA,SAAS,aAAa,KAAA,EAAgD;AACpE,EAAA,MAAM,YAA2B,EAAC;AAClC,EAAA,MAAM,cAAyC,EAAC;AAChD,EAAA,MAAM,YAAqD,EAAC;AAC5D,EAAA,KAAA,MAAW,QAAQ,KAAA,EAAO;AACxB,IAAA,IAAI,KAAK,IAAA,KAAS,iBAAA,EAAmB,iBAAA,CAAkB,SAAA,EAAW,KAAK,OAAO,CAAA;AAAA,SAAA,IACrE,KAAK,IAAA,KAAS,kBAAA,EAAoB,SAAA,CAAU,IAAA,GAAO,KAAK,OAAA,CAAQ,IAAA;AAAA,SAAA,IAChE,KAAK,IAAA,KAAS,UAAA;AACrB,MAAA,SAAA,CAAU,IAAA,CAAK;AAAA,QACb,EAAA,EAAI,KAAK,OAAA,CAAQ,MAAA;AAAA,QACjB,IAAA,EAAM,KAAK,OAAA,CAAQ,IAAA;AAAA,QACnB,KAAA,EAAQ,IAAA,CAAK,OAAA,CAAQ,IAAA,IAAgD;AAAC,OACvE,CAAA;AAAA;AAED,MAAA,WAAA,CAAY,IAAA,CAAK;AAAA,QACf,SAAA,EAAW,KAAK,OAAA,CAAQ,MAAA;AAAA,QACxB,OAAA,EAAS,KAAK,OAAA,CAAQ,MAAA;AAAA,QACt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,CAAW,sBAAsB,IAAI,CAAA;AACrC,EAAA,MAAM,KAAA,CAAM,cAAc,GAAA,CAAI,OAAA,EAAS,aAAa,UAAA,EAAY,KAAA,CAAM,MAAM,CAAC,CAAA;AAC/E","file":"chunk-G24KZRSA.js","sourcesContent":["/**\n * SE40 — native session store over the Claude-shaped `.jsonl` transcript.\n *\n * The theokit session format IS the Claude Code record shape (see\n * `../../persistence/session-transcript.ts`). This module owns the FS lifecycle:\n * read existing records, seed a {@link SessionTranscript}'s parent chain, append\n * the new turn (user + assistant/tool blocks), and write append-only. Compaction\n * appends a `compact_boundary` record (a new root) — it NEVER shrinks the line\n * set (that would break the DAG). Reads reconstruct `LlmMessage[]` via\n * {@link reconstructMessages}, narrowed to the in-memory {@link SessionMessage}.\n *\n * @internal\n */\n\nimport type { ToolResultContentBlock } from \"../../types/content-blocks.js\";\nimport type { ConversationStep, ConversationTurn } from \"../../types/conversation.js\";\nimport type { SessionStore } from \"../../types/session-store.js\";\nimport {\n type AssistantTurn,\n reconstructMessages,\n type SessionRecord,\n SessionTranscript,\n} from \"../persistence/session-transcript.js\";\nimport type { SessionMessage, SessionMessagePart } from \"./session-types.js\";\n\n/**\n * Seed a {@link SessionTranscript} from the already-on-disk records so a new\n * append parents correctly on the existing DAG leaf. The transcript re-emits the\n * seeded records verbatim before the new turn, so the whole file rewrites atomically\n * as one append-only line set. Returns the transcript primed with the prior records.\n */\nfunction seedTranscript(\n prior: readonly SessionRecord[],\n opts: { cwd: string; sessionId: string; model: string },\n): SessionTranscript {\n return SessionTranscript.fromRecords(prior, opts);\n}\n\n/** The turn to persist: the user's text plus the rich per-turn conversation view. */\nexport interface PersistTurnInput {\n userText: string;\n conversation: readonly ConversationTurn[];\n /**\n * M50 — when supplied, size-driven auto-compaction runs in the SAME write chain after the turn\n * persists (usage real vs the model's context window; summarizer injected by the caller).\n */\n autoCompact?: {\n usageTotal?: number | undefined;\n contextWindow?: number | undefined;\n summarize: (\n messages: readonly import(\"../../compaction.js\").CompressibleMessage[],\n ) => Promise<string>;\n };\n}\n\ninterface MappedTurn {\n assistant: AssistantTurn;\n toolResults: Array<{ toolUseId: string; content: string; isError?: boolean }>;\n}\n\n/**\n * theokit#122 — record the turn's thinking block, signature included.\n *\n * The signature is what makes the block replayable: without it the resumed turn is rejected by\n * Anthropic with `400 \"thinking blocks cannot be modified\"`.\n */\nfunction applyThinkingStep(\n assistant: AssistantTurn,\n message: { text: string; signature?: string },\n): void {\n assistant.thinking = message.text;\n if (message.signature !== undefined) assistant.thinkingSignature = message.signature;\n}\n\n/** Fold one agent turn's steps into an assistant record + paired tool results. */\nfunction mapAgentTurn(steps: readonly ConversationStep[]): MappedTurn {\n const assistant: AssistantTurn = {};\n const toolResults: MappedTurn[\"toolResults\"] = [];\n const toolCalls: NonNullable<AssistantTurn[\"toolCalls\"]> = [];\n for (const step of steps) {\n if (step.type === \"thinkingMessage\") applyThinkingStep(assistant, step.message);\n else if (step.type === \"assistantMessage\") assistant.text = step.message.text;\n else if (step.type === \"toolCall\")\n toolCalls.push({\n id: step.message.callId,\n name: step.message.name,\n input: (step.message.args as Record<string, unknown> | undefined) ?? {},\n });\n else\n toolResults.push({\n toolUseId: step.message.callId,\n content: step.message.result,\n isError: step.message.isError,\n });\n }\n if (toolCalls.length > 0) assistant.toolCalls = toolCalls;\n return { assistant, toolResults };\n}\n\n/** True when the assistant record carries any content worth emitting. */\nfunction hasAssistantContent(a: AssistantTurn): boolean {\n return a.text !== undefined || a.thinking !== undefined || (a.toolCalls?.length ?? 0) > 0;\n}\n\n/**\n * Map the rich `ConversationTurn[]` (from `run.conversation()`) into the native\n * assistant/tool records. One transcript turn is: an `assistant` record carrying\n * thinking + text + tool_use blocks, then (when present) a `user` record carrying\n * the paired tool_result blocks. Tool results pair with tool_use by `callId`.\n */\nfunction appendConversation(\n transcript: SessionTranscript,\n conversation: readonly ConversationTurn[],\n): void {\n for (const ct of conversation) {\n if (ct.type !== \"agentConversationTurn\") continue;\n const { assistant, toolResults } = mapAgentTurn(ct.turn.steps);\n if (hasAssistantContent(assistant)) transcript.appendAssistantTurn(assistant);\n if (toolResults.length > 0) transcript.appendToolResults(toolResults);\n }\n}\n\n/**\n * The per-agent transcript metadata used to seed a {@link SessionTranscript}. The\n * actual record I/O goes through the injected {@link SessionStore} (SE41), so this\n * no longer carries a `baseDir` — the store is already bound to its location.\n */\nexport interface TranscriptLocation {\n cwd: string;\n agentId: string;\n model: string;\n}\n\n/**\n * Read the session's records via the {@link SessionStore} and reconstruct the\n * resumable history, narrowed to the in-memory {@link SessionMessage} shape\n * (user/assistant text). Tool turns fold into assistant-role context so resume\n * keeps tool history. Works identically for the FS default and an external store.\n */\nexport async function readSessionMessages(\n store: SessionStore,\n agentId: string,\n): Promise<SessionMessage[]> {\n const records = await store.readRecords(agentId);\n return reconstructMessages(records).map(narrowToSessionMessage);\n}\n\ntype NarrowPart = {\n type: string;\n text?: string;\n content?: unknown;\n name?: string;\n id?: string;\n toolUseId?: string;\n input?: unknown;\n isError?: boolean;\n};\n\n/** Render one reconstructed content part as folded session text. */\nfunction partToText(p: NarrowPart): string {\n if (p.type === \"text\") return p.text ?? \"\";\n if (p.type === \"tool_use\") return `[tool call] ${p.name ?? \"\"}`;\n if (p.type === \"tool_result\") {\n const body = typeof p.content === \"string\" ? p.content : JSON.stringify(p.content);\n return `[tool result] ${body}`;\n }\n return \"\";\n}\n\n/**\n * theokit#146 — the same part, kept as STRUCTURE.\n *\n * `partToText` above is what the model replay wants; a host rendering tool cards needs the call id,\n * the tool name and the arguments, none of which survive `[tool call] NAME`. Both projections are\n * produced from the one reconstructed part, so they cannot drift apart.\n *\n * Returns `undefined` for a part with no display meaning (e.g. an image placeholder the session\n * projection does not model), which the caller filters out.\n */\nfunction partToStructured(p: NarrowPart): SessionMessagePart | undefined {\n if (p.type === \"text\") return { type: \"text\", text: p.text ?? \"\" };\n if (p.type === \"tool_use\") {\n return {\n type: \"tool_use\",\n id: p.id ?? \"\",\n name: p.name ?? \"\",\n input: (p.input ?? {}) as Record<string, unknown>,\n };\n }\n if (p.type === \"tool_result\") {\n return {\n type: \"tool_result\",\n toolUseId: p.toolUseId ?? \"\",\n // Reconstructed tool results carry either a string or the SE7 content blocks; both are\n // already the session shape, so this narrows `unknown` rather than converting anything.\n content: p.content as string | ReadonlyArray<ToolResultContentBlock>,\n ...(p.isError === true ? { isError: true } : {}),\n };\n }\n return undefined;\n}\n\n/** Flatten a reconstructed `LlmMessage` to the narrowed in-memory `SessionMessage`. */\nfunction narrowToSessionMessage(m: {\n role: \"system\" | \"user\" | \"assistant\";\n content: NarrowPart[];\n}): SessionMessage {\n const role = m.role === \"user\" ? \"user\" : \"assistant\";\n const text = m.content\n .map(partToText)\n .filter((s) => s.length > 0)\n .join(\"\\n\");\n const parts = m.content\n .map(partToStructured)\n .filter((p): p is SessionMessagePart => p !== undefined);\n return { role, text, parts };\n}\n\n/** The records appended by the last turn (the delta beyond the seeded prior). */\nfunction deltaRecords(\n transcript: SessionTranscript,\n priorLength: number,\n): readonly SessionRecord[] {\n return transcript.records().slice(priorLength);\n}\n\n/**\n * Persist one conversation turn (user + assistant/tool records) to the session\n * store, append-only. Reads the prior records to seed the parent chain, folds the\n * new turn, and appends ONLY the delta via {@link SessionStore.appendRecords}\n * (the store owns the append atomicity — the FS default serializes under a file\n * lock). Within one process, turns for an agent are already chained upstream, so\n * the read→append is ordered; cross-host ordering is the external store's contract.\n */\nexport async function persistTurn(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n turn: PersistTurnInput,\n): Promise<void> {\n const prior = await store.readRecords(loc.agentId);\n const transcript = seedTranscript(prior, { cwd: loc.cwd, sessionId, model: loc.model });\n transcript.appendUserTurn(turn.userText);\n appendConversation(transcript, turn.conversation);\n await store.appendRecords(loc.agentId, deltaRecords(transcript, prior.length));\n}\n\n/**\n * Append-only compaction: add a `compact_boundary` system record (a new root) so\n * resume replays only the post-boundary continuation. Appends only the boundary\n * record via the store — NEVER rewrites or shrinks the prior records.\n */\nexport async function appendCompactBoundaryRecord(\n store: SessionStore,\n loc: TranscriptLocation,\n sessionId: string,\n meta: { preTokens: number; trigger: string },\n): Promise<void> {\n const prior = await store.readRecords(loc.agentId);\n const transcript = seedTranscript(prior, { cwd: loc.cwd, sessionId, model: loc.model });\n transcript.appendCompactBoundary(meta);\n await store.appendRecords(loc.agentId, deltaRecords(transcript, prior.length));\n}\n"]}
|