@theokit/sdk 5.4.0 → 5.6.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 +642 -0
- package/dist/{agent-AUVD4TI4.cjs → agent-47NS6ZVL.cjs} +13 -13
- package/dist/{agent-AUVD4TI4.cjs.map → agent-47NS6ZVL.cjs.map} +1 -1
- package/dist/{agent-C1Efo7PI.d.cts → agent-82d_DrCL.d.cts} +33 -2
- package/dist/{agent-Bmy2G_ml.d.ts → agent-G6g-uwcB.d.ts} +33 -2
- package/dist/{agent-MNINE73R.js → agent-JJZM2VIK.js} +12 -12
- package/dist/{agent-MNINE73R.js.map → agent-JJZM2VIK.js.map} +1 -1
- package/dist/{chunk-IKBLU7ZS.js → chunk-2UXQASTX.js} +232 -32
- package/dist/chunk-2UXQASTX.js.map +1 -0
- package/dist/{chunk-VPK6PHIE.cjs → chunk-52FDUJSV.cjs} +8 -8
- package/dist/{chunk-VPK6PHIE.cjs.map → chunk-52FDUJSV.cjs.map} +1 -1
- package/dist/{chunk-2XRAWOZZ.js → chunk-5NELQ6LB.js} +65 -3
- package/dist/chunk-5NELQ6LB.js.map +1 -0
- package/dist/{chunk-3FDU5JFE.cjs → chunk-7IZKTQ5G.cjs} +35 -7
- package/dist/chunk-7IZKTQ5G.cjs.map +1 -0
- package/dist/{chunk-7SZAV6QG.js → chunk-7MMTZBTT.js} +3 -3
- package/dist/{chunk-7SZAV6QG.js.map → chunk-7MMTZBTT.js.map} +1 -1
- package/dist/{chunk-SADXXGWU.js → chunk-BZ3YMAMP.js} +3 -3
- package/dist/{chunk-NQTNSHSB.cjs.map → chunk-BZ3YMAMP.js.map} +1 -1
- package/dist/{chunk-LX7SEXOQ.js → chunk-CA5VUAP3.js} +25 -7
- package/dist/chunk-CA5VUAP3.js.map +1 -0
- package/dist/{chunk-IU5N5224.cjs → chunk-EIOMN5VA.cjs} +8 -8
- package/dist/chunk-EIOMN5VA.cjs.map +1 -0
- package/dist/{chunk-KWGSBZ2Q.js → chunk-FPIY5CLV.js} +3 -3
- package/dist/{chunk-KWGSBZ2Q.js.map → chunk-FPIY5CLV.js.map} +1 -1
- package/dist/{chunk-UALC6Q3J.cjs → chunk-GCHZMH42.cjs} +290 -88
- package/dist/chunk-GCHZMH42.cjs.map +1 -0
- package/dist/{chunk-NQTNSHSB.cjs → chunk-GFFBXSQT.cjs} +5 -5
- package/dist/chunk-GFFBXSQT.cjs.map +1 -0
- package/dist/{chunk-J6KZE2ZQ.cjs → chunk-HG4UN4MN.cjs} +4 -4
- package/dist/{chunk-J6KZE2ZQ.cjs.map → chunk-HG4UN4MN.cjs.map} +1 -1
- package/dist/{chunk-N6OOOYFZ.js → chunk-HUDNLFY4.js} +4 -4
- package/dist/chunk-HUDNLFY4.js.map +1 -0
- package/dist/{chunk-LOHMT36V.cjs → chunk-LD6HASA5.cjs} +65 -2
- package/dist/chunk-LD6HASA5.cjs.map +1 -0
- package/dist/{chunk-QATRS7JD.cjs → chunk-MYJGWS2J.cjs} +26 -8
- package/dist/chunk-MYJGWS2J.cjs.map +1 -0
- package/dist/{chunk-XD3FS5OI.js → chunk-N2KAIZ5D.js} +34 -7
- package/dist/chunk-N2KAIZ5D.js.map +1 -0
- package/dist/{chunk-HW7SEELD.cjs → chunk-QRVS2PRE.cjs} +31 -8
- package/dist/chunk-QRVS2PRE.cjs.map +1 -0
- package/dist/{chunk-AYA65JA5.cjs → chunk-RWPLWMCZ.cjs} +25 -9
- package/dist/chunk-RWPLWMCZ.cjs.map +1 -0
- package/dist/{chunk-WS5ULCL4.js → chunk-STGSMJMJ.js} +3 -3
- package/dist/{chunk-WS5ULCL4.js.map → chunk-STGSMJMJ.js.map} +1 -1
- package/dist/{chunk-O7L7M42F.js → chunk-T3ZDEYTJ.js} +21 -5
- package/dist/chunk-T3ZDEYTJ.js.map +1 -0
- package/dist/{chunk-43YXGD3P.cjs → chunk-TY56BKSK.cjs} +8 -4
- package/dist/chunk-TY56BKSK.cjs.map +1 -0
- package/dist/chunk-UOLBAPDM.js +66 -0
- package/dist/chunk-UOLBAPDM.js.map +1 -0
- package/dist/{chunk-Z2JFX372.cjs → chunk-VUHXC74Q.cjs} +15 -15
- package/dist/{chunk-Z2JFX372.cjs.map → chunk-VUHXC74Q.cjs.map} +1 -1
- package/dist/{chunk-NSLHPAC7.js → chunk-X7EUUHXU.js} +6 -5
- package/dist/chunk-X7EUUHXU.js.map +1 -0
- package/dist/context/index.cjs +7 -7
- package/dist/context/index.js +3 -3
- package/dist/{context-4AIK26QB.cjs → context-HR4KMXMA.cjs} +7 -7
- package/dist/{context-4AIK26QB.cjs.map → context-HR4KMXMA.cjs.map} +1 -1
- package/dist/context-J5BJ3LBS.js +6 -0
- package/dist/{context-EGM6CHXD.js.map → context-J5BJ3LBS.js.map} +1 -1
- package/dist/{cron-DSMdlhyF.d.cts → cron-DWv69ZSD.d.cts} +1 -1
- package/dist/{cron-Dcdrdv_T.d.ts → cron-GynWtAax.d.ts} +1 -1
- package/dist/cron.cjs +12 -12
- package/dist/cron.d.cts +2 -2
- package/dist/cron.d.ts +2 -2
- package/dist/cron.js +11 -11
- package/dist/eval.cjs +11 -11
- package/dist/eval.js +10 -10
- package/dist/{index-manager-W7FDMGEG.js → index-manager-27WLNQEE.js} +5 -5
- package/dist/{index-manager-W7FDMGEG.js.map → index-manager-27WLNQEE.js.map} +1 -1
- package/dist/{index-manager-3UNPYH34.cjs → index-manager-BBHDKMQS.cjs} +6 -6
- package/dist/{index-manager-3UNPYH34.cjs.map → index-manager-BBHDKMQS.cjs.map} +1 -1
- package/dist/index.cjs +274 -40
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +168 -5
- package/dist/index.d.ts +168 -5
- package/dist/index.js +246 -23
- package/dist/index.js.map +1 -1
- package/dist/internal/memory/storage/index.cjs +32 -32
- package/dist/internal/memory/storage/index.js +3 -3
- package/dist/internal/memory/storage/memory-root.d.cts +27 -0
- package/dist/internal/memory/storage/memory-root.d.ts +27 -0
- package/dist/internal/persistence/index.cjs +4 -4
- package/dist/internal/persistence/index.js +1 -1
- package/dist/internal/runtime/compat/foreign-config-sources.d.ts +17 -4
- package/dist/internal/runtime/compat/managed-settings.d.ts +80 -0
- package/dist/internal/runtime/context/context-discovery-runner.d.ts +14 -0
- package/dist/internal/runtime/context/context-discovery.d.ts +37 -0
- package/dist/internal/runtime/context/context-manager.d.ts +21 -1
- package/dist/internal/runtime/context/yaml-frontmatter.d.ts +6 -3
- package/dist/internal/runtime/hooks/hooks-executor.d.ts +23 -1
- package/dist/internal/runtime/hooks/hooks-source.d.ts +46 -1
- package/dist/internal/runtime/skills/discover-skills.d.ts +4 -0
- package/dist/project.cjs +3 -3
- package/dist/project.js +1 -1
- package/dist/skills.cjs +5 -5
- package/dist/skills.js +2 -2
- package/dist/subagents-loader-CJFYQQU2.js +7 -0
- package/dist/{subagents-loader-AIVDQ2D5.js.map → subagents-loader-CJFYQQU2.js.map} +1 -1
- package/dist/subagents-loader-MOO7DC4E.cjs +16 -0
- package/dist/{subagents-loader-DN4LETGL.cjs.map → subagents-loader-MOO7DC4E.cjs.map} +1 -1
- package/dist/subagents-loader.cjs +4 -4
- package/dist/subagents-loader.d.cts +1 -1
- package/dist/subagents-loader.d.ts +1 -1
- package/dist/subagents-loader.js +3 -3
- package/dist/types/agent.d.ts +6 -1
- package/dist/types/hooks.d.ts +22 -0
- package/docs/error-codes.md +20 -18
- package/docs/harness-capability-map.md +9 -1
- package/package.json +1 -1
- package/dist/chunk-2XRAWOZZ.js.map +0 -1
- package/dist/chunk-3FDU5JFE.cjs.map +0 -1
- package/dist/chunk-43YXGD3P.cjs.map +0 -1
- package/dist/chunk-AYA65JA5.cjs.map +0 -1
- package/dist/chunk-HW7SEELD.cjs.map +0 -1
- package/dist/chunk-IKBLU7ZS.js.map +0 -1
- package/dist/chunk-IU5N5224.cjs.map +0 -1
- package/dist/chunk-JNAA4G4H.js +0 -43
- package/dist/chunk-JNAA4G4H.js.map +0 -1
- package/dist/chunk-LOHMT36V.cjs.map +0 -1
- package/dist/chunk-LX7SEXOQ.js.map +0 -1
- package/dist/chunk-N6OOOYFZ.js.map +0 -1
- package/dist/chunk-NSLHPAC7.js.map +0 -1
- package/dist/chunk-O7L7M42F.js.map +0 -1
- package/dist/chunk-QATRS7JD.cjs.map +0 -1
- package/dist/chunk-SADXXGWU.js.map +0 -1
- package/dist/chunk-UALC6Q3J.cjs.map +0 -1
- package/dist/chunk-XD3FS5OI.js.map +0 -1
- package/dist/context-EGM6CHXD.js +0 -6
- package/dist/subagents-loader-AIVDQ2D5.js +0 -7
- package/dist/subagents-loader-DN4LETGL.cjs +0 -16
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
3
|
var chunkGHX4P3V2_cjs = require('./chunk-GHX4P3V2.cjs');
|
|
4
|
-
var
|
|
4
|
+
var chunkGFFBXSQT_cjs = require('./chunk-GFFBXSQT.cjs');
|
|
5
5
|
var chunkA4RAL2ER_cjs = require('./chunk-A4RAL2ER.cjs');
|
|
6
6
|
var chunkJ7J7J2GN_cjs = require('./chunk-J7J7J2GN.cjs');
|
|
7
7
|
var chunk6LHQPOMI_cjs = require('./chunk-6LHQPOMI.cjs');
|
|
@@ -86,13 +86,13 @@ function findWordBoundarySplit(text, maxChars) {
|
|
|
86
86
|
|
|
87
87
|
// src/internal/memory/corpus-sync.ts
|
|
88
88
|
async function syncCorpus(repo, memoryRoot) {
|
|
89
|
-
const files = await
|
|
89
|
+
const files = await chunkGFFBXSQT_cjs.collectMarkdownFiles(memoryRoot);
|
|
90
90
|
const existingByPath = repo.filesByPath();
|
|
91
91
|
let filesUpdated = 0;
|
|
92
92
|
let chunksWritten = 0;
|
|
93
93
|
for (const entry of files) {
|
|
94
94
|
const raw = await promises.readFile(entry.absolutePath, "utf8");
|
|
95
|
-
const hash =
|
|
95
|
+
const hash = chunkGFFBXSQT_cjs.sha256(raw);
|
|
96
96
|
if (existingByPath.get(entry.absolutePath)?.hash === hash) continue;
|
|
97
97
|
const stats = await promises.stat(entry.absolutePath);
|
|
98
98
|
const fileId = repo.upsertFile({
|
|
@@ -156,7 +156,7 @@ var LanceMemoryAdapter = class {
|
|
|
156
156
|
limit: maxResults * 2,
|
|
157
157
|
...options.sources !== void 0 ? { sources: options.sources } : {}
|
|
158
158
|
});
|
|
159
|
-
return lanceHits.filter((h) => h.score >= minScore).slice(0, maxResults).map((h) => translateLanceHit(h, query,
|
|
159
|
+
return lanceHits.filter((h) => h.score >= minScore).slice(0, maxResults).map((h) => translateLanceHit(h, query, chunkGFFBXSQT_cjs.resolveWeights(options)));
|
|
160
160
|
}
|
|
161
161
|
status() {
|
|
162
162
|
return {
|
|
@@ -211,7 +211,7 @@ async function openLanceIndex(opts) {
|
|
|
211
211
|
{ code: "lance_requires_embedding" }
|
|
212
212
|
);
|
|
213
213
|
}
|
|
214
|
-
const lance = await
|
|
214
|
+
const lance = await chunkGFFBXSQT_cjs.LanceIndex.open({
|
|
215
215
|
cwd: opts.cwd,
|
|
216
216
|
embedding: opts.embedding,
|
|
217
217
|
...opts.filePath !== void 0 ? { storagePath: opts.filePath } : {}
|
|
@@ -414,9 +414,9 @@ var IndexManager = class _IndexManager {
|
|
|
414
414
|
}
|
|
415
415
|
/** Internal SQLite-path open. Renamed from previous public `open`. */
|
|
416
416
|
static async openSqliteInternal(opts) {
|
|
417
|
-
const memoryRoot = opts.memoryRoot ??
|
|
418
|
-
const filePath = opts.filePath ??
|
|
419
|
-
const db = await
|
|
417
|
+
const memoryRoot = opts.memoryRoot ?? chunkGFFBXSQT_cjs.resolveMemoryRoot(opts.cwd);
|
|
418
|
+
const filePath = opts.filePath ?? chunkGFFBXSQT_cjs.defaultIndexPath(chunkGFFBXSQT_cjs.memoryIndexRoot(opts.cwd, memoryRoot));
|
|
419
|
+
const db = await chunkGFFBXSQT_cjs.openMemoryDb({ filePath });
|
|
420
420
|
const manager = new _IndexManager(memoryRoot, db, opts.embedding);
|
|
421
421
|
if (opts.embedding !== void 0) await manager.initVectorBackend(opts.embedding);
|
|
422
422
|
return manager;
|
|
@@ -497,7 +497,7 @@ var IndexManager = class _IndexManager {
|
|
|
497
497
|
endLine,
|
|
498
498
|
score: textScore,
|
|
499
499
|
textScore,
|
|
500
|
-
snippet:
|
|
500
|
+
snippet: chunkGFFBXSQT_cjs.truncateSnippet(String(row.text ?? "")),
|
|
501
501
|
source: String(row.source),
|
|
502
502
|
citation: `${path}:${startLine}-${endLine}`,
|
|
503
503
|
// sneak the chunk id through for the hybrid join below
|
|
@@ -525,7 +525,7 @@ var IndexManager = class _IndexManager {
|
|
|
525
525
|
score: 0.5,
|
|
526
526
|
// LIKE has no relevance score — use a neutral midpoint
|
|
527
527
|
textScore: 0.5,
|
|
528
|
-
snippet:
|
|
528
|
+
snippet: chunkGFFBXSQT_cjs.truncateSnippet(String(row.text ?? "")),
|
|
529
529
|
source: String(row.source),
|
|
530
530
|
citation: `${path}:${startLine}-${endLine}`,
|
|
531
531
|
chunkId: Number(row.id)
|
|
@@ -548,10 +548,10 @@ var IndexManager = class _IndexManager {
|
|
|
548
548
|
return out;
|
|
549
549
|
}
|
|
550
550
|
combineHybridScores(textHits, vectorHitsById, options) {
|
|
551
|
-
const weights =
|
|
551
|
+
const weights = chunkGFFBXSQT_cjs.resolveWeights(options);
|
|
552
552
|
const merged = this.mergeHits(textHits, vectorHitsById);
|
|
553
553
|
const combined = [...merged.values()].map(
|
|
554
|
-
(hit) =>
|
|
554
|
+
(hit) => chunkGFFBXSQT_cjs.blendScores(hit, vectorHitsById.get(hit.chunkId)?.vectorScore ?? 0, weights)
|
|
555
555
|
);
|
|
556
556
|
return combined.sort((a, b) => b.score - a.score);
|
|
557
557
|
}
|
|
@@ -579,7 +579,7 @@ var IndexManager = class _IndexManager {
|
|
|
579
579
|
endLine,
|
|
580
580
|
score: 0,
|
|
581
581
|
textScore: 0,
|
|
582
|
-
snippet:
|
|
582
|
+
snippet: chunkGFFBXSQT_cjs.truncateSnippet(String(row.text ?? "")),
|
|
583
583
|
source: String(row.source),
|
|
584
584
|
citation: `${path}:${startLine}-${endLine}`
|
|
585
585
|
};
|
|
@@ -591,5 +591,5 @@ var IndexManager = class _IndexManager {
|
|
|
591
591
|
};
|
|
592
592
|
|
|
593
593
|
exports.IndexManager = IndexManager;
|
|
594
|
-
//# sourceMappingURL=chunk-
|
|
595
|
-
//# sourceMappingURL=chunk-
|
|
594
|
+
//# sourceMappingURL=chunk-VUHXC74Q.cjs.map
|
|
595
|
+
//# sourceMappingURL=chunk-VUHXC74Q.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/memory/storage/chunk-markdown.ts","../src/internal/memory/corpus-sync.ts","../src/internal/memory/escape-like-pattern.ts","../src/internal/memory/memory-index.ts","../src/internal/memory/lance-memory-adapter.ts","../src/internal/memory/index-manager-dispatch.ts","../src/internal/memory/index-repository.ts","../src/internal/memory/sqlite-vec-loader.ts","../src/internal/memory/vec-index.ts","../src/internal/memory/index-manager.ts"],"names":["createHash","collectMarkdownFiles","readFile","sha256","stat","resolveWeights","ConfigurationError","LanceIndex","LruEmbeddingCache","resolveMemoryRoot","defaultIndexPath","memoryIndexRoot","openMemoryDb","sanitizeFts5Query","containsCjk","diag","truncateSnippet","blendScores"],"mappings":";;;;;;;;;;AA6BA,IAAM,UAAA,GAAa,uBAAA;AASZ,SAAS,aAAA,CAAc,IAAA,EAAc,OAAA,GAAgC,EAAC,EAAkB;AAC7F,EAAA,MAAM,QAAA,GAAW,QAAQ,QAAA,IAAY,GAAA;AACrC,EAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,OAAO,EAAC;AAC/B,EAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA;AAC7B,EAAA,MAAM,GAAA,GAAwB,EAAE,MAAA,EAAQ,EAAC,EAAG,KAAA,EAAO,EAAC,EAAG,KAAA,EAAO,CAAA,EAAG,OAAA,EAAS,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AA,EAAG,IAAI,CAAA,CAAA,EAAI,SAAS,IAAI,OAAO,CAAA;AAAA,OAC3C;AAAA,IACF,CAAC,CAAA;AAAA,EACH;AAAA,EAEA,KAAA,GAAc;AACZ,IAAA,IAAA,CAAK,KAAK,KAAA,EAAM;AAAA,EAClB;AACF","file":"chunk-Z2JFX372.cjs","sourcesContent":["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","/**\n * The corpus walk: read every markdown file under the memory root, and re-chunk the ones that\n * changed.\n *\n * One of the four concerns that shared `IndexManager`, and the one with the most distinct reason to\n * change — \"which files are in the corpus and when is one stale\" is a question about the filesystem,\n * not about search or about the schema. It takes a {@link MemoryIndexRepository} rather than a\n * database, so it cannot reach past it into SQL.\n *\n * The staleness test is the content hash, NOT the mtime. mtime is written into `files` for\n * observability; a file touched without being edited must not cost a re-chunk, and a file restored\n * from a backup with an older mtime must not be skipped.\n *\n * @internal\n */\n\nimport { readFile, stat } from \"node:fs/promises\";\nimport { collectMarkdownFiles, sha256 } from \"./index-manager-helpers.js\";\nimport type { MemoryIndexRepository } from \"./index-repository.js\";\nimport { chunkMarkdown } from \"./storage/chunk-markdown.js\";\nimport type { MemoryRoot } from \"./storage/memory-root.js\";\n\nexport interface CorpusSyncCounts {\n readonly filesScanned: number;\n readonly filesUpdated: number;\n readonly chunksWritten: number;\n}\n\nexport async function syncCorpus(\n repo: MemoryIndexRepository,\n memoryRoot: MemoryRoot,\n): Promise<CorpusSyncCounts> {\n const files = await collectMarkdownFiles(memoryRoot);\n const existingByPath = repo.filesByPath();\n let filesUpdated = 0;\n let chunksWritten = 0;\n\n for (const entry of files) {\n const raw = await readFile(entry.absolutePath, \"utf8\");\n const hash = sha256(raw);\n if (existingByPath.get(entry.absolutePath)?.hash === hash) continue;\n\n const stats = await stat(entry.absolutePath);\n const fileId = repo.upsertFile({\n absPath: entry.absolutePath,\n relPath: entry.relPath,\n hash,\n mtimeMs: stats.mtimeMs,\n source: entry.source,\n });\n repo.deleteChunksForFile(fileId);\n const chunks = chunkMarkdown(raw);\n for (const chunk of chunks) repo.insertChunk({ fileId, ...chunk });\n\n filesUpdated += 1;\n chunksWritten += chunks.length;\n }\n\n return { filesScanned: files.length, filesUpdated, chunksWritten };\n}\n","/**\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 * 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 * Whether this backend actually walked a corpus.\n *\n * REQUIRED, not optional, and that is the point. `MemoryIndex` has two implementers and consumers\n * hold the interface: `IndexManager` walks files, and `LanceMemoryAdapter` has no corpus to walk —\n * it is a vector store fed by explicit `addFacts`. The adapter used to answer with a frozen\n * all-zeros result, which a caller cannot tell apart from a real sync that found nothing to do.\n * The comment above it stated that as the intention (\"so callers' existing logging does not\n * break\"), which is the substitution defect written down as a feature.\n *\n * A required boolean forces every implementer to say which case it is in, and forces the compiler\n * to notice a new implementer that forgot. An optional flag would have let the next backend\n * reproduce the silence.\n */\n supported: boolean;\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. It returns zero counts with `supported: false`\n * so the result is not mistaken for a sync that found nothing. Consumers\n * writing facts hold a `LanceIndex` and call `addFacts` on it; the adapter\n * does not hand its adaptee out.\n * - `search()` is HYBRID, not vector-only. Lance supplies the vector distance\n * and `translateLanceHit` adds a client-side term-overlap ratio (T4.5), so\n * `textScore` is a real number in 0..1 and `score` is `0.7 * vectorScore +\n * 0.3 * textScore` — never `=== vectorScore`. This block said the opposite\n * for as long as T4.5 has been shipped, while the docblock 90 lines below\n * described the change correctly, so the two halves of one file disagreed\n * and the header is the half a caller reads.\n * - `status()` reports `backend: \"hybrid\"` only when an embedding runtime\n * is wired (always the case for Lance — embedding is required at open).\n * Both counts are 0 with `countsExact: false`: the port declares `status()`\n * synchronous and Lance's row count is async, so nothing can be measured\n * here. The zeros are placeholders and the flag says which.\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 HybridWeights, resolveWeights } from \"./index-manager-helpers.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/**\n * Lance has no corpus to walk, and the result now SAYS so.\n *\n * The counts stay zero — inventing numbers would trade one false claim for another. What changed is\n * `supported: false`: an all-zeros result was previously indistinguishable from a real sync that\n * found nothing to reindex, and the comment above this constant used to present that as the goal\n * (\"so callers' existing logging does not break\"). A caller can now tell \"nothing to do\" from\n * \"this backend does not do this\".\n */\nconst UNSUPPORTED_SYNC_RESULT: SyncResult = Object.freeze({\n filesScanned: 0,\n filesUpdated: 0,\n chunksWritten: 0,\n chunksEmbedded: 0,\n supported: false,\n});\n\nexport class LanceMemoryAdapter implements MemoryIndex {\n constructor(private readonly inner: LanceIndex) {}\n\n /**\n * Not applicable to Lance — see file header. Returns zero counts with `supported: false` so a\n * caller can distinguish this from a real sync that found nothing.\n */\n async sync(): Promise<SyncResult> {\n return UNSUPPORTED_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, resolveWeights(options)));\n }\n\n status(): IndexStatus {\n // The Lance API is async and `status()` is not, so no count can be taken here. The zeros are\n // placeholders and `countsExact: false` says so — previously they were indistinguishable from a\n // measured empty index, so a caller testing `chunksIndexed > 0` got a false negative on every\n // run regardless of how many rows the table held.\n //\n // There is deliberately no escape hatch. This class used to carry `unwrap(): LanceIndex`,\n // documented as being for \"the migration tool, benchmark script\" — measured 2026-09-01, it had\n // ZERO callers anywhere in the monorepo, including those two, which hold a `LanceIndex`\n // directly and never open the adapter. What it did have was this comment pointing at it, which\n // made the leak read as the supported way to work around the limitation. A caller that needs\n // the real count needs `LanceIndex`, and the honest way to get one is to open one.\n return {\n backend: \"hybrid\",\n filesIndexed: 0,\n chunksIndexed: 0,\n countsExact: false,\n };\n }\n\n async close(): Promise<void> {\n await this.inner.close();\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 | undefined,\n weights: HybridWeights,\n): MemorySearchHit {\n const textScore = query !== undefined ? computeTermOverlapScore(query, hit.text) : 0;\n const vectorScore = hit.score;\n // The CALLER's weights, through the same `resolveWeights` the SQLite path uses. These were the\n // literals 0.7 and 0.3, so a caller that tuned `vectorWeight` / `textWeight` had its tuning applied\n // on one backend and silently dropped on the other — the shape of failure that makes a swap-in\n // backend untrustworthy. The defaults differ between the two (0.6/0.4 from resolveWeights, versus\n // the 0.7/0.3 written here), so unweighted results move slightly; that is the point, since one of\n // the two numbers was not the contract's.\n const combined =\n (vectorScore * weights.vectorWeight + textScore * weights.textWeight) / weights.total;\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 * Every SQL string the memory index runs, in one place.\n *\n * `IndexManager` answered four questions with four independent reasons to change: the corpus walk,\n * the BM25-to-score normalisation, the vector-cache strategy, and the schema. This is the fourth.\n * Changing a column, an index or a join is now a change to THIS file, and the caller above it reads\n * as search logic rather than as SQL with scoring in between.\n *\n * The row-to-`MemorySearchHit` mapping deliberately stays with the caller: turning a row into a hit\n * involves a score, a snippet and a citation, none of which the schema knows about. Keeping it here\n * would move the normalisation into the repository and re-create the same mixture one layer down.\n *\n * Rows come back as `Record<string, unknown>` for the same reason: the repository knows what it\n * SELECTed, not what the caller will make of it.\n *\n * @internal\n */\n\nimport type { MemoryDb } from \"./index-db.js\";\n\n/** What `files` holds for one path — the pair the corpus walk compares against disk. */\nexport interface FileRow {\n readonly id: number;\n readonly hash: string;\n}\n\nexport class MemoryIndexRepository {\n constructor(private readonly db: MemoryDb) {}\n\n counts(): { files: number; chunks: number } {\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 return { files: Number(files.n ?? 0), chunks: Number(chunks.n ?? 0) };\n }\n\n /**\n * FTS5 match, ordered by bm25. THROWS on an FTS5 error rather than swallowing it — whether that\n * error means \"CJK input the default tokenizer cannot segment\" or \"the table is missing\" is a\n * judgement the caller makes, and it makes it differently for each.\n */\n ftsRows(sanitizedQuery: string, limit: number): Array<Record<string, unknown>> {\n return 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, 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 .all(sanitizedQuery, limit);\n }\n\n /** Substring scan — the CJK fallback. No relevance score exists here; the caller supplies one. */\n likeRows(escapedPattern: string, limit: number): Array<Record<string, unknown>> {\n return 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\n JOIN files ON chunks.file_id = files.id\n WHERE chunks.text LIKE ? ESCAPE '\\\\'\n LIMIT ?`,\n )\n .all(escapedPattern, limit) as Array<Record<string, unknown>>;\n }\n\n /** Hydrate the chunks a vector search returned by id. Empty in, empty out — no query runs. */\n chunkRowsByIds(ids: ReadonlyArray<number>): Array<Record<string, unknown>> {\n if (ids.length === 0) return [];\n const placeholders = ids.map(() => \"?\").join(\",\");\n return 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 }\n\n /** Absolute path → its row, for the corpus walk to compare hashes against disk. */\n filesByPath(): Map<string, FileRow> {\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 upsertFile(file: {\n absPath: string;\n relPath: string;\n hash: string;\n mtimeMs: number;\n source: \"memory\" | \"wiki\" | \"sessions\";\n }): number {\n const row = this.db\n .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 .get(file.absPath, file.relPath, Math.floor(file.mtimeMs), file.hash, file.source) as {\n id: number;\n };\n return row.id;\n }\n\n deleteChunksForFile(fileId: number): void {\n this.db.prepare(\"DELETE FROM chunks WHERE file_id = ?\").run(fileId);\n }\n\n insertChunk(chunk: {\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(chunk.fileId, chunk.startLine, chunk.endLine, chunk.text, chunk.hash);\n }\n\n close(): void {\n this.db.close();\n }\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 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 { diag } from \"../diagnostics.js\";\nimport { containsCjk, sanitizeFts5Query } from \"../persistence/fts5-sanitize.js\";\nimport { syncCorpus } from \"./corpus-sync.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 { blendScores, resolveWeights, truncateSnippet } from \"./index-manager-helpers.js\";\nimport { MemoryIndexRepository } from \"./index-repository.js\";\nimport type { SyncResult } from \"./memory-index.js\";\nimport { type MemoryIndex, parseSearchOptions } from \"./memory-index.js\";\nimport { loadSqliteVecExtension } from \"./sqlite-vec-loader.js\";\nimport { type MemoryRoot, memoryIndexRoot, resolveMemoryRoot } from \"./storage/memory-root.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 /** Every SQL string this class used to hold. See `index-repository.ts` for why it moved. */\n private readonly repo: MemoryIndexRepository;\n\n private constructor(\n private readonly memoryRoot: MemoryRoot,\n private readonly db: MemoryDb,\n private readonly embedding: EmbeddingRuntime | undefined,\n ) {\n this.repo = new MemoryIndexRepository(db);\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 memoryRoot = opts.memoryRoot ?? resolveMemoryRoot(opts.cwd);\n // What gets INDEXED and where the DATABASE lives are two decisions, and they diverge —\n // for one directory, not for every directory (theokit-sdk#554).\n //\n // The database stays in the project store when `memory.directory` names the directory the\n // Claude Code CLI manages, because that CLI has no index format and a binary there is an\n // artefact the partner does not understand inside a directory it owns\n // (`docs/memory-decisions.md` § 1). That argument covers exactly that directory.\n //\n // It does not reach a plain directory, and treating every root as if it did leaked: the index\n // holds `chunks.text` — the fact TEXT, which FTS5 needs — so leaving it in `<cwd>` while the\n // facts move writes one operator's personal store into every repository the agent runs in.\n const filePath = opts.filePath ?? defaultIndexPath(memoryIndexRoot(opts.cwd, memoryRoot));\n const db = await openMemoryDb({ filePath });\n const manager = new IndexManager(memoryRoot, 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 // Declares `Promise<SyncResult>` rather than repeating the shape inline. The inline version was a\n // structural copy of the interface it implements, so widening `SyncResult` with `supported` left\n // this method silently no longer assignable to `MemoryIndex` — the compiler caught it, which is\n // the argument for naming the type instead of restating it.\n async sync(): Promise<SyncResult> {\n const counts = await syncCorpus(this.repo, this.memoryRoot);\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 // `supported: true` — this implementer genuinely walks the corpus, so its counts are a\n // measurement rather than a placeholder. See SyncResult.supported.\n return { ...counts, chunksEmbedded, supported: true };\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, chunks } = this.repo.counts();\n const status: IndexStatus = {\n backend: this.vectorReady ? \"hybrid\" : \"fts-only\",\n filesIndexed: files,\n chunksIndexed: chunks,\n // Counted with SELECT COUNT(*) just above — these are measurements, not placeholders.\n countsExact: true,\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 let rows: Array<Record<string, unknown>> = [];\n try {\n rows = this.repo.ftsRows(sanitized, limit);\n } catch (err) {\n // T4.8 — CJK fallback: FTS5's default tokenizer chokes on CJK characters (no word boundaries).\n // Instead of returning empty, fall back to a LIKE search, which handles CJK correctly (slower\n // but correct). ADR D64 documents the trigram-routing deferral.\n //\n // GATED on the condition it was written for, and reported otherwise. The catch used to be\n // unconditional, so a corrupt database, a missing `chunks_fts` table (which happens when FTS5\n // is unavailable at open) and a disk error all became a LIKE scan over the whole table\n // returning plausible hits at a hardcoded 0.5 — degraded relevance with no signal that\n // anything had failed. The fallback still runs, because returning nothing would be worse; what\n // changes is that the operator learns the query is not being answered by the index.\n if (!containsCjk(query)) {\n diag(\n `memory FTS query failed for a non-CJK query and fell back to a LIKE scan — relevance is ` +\n `degraded and the index may be missing or corrupt: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\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 rows = this.repo.likeRows(escapeLikePattern(query), limit);\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 const rows = this.repo.chunkRowsByIds(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 close(): void {\n this.repo.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
|
+
{"version":3,"sources":["../src/internal/memory/storage/chunk-markdown.ts","../src/internal/memory/corpus-sync.ts","../src/internal/memory/escape-like-pattern.ts","../src/internal/memory/memory-index.ts","../src/internal/memory/lance-memory-adapter.ts","../src/internal/memory/index-manager-dispatch.ts","../src/internal/memory/index-repository.ts","../src/internal/memory/sqlite-vec-loader.ts","../src/internal/memory/vec-index.ts","../src/internal/memory/index-manager.ts"],"names":["createHash","collectMarkdownFiles","readFile","sha256","stat","resolveWeights","ConfigurationError","LanceIndex","LruEmbeddingCache","resolveMemoryRoot","defaultInd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MAAA,MAAM,OAAA,GAAU,MAAA,CAAO,GAAA,CAAI,QAAA,IAAY,CAAC,CAAA;AACxC,MAAA,MAAM,IAAA,GAAO,MAAA,CAAO,GAAA,CAAI,QAAQ,CAAA;AAChC,MAAA,OAAO;AAAA,QACL,OAAA,EAAS,MAAA,CAAO,GAAA,CAAI,EAAE,CAAA;AAAA,QACtB,IAAA;AAAA,QACA,SAAA;AAAA,QACA,OAAA;AAAA,QACA,KAAA,EAAO,CAAA;AAAA,QACP,SAAA,EAAW,CAAA;AAAA,QACX,SAASD,iCAAA,CAAgB,MAAA,CAAO,GAAA,CAAI,IAAA,IAAQ,EAAE,CAAC,CAAA;AAAA,QAC/C,MAAA,EAAQ,MAAA,CAAO,GAAA,CAAI,MAAM,CAAA;AAAA,QACzB,UAAU,CAAA,EAAG,IAAI,CAAA,CAAA,EAAI,SAAS,IAAI,OAAO,CAAA;AAAA,OAC3C;AAAA,IACF,CAAC,CAAA;AAAA,EACH;AAAA,EAEA,KAAA,GAAc;AACZ,IAAA,IAAA,CAAK,KAAK,KAAA,EAAM;AAAA,EAClB;AACF","file":"chunk-VUHXC74Q.cjs","sourcesContent":["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","/**\n * The corpus walk: read every markdown file under the memory root, and re-chunk the ones that\n * changed.\n *\n * One of the four concerns that shared `IndexManager`, and the one with the most distinct reason to\n * change — \"which files are in the corpus and when is one stale\" is a question about the filesystem,\n * not about search or about the schema. It takes a {@link MemoryIndexRepository} rather than a\n * database, so it cannot reach past it into SQL.\n *\n * The staleness test is the content hash, NOT the mtime. mtime is written into `files` for\n * observability; a file touched without being edited must not cost a re-chunk, and a file restored\n * from a backup with an older mtime must not be skipped.\n *\n * @internal\n */\n\nimport { readFile, stat } from \"node:fs/promises\";\nimport { collectMarkdownFiles, sha256 } from \"./index-manager-helpers.js\";\nimport type { MemoryIndexRepository } from \"./index-repository.js\";\nimport { chunkMarkdown } from \"./storage/chunk-markdown.js\";\nimport type { MemoryRoot } from \"./storage/memory-root.js\";\n\nexport interface CorpusSyncCounts {\n readonly filesScanned: number;\n readonly filesUpdated: number;\n readonly chunksWritten: number;\n}\n\nexport async function syncCorpus(\n repo: MemoryIndexRepository,\n memoryRoot: MemoryRoot,\n): Promise<CorpusSyncCounts> {\n const files = await collectMarkdownFiles(memoryRoot);\n const existingByPath = repo.filesByPath();\n let filesUpdated = 0;\n let chunksWritten = 0;\n\n for (const entry of files) {\n const raw = await readFile(entry.absolutePath, \"utf8\");\n const hash = sha256(raw);\n if (existingByPath.get(entry.absolutePath)?.hash === hash) continue;\n\n const stats = await stat(entry.absolutePath);\n const fileId = repo.upsertFile({\n absPath: entry.absolutePath,\n relPath: entry.relPath,\n hash,\n mtimeMs: stats.mtimeMs,\n source: entry.source,\n });\n repo.deleteChunksForFile(fileId);\n const chunks = chunkMarkdown(raw);\n for (const chunk of chunks) repo.insertChunk({ fileId, ...chunk });\n\n filesUpdated += 1;\n chunksWritten += chunks.length;\n }\n\n return { filesScanned: files.length, filesUpdated, chunksWritten };\n}\n","/**\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 * 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 * Whether this backend actually walked a corpus.\n *\n * REQUIRED, not optional, and that is the point. `MemoryIndex` has two implementers and consumers\n * hold the interface: `IndexManager` walks files, and `LanceMemoryAdapter` has no corpus to walk —\n * it is a vector store fed by explicit `addFacts`. The adapter used to answer with a frozen\n * all-zeros result, which a caller cannot tell apart from a real sync that found nothing to do.\n * The comment above it stated that as the intention (\"so callers' existing logging does not\n * break\"), which is the substitution defect written down as a feature.\n *\n * A required boolean forces every implementer to say which case it is in, and forces the compiler\n * to notice a new implementer that forgot. An optional flag would have let the next backend\n * reproduce the silence.\n */\n supported: boolean;\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. It returns zero counts with `supported: false`\n * so the result is not mistaken for a sync that found nothing. Consumers\n * writing facts hold a `LanceIndex` and call `addFacts` on it; the adapter\n * does not hand its adaptee out.\n * - `search()` is HYBRID, not vector-only. Lance supplies the vector distance\n * and `translateLanceHit` adds a client-side term-overlap ratio (T4.5), so\n * `textScore` is a real number in 0..1 and `score` is `0.7 * vectorScore +\n * 0.3 * textScore` — never `=== vectorScore`. This block said the opposite\n * for as long as T4.5 has been shipped, while the docblock 90 lines below\n * described the change correctly, so the two halves of one file disagreed\n * and the header is the half a caller reads.\n * - `status()` reports `backend: \"hybrid\"` only when an embedding runtime\n * is wired (always the case for Lance — embedding is required at open).\n * Both counts are 0 with `countsExact: false`: the port declares `status()`\n * synchronous and Lance's row count is async, so nothing can be measured\n * here. The zeros are placeholders and the flag says which.\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 HybridWeights, resolveWeights } from \"./index-manager-helpers.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/**\n * Lance has no corpus to walk, and the result now SAYS so.\n *\n * The counts stay zero — inventing numbers would trade one false claim for another. What changed is\n * `supported: false`: an all-zeros result was previously indistinguishable from a real sync that\n * found nothing to reindex, and the comment above this constant used to present that as the goal\n * (\"so callers' existing logging does not break\"). A caller can now tell \"nothing to do\" from\n * \"this backend does not do this\".\n */\nconst UNSUPPORTED_SYNC_RESULT: SyncResult = Object.freeze({\n filesScanned: 0,\n filesUpdated: 0,\n chunksWritten: 0,\n chunksEmbedded: 0,\n supported: false,\n});\n\nexport class LanceMemoryAdapter implements MemoryIndex {\n constructor(private readonly inner: LanceIndex) {}\n\n /**\n * Not applicable to Lance — see file header. Returns zero counts with `supported: false` so a\n * caller can distinguish this from a real sync that found nothing.\n */\n async sync(): Promise<SyncResult> {\n return UNSUPPORTED_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, resolveWeights(options)));\n }\n\n status(): IndexStatus {\n // The Lance API is async and `status()` is not, so no count can be taken here. The zeros are\n // placeholders and `countsExact: false` says so — previously they were indistinguishable from a\n // measured empty index, so a caller testing `chunksIndexed > 0` got a false negative on every\n // run regardless of how many rows the table held.\n //\n // There is deliberately no escape hatch. This class used to carry `unwrap(): LanceIndex`,\n // documented as being for \"the migration tool, benchmark script\" — measured 2026-09-01, it had\n // ZERO callers anywhere in the monorepo, including those two, which hold a `LanceIndex`\n // directly and never open the adapter. What it did have was this comment pointing at it, which\n // made the leak read as the supported way to work around the limitation. A caller that needs\n // the real count needs `LanceIndex`, and the honest way to get one is to open one.\n return {\n backend: \"hybrid\",\n filesIndexed: 0,\n chunksIndexed: 0,\n countsExact: false,\n };\n }\n\n async close(): Promise<void> {\n await this.inner.close();\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 | undefined,\n weights: HybridWeights,\n): MemorySearchHit {\n const textScore = query !== undefined ? computeTermOverlapScore(query, hit.text) : 0;\n const vectorScore = hit.score;\n // The CALLER's weights, through the same `resolveWeights` the SQLite path uses. These were the\n // literals 0.7 and 0.3, so a caller that tuned `vectorWeight` / `textWeight` had its tuning applied\n // on one backend and silently dropped on the other — the shape of failure that makes a swap-in\n // backend untrustworthy. The defaults differ between the two (0.6/0.4 from resolveWeights, versus\n // the 0.7/0.3 written here), so unweighted results move slightly; that is the point, since one of\n // the two numbers was not the contract's.\n const combined =\n (vectorScore * weights.vectorWeight + textScore * weights.textWeight) / weights.total;\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 * Every SQL string the memory index runs, in one place.\n *\n * `IndexManager` answered four questions with four independent reasons to change: the corpus walk,\n * the BM25-to-score normalisation, the vector-cache strategy, and the schema. This is the fourth.\n * Changing a column, an index or a join is now a change to THIS file, and the caller above it reads\n * as search logic rather than as SQL with scoring in between.\n *\n * The row-to-`MemorySearchHit` mapping deliberately stays with the caller: turning a row into a hit\n * involves a score, a snippet and a citation, none of which the schema knows about. Keeping it here\n * would move the normalisation into the repository and re-create the same mixture one layer down.\n *\n * Rows come back as `Record<string, unknown>` for the same reason: the repository knows what it\n * SELECTed, not what the caller will make of it.\n *\n * @internal\n */\n\nimport type { MemoryDb } from \"./index-db.js\";\n\n/** What `files` holds for one path — the pair the corpus walk compares against disk. */\nexport interface FileRow {\n readonly id: number;\n readonly hash: string;\n}\n\nexport class MemoryIndexRepository {\n constructor(private readonly db: MemoryDb) {}\n\n counts(): { files: number; chunks: number } {\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 return { files: Number(files.n ?? 0), chunks: Number(chunks.n ?? 0) };\n }\n\n /**\n * FTS5 match, ordered by bm25. THROWS on an FTS5 error rather than swallowing it — whether that\n * error means \"CJK input the default tokenizer cannot segment\" or \"the table is missing\" is a\n * judgement the caller makes, and it makes it differently for each.\n */\n ftsRows(sanitizedQuery: string, limit: number): Array<Record<string, unknown>> {\n return 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, 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 .all(sanitizedQuery, limit);\n }\n\n /** Substring scan — the CJK fallback. No relevance score exists here; the caller supplies one. */\n likeRows(escapedPattern: string, limit: number): Array<Record<string, unknown>> {\n return 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\n JOIN files ON chunks.file_id = files.id\n WHERE chunks.text LIKE ? ESCAPE '\\\\'\n LIMIT ?`,\n )\n .all(escapedPattern, limit) as Array<Record<string, unknown>>;\n }\n\n /** Hydrate the chunks a vector search returned by id. Empty in, empty out — no query runs. */\n chunkRowsByIds(ids: ReadonlyArray<number>): Array<Record<string, unknown>> {\n if (ids.length === 0) return [];\n const placeholders = ids.map(() => \"?\").join(\",\");\n return 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 }\n\n /** Absolute path → its row, for the corpus walk to compare hashes against disk. */\n filesByPath(): Map<string, FileRow> {\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 upsertFile(file: {\n absPath: string;\n relPath: string;\n hash: string;\n mtimeMs: number;\n source: \"memory\" | \"wiki\" | \"sessions\";\n }): number {\n const row = this.db\n .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 .get(file.absPath, file.relPath, Math.floor(file.mtimeMs), file.hash, file.source) as {\n id: number;\n };\n return row.id;\n }\n\n deleteChunksForFile(fileId: number): void {\n this.db.prepare(\"DELETE FROM chunks WHERE file_id = ?\").run(fileId);\n }\n\n insertChunk(chunk: {\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(chunk.fileId, chunk.startLine, chunk.endLine, chunk.text, chunk.hash);\n }\n\n close(): void {\n this.db.close();\n }\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 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 { diag } from \"../diagnostics.js\";\nimport { containsCjk, sanitizeFts5Query } from \"../persistence/fts5-sanitize.js\";\nimport { syncCorpus } from \"./corpus-sync.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 { blendScores, resolveWeights, truncateSnippet } from \"./index-manager-helpers.js\";\nimport { MemoryIndexRepository } from \"./index-repository.js\";\nimport type { SyncResult } from \"./memory-index.js\";\nimport { type MemoryIndex, parseSearchOptions } from \"./memory-index.js\";\nimport { loadSqliteVecExtension } from \"./sqlite-vec-loader.js\";\nimport { type MemoryRoot, memoryIndexRoot, resolveMemoryRoot } from \"./storage/memory-root.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 /** Every SQL string this class used to hold. See `index-repository.ts` for why it moved. */\n private readonly repo: MemoryIndexRepository;\n\n private constructor(\n private readonly memoryRoot: MemoryRoot,\n private readonly db: MemoryDb,\n private readonly embedding: EmbeddingRuntime | undefined,\n ) {\n this.repo = new MemoryIndexRepository(db);\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 memoryRoot = opts.memoryRoot ?? resolveMemoryRoot(opts.cwd);\n // What gets INDEXED and where the DATABASE lives are two decisions, and they diverge —\n // for one directory, not for every directory (theokit-sdk#554).\n //\n // The database stays in the project store when `memory.directory` names the directory the\n // Claude Code CLI manages, because that CLI has no index format and a binary there is an\n // artefact the partner does not understand inside a directory it owns\n // (`docs/memory-decisions.md` § 1). That argument covers exactly that directory.\n //\n // It does not reach a plain directory, and treating every root as if it did leaked: the index\n // holds `chunks.text` — the fact TEXT, which FTS5 needs — so leaving it in `<cwd>` while the\n // facts move writes one operator's personal store into every repository the agent runs in.\n const filePath = opts.filePath ?? defaultIndexPath(memoryIndexRoot(opts.cwd, memoryRoot));\n const db = await openMemoryDb({ filePath });\n const manager = new IndexManager(memoryRoot, 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 // Declares `Promise<SyncResult>` rather than repeating the shape inline. The inline version was a\n // structural copy of the interface it implements, so widening `SyncResult` with `supported` left\n // this method silently no longer assignable to `MemoryIndex` — the compiler caught it, which is\n // the argument for naming the type instead of restating it.\n async sync(): Promise<SyncResult> {\n const counts = await syncCorpus(this.repo, this.memoryRoot);\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 // `supported: true` — this implementer genuinely walks the corpus, so its counts are a\n // measurement rather than a placeholder. See SyncResult.supported.\n return { ...counts, chunksEmbedded, supported: true };\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, chunks } = this.repo.counts();\n const status: IndexStatus = {\n backend: this.vectorReady ? \"hybrid\" : \"fts-only\",\n filesIndexed: files,\n chunksIndexed: chunks,\n // Counted with SELECT COUNT(*) just above — these are measurements, not placeholders.\n countsExact: true,\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 let rows: Array<Record<string, unknown>> = [];\n try {\n rows = this.repo.ftsRows(sanitized, limit);\n } catch (err) {\n // T4.8 — CJK fallback: FTS5's default tokenizer chokes on CJK characters (no word boundaries).\n // Instead of returning empty, fall back to a LIKE search, which handles CJK correctly (slower\n // but correct). ADR D64 documents the trigram-routing deferral.\n //\n // GATED on the condition it was written for, and reported otherwise. The catch used to be\n // unconditional, so a corrupt database, a missing `chunks_fts` table (which happens when FTS5\n // is unavailable at open) and a disk error all became a LIKE scan over the whole table\n // returning plausible hits at a hardcoded 0.5 — degraded relevance with no signal that\n // anything had failed. The fallback still runs, because returning nothing would be worse; what\n // changes is that the operator learns the query is not being answered by the index.\n if (!containsCjk(query)) {\n diag(\n `memory FTS query failed for a non-CJK query and fell back to a LIKE scan — relevance is ` +\n `degraded and the index may be missing or corrupt: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\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 rows = this.repo.likeRows(escapeLikePattern(query), limit);\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 const rows = this.repo.chunkRowsByIds(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 close(): void {\n this.repo.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"]}
|
|
@@ -8,7 +8,7 @@ var CLAUDE_DIR_NAME = ".claude";
|
|
|
8
8
|
var NATIVE_SOURCE = {
|
|
9
9
|
kind: "theokit",
|
|
10
10
|
dirName: THEOKIT_DIR_LITERAL,
|
|
11
|
-
runtimeEnv: () => ({})
|
|
11
|
+
runtimeEnv: (cwd) => ({ THEOKIT_PROJECT_DIR: cwd })
|
|
12
12
|
};
|
|
13
13
|
var CLAUDE_CODE_SOURCE = {
|
|
14
14
|
kind: "claude-code",
|
|
@@ -29,6 +29,7 @@ function adaptersFor(kinds) {
|
|
|
29
29
|
return out;
|
|
30
30
|
}
|
|
31
31
|
var COMPAT_SURFACES = [
|
|
32
|
+
"context",
|
|
32
33
|
"hooks",
|
|
33
34
|
"plugins",
|
|
34
35
|
"skills",
|
|
@@ -81,7 +82,7 @@ function reportUndeclaredSources(cwd, declared) {
|
|
|
81
82
|
if (reported.has(dir)) continue;
|
|
82
83
|
reported.add(dir);
|
|
83
84
|
diagFailure(
|
|
84
|
-
`[theokit] ${adapter.dirName}/ is present but not declared, so its hooks, skills, subagents and
|
|
85
|
+
`[theokit] ${adapter.dirName}/ is present but not declared, so its hooks, skills, subagents, plugins and rules are ignored. To read it, add {"compat":{"adapters":["${adapter.kind}"]}} to .theokit/config.json \u2014 or, if you embed this SDK, pass local: { compatSources: ["${adapter.kind}"] } (usetheokit/theokit-sdk#524).
|
|
85
86
|
`
|
|
86
87
|
);
|
|
87
88
|
}
|
|
@@ -130,6 +131,6 @@ function displayTheokitHome(cwd) {
|
|
|
130
131
|
return resolved;
|
|
131
132
|
}
|
|
132
133
|
|
|
133
|
-
export { adapterForConfigPath, displayTheokitHome, getProfilesRoot, getTheokitHome, pluginBundleRoots, projectConfigRoots, reportUndeclaredSources, theokitConfigRoot, undefinedVariablesIn };
|
|
134
|
-
//# sourceMappingURL=chunk-
|
|
135
|
-
//# sourceMappingURL=chunk-
|
|
134
|
+
export { CLAUDE_DIR_NAME, THEOKIT_DIR_LITERAL, adapterForConfigPath, adaptersForSurface, displayTheokitHome, getProfilesRoot, getTheokitHome, pluginBundleRoots, projectConfigRoots, reportUndeclaredSources, theokitConfigRoot, undefinedVariablesIn };
|
|
135
|
+
//# sourceMappingURL=chunk-X7EUUHXU.js.map
|
|
136
|
+
//# sourceMappingURL=chunk-X7EUUHXU.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/internal/runtime/compat/foreign-config-sources.ts","../src/internal/persistence/paths.ts"],"names":["join"],"mappings":";;;;;AAmDO,IAAM,mBAAA,GAAsB;AAG5B,IAAM,eAAA,GAAkB;AA+BxB,IAAM,aAAA,GAAqC;AAAA,EAChD,IAAA,EAAM,SAAA;AAAA,EACN,OAAA,EAAS,mBAAA;AAAA,EACT,UAAA,EAAY,CAAC,GAAA,MAAS,EAAE,qBAAqB,GAAA,EAAI;AACnD,CAAA;AAWO,IAAM,kBAAA,GAA0C;AAAA,EACrD,IAAA,EAAM,aAAA;AAAA,EACN,OAAA,EAAS,eAAA;AAAA,EACT,UAAA,EAAY,CAAC,GAAA,MAAS,EAAE,oBAAoB,GAAA,EAAI;AAClD,CAAA;AAEA,IAAM,eAAA,GAAkD,CAAC,kBAAkB,CAAA;AAE3E,IAAM,cAAwD,IAAI,GAAA;AAAA,EAChE,CAAC,aAAA,EAAe,GAAG,eAAe,CAAA,CAAE,GAAA,CAAI,CAAC,CAAA,KAAM,CAAC,CAAA,CAAE,OAAA,EAAS,CAAC,CAAC;AAC/D,CAAA;AASO,SAAS,YAAY,KAAA,EAAiD;AAC3E,EAAA,MAAM,MAAA,GAAS,IAAI,GAAA,CAAI,eAAA,CAAgB,GAAA,CAAI,CAAC,CAAA,KAAM,CAAC,CAAA,CAAE,IAAA,EAAM,CAAC,CAAC,CAAC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,OAAO,IAAA;AAClC,EAAA,OAAO,QAAA,CAAS,IAAA,CAAK,CAAC,CAAA,KAAO,OAAO,CAAA,KAAM,QAAA,GAAW,IAAA,GAAA,CAAQ,CAAA,CAAE,MAAA,IAAU,EAAC,EAAG,QAAA,CAAS,OAAO,CAAE,CAAA;AACjG;AAQA,SAAS,YACP,OAAA,EACoC;AACpC,EAAA,OAAO,OAAA,CAAQ,MAAA,CAAO,CAAC,CAAA,KAAA,CAAO,OAAO,MAAM,QAAA,GAAW,CAAA,GAAI,CAAA,CAAE,IAAA,MAAU,WAAW,CAAA;AACnF;AAeO,SAAS,iBAAA,CACd,KACA,OAAA,EACU;AAMV,EAAA,OAAO,kBAAA,CAAmB,GAAA,EAAK,OAAA,EAAS,SAAS,CAAA,CAAE,GAAA,CAAI,CAAC,IAAA,KAASA,IAAAA,CAAK,IAAA,EAAM,SAAS,CAAC,CAAA;AACxF;AAeO,SAAS,eAAA,GAA0B;AACxC,EAAA,OAAOA,IAAAA,CAAK,OAAA,EAAQ,EAAG,mBAAA,EAAqB,UAAU,CAAA;AACxD;AAmBO,SAAS,mBAAmB,GAAA,EAAqB;AACtD,EAAA,MAAM,QAAA,GAAW,eAAe,GAAG,CAAA;AACnC,EAAA,MAAM,OAAO,OAAA,EAAQ;AACrB,EAAA,IAAI,QAAA,KAAa,MAAM,OAAO,GAAA;AAC9B,EAAA,IAAI,QAAA,CAAS,UAAA,CAAW,CAAA,EAAG,IAAI,GAAG,CAAA,EAAG;AACnC,IAAA,OAAO,CAAA,CAAA,EAAI,QAAA,CAAS,KAAA,CAAM,IAAA,CAAK,MAAM,CAAC,CAAA,CAAA;AAAA,EACxC;AACA,EAAA,OAAO,QAAA;AACT","file":"chunk-X7EUUHXU.js","sourcesContent":["import { existsSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport type { CompatSurface } from \"../../../types/agent.js\";\nimport { diagFailure } from \"../../diagnostics.js\";\n\n/*\n * The foreign configuration dialects this SDK can read, and what each one PRESUMES.\n *\n * ## Why a registry and not a list of directory names\n *\n * `projectConfigRoots` returned `[\".theokit\", \".claude\"]` — two paths — and that shape is what\n * usetheokit/theokit-sdk#522 fell through. A path says WHERE a file lives. It does not say how the\n * file is parsed, and it does not say what runtime the commands inside it were written against.\n *\n * Claude Code defines `$CLAUDE_PROJECT_DIR` for the hook commands in its `settings.json`, and its\n * documentation tells authors to reach project files through it — an absolute path would break for\n * every other person on the team, so the shape that failed here is the shape upstream recommends.\n * This SDK read the file and ran the command without the variable. `sh` expands an unset variable to\n * the empty string, so\n *\n * bash \"$CLAUDE_PROJECT_DIR/.claude/hooks/guard.sh\" became bash \"/.claude/hooks/guard.sh\"\n *\n * which does not exist, which a hook runner correctly reads as a refusal. Every turn denied, in any\n * repository that also had Claude Code set up, with a message naming a file that was present and\n * executable all along.\n *\n * Importing a format means accepting the contract that format presumes. An adapter is where that\n * contract is written down, so the next dialect (`.codex/` is the obvious one) declares its own\n * instead of inheriting a hole.\n *\n * ## What an adapter deliberately does NOT do\n *\n * It does not make the foreign source trusted, and it does not make its hooks permissive: a script\n * that exits non-zero is still a refusal. It supplies the variables the format's authors were\n * entitled to assume, and nothing else — `env` here is merged over the scrubbed inherit policy by\n * `spawnAndCollect`, so it adds names rather than widening what a child can see.\n *\n * @internal\n */\n\n/**\n * The project config directory literal.\n *\n * Renamed from `THEOKIT_DIR_NAME` in #410. Sharing a name with the (now removed) sovereign env var\n * was the MECHANISM of that defect, not scenery: every grep for the variable landed on that const\n * and looked answered, so \"is it read?\" returned five hits and nobody checked what they were.\n *\n * Lives here rather than in `persistence/paths.ts` because a directory name is one third of what a\n * dialect is — the other two being how it parses and what it presumes — and splitting the three\n * across two modules is what let the third go unwritten.\n */\nexport const THEOKIT_DIR_LITERAL = \".theokit\";\n\n/** The Claude Code CLI's project configuration directory. */\nexport const CLAUDE_DIR_NAME = \".claude\";\n\n/** A configuration dialect this SDK understands. `theokit` is native; the rest are foreign. */\nexport interface ConfigSourceAdapter {\n /** Stable identifier, and what a consumer names to opt in. */\n readonly kind: string;\n /** The project-relative directory the dialect keeps its configuration in. */\n readonly dirName: string;\n /**\n * Variables the dialect's own runtime defines for commands it executes, under the dialect's own\n * documented spellings.\n *\n * Every dialect gets a project-directory variable, because none of them can locate a\n * project-relative script without one — the inherited environment says where the PROCESS is, and\n * a hook that has to depend on the process cwd is the dependency #522 removed for the foreign\n * side. Fixing one dialect and leaving the other different was the half-fix.\n *\n * The SPELLINGS differ on purpose: a ported script reaches for the name its own docs use, and a\n * native one for this runtime's.\n */\n runtimeEnv(cwd: string): Record<string, string>;\n}\n\n/**\n * The native source. Always read, never opted into, always first for precedence.\n *\n * `THEOKIT_PROJECT_DIR` is the native counterpart of `CLAUDE_PROJECT_DIR` below. This used to be\n * `{}`, on the reasoning that a `.theokit/` hook \"is written against THIS runtime and inherits it\n * already\" — true of the runtime's BEHAVIOUR and not of a project PATH. Nothing in the inherited\n * environment says where the project is, so a native hook had to depend on the process cwd.\n */\nexport const NATIVE_SOURCE: ConfigSourceAdapter = {\n kind: \"theokit\",\n dirName: THEOKIT_DIR_LITERAL,\n runtimeEnv: (cwd) => ({ THEOKIT_PROJECT_DIR: cwd }),\n};\n\n/**\n * Claude Code.\n *\n * `CLAUDE_PROJECT_DIR` is the documented way for a hook command in `settings.json` to reach a file\n * in the project. Only that one variable is supplied: `$CLAUDE_PLUGIN_ROOT` and the rest of that\n * runtime's surface are NOT defined here, because supplying a name whose value this SDK would have\n * to invent is worse than leaving it unset — an invented root sends a script somewhere real and\n * wrong, where an unset one fails loudly.\n */\nexport const CLAUDE_CODE_SOURCE: ConfigSourceAdapter = {\n kind: \"claude-code\",\n dirName: CLAUDE_DIR_NAME,\n runtimeEnv: (cwd) => ({ CLAUDE_PROJECT_DIR: cwd }),\n};\n\nconst FOREIGN_SOURCES: readonly ConfigSourceAdapter[] = [CLAUDE_CODE_SOURCE];\n\nconst BY_DIR_NAME: ReadonlyMap<string, ConfigSourceAdapter> = new Map(\n [NATIVE_SOURCE, ...FOREIGN_SOURCES].map((a) => [a.dirName, a]),\n);\n\n/**\n * The adapters a caller declared, in declaration order, skipping any name that names no adapter.\n *\n * An unknown name is DROPPED rather than turned into `<cwd>/<name>`: a typo must fail closed. Making\n * a directory out of an unrecognised string would import a dialect nothing knows how to parse — and\n * the whole reason this exists is that a directory name was never enough to describe a dialect.\n */\nexport function adaptersFor(kinds: readonly string[]): ConfigSourceAdapter[] {\n const byKind = new Map(FOREIGN_SOURCES.map((a) => [a.kind, a]));\n const out: ConfigSourceAdapter[] = [];\n for (const kind of kinds) {\n const adapter = byKind.get(kind);\n if (adapter !== undefined && !out.includes(adapter)) out.push(adapter);\n }\n return out;\n}\n\n/**\n * #586 — re-exported from `types/agent.ts` rather than declared here, which is what it used to be.\n *\n * Two independent declarations of one public contract: `AgentOptions.local.compatSources` was typed\n * by the public one, `persistence/paths.ts` by this one, and neither imported the other. Measured:\n * adding a member to one alone produced ZERO type errors, because structurally-identical unions\n * compare equal and the two halves would simply stop agreeing about which surfaces exist.\n *\n * Neither direction of that drift raises anything. Widen the public type and a caller declares a\n * surface the admission logic ignores; widen this one and the loader admits a surface no public\n * caller can name. Both produce a declaration that reads as honoured and is not — the failure #524\n * exists to prevent, one layer down.\n *\n * `types/` is a leaf by design (theokit#146), so the public declaration is the one that stays and\n * this module imports it. The docblock that lived here — a skill is text entering the system prompt,\n * a hook is command execution, a plugin is code loading — is on the declaration in `types/agent.ts`.\n */\nexport type { CompatSurface };\n\n/**\n * The runtime list. A type cannot be enumerated at runtime, so this is the one place the members are\n * written twice by necessity — and {@link assertCompatSurfacesExhaustive} below is what stops that\n * second copy from being a second source of truth.\n *\n * `as const satisfies` rather than an annotation, and the difference is the whole guard: annotating\n * it `readonly CompatSurface[]` widens each entry back to `CompatSurface`, so the check below\n * compares a type against itself and passes on any drift. Measured on the first attempt — a member\n * added to the public type alone produced zero errors. `satisfies` keeps the literals while still\n * rejecting an entry that is not a surface, which is both directions at once.\n */\nconst COMPAT_SURFACES = [\n \"context\",\n \"hooks\",\n \"plugins\",\n \"skills\",\n \"subagents\",\n] as const satisfies readonly CompatSurface[];\n\n/**\n * Compile-time guard: adding a member to {@link CompatSurface} without adding it to\n * {@link COMPAT_SURFACES} fails `tsc` here.\n *\n * Never called. It exists so the pairing is checked by the compiler rather than by whoever\n * remembers — which is the entire lesson of #586, applied to the copy that could not be removed.\n */\nfunction assertCompatSurfacesExhaustive(surface: CompatSurface): (typeof COMPAT_SURFACES)[number] {\n return surface;\n}\nvoid assertCompatSurfacesExhaustive;\n\n/**\n * A declared foreign source: a bare kind, or a kind with the surfaces it may be read for.\n */\nexport type CompatSourceDeclaration =\n | string\n | { readonly kind: string; readonly import?: readonly string[] };\n\n/**\n * The adapters admitted to ONE surface.\n *\n * Three rules, and each one fails closed:\n *\n * - A bare string admits every surface. It is what `5.0.0-next.1` published, so narrowing it\n * silently would turn a working opt-in into a no-op — the exact defect #524 is about, one level\n * up.\n * - An object with no `import` admits nothing. The issue's own rule, and safe to apply strictly\n * because the object form is new and nobody can be depending on it.\n * - An unrecognised surface name is dropped rather than matched loosely, for the same reason an\n * unrecognised KIND is dropped in {@link adaptersFor}: a typo must not silently widen access.\n */\nexport function adaptersForSurface(\n sources: readonly CompatSourceDeclaration[],\n surface: CompatSurface,\n): ConfigSourceAdapter[] {\n const admitted: string[] = [];\n for (const source of sources) {\n if (typeof source === \"string\") {\n admitted.push(source);\n continue;\n }\n const wanted = source.import ?? [];\n if (wanted.some((s) => s === surface && COMPAT_SURFACES.includes(s as CompatSurface))) {\n admitted.push(source.kind);\n }\n }\n return adaptersFor(admitted);\n}\n\n/**\n * The adapter whose directory an absolute config path sits under, or `undefined` for a path that\n * belongs to no registered dialect.\n *\n * Matched on the path SEGMENT rather than with `includes`, so a workspace that happens to live under\n * `/home/me/.claude-backups/repo` does not read as a Claude Code source.\n */\nexport function adapterForConfigPath(path: string): ConfigSourceAdapter | undefined {\n for (const segment of path.split(/[\\\\/]/)) {\n const adapter = BY_DIR_NAME.get(segment);\n if (adapter !== undefined) return adapter;\n }\n return undefined;\n}\n\n/**\n * Variable references in a shell command that nothing will define.\n *\n * The second half of #522, and the half that cost the debugging session. `sh` expands an unset\n * variable to the empty string and says nothing, so the failure surfaces ten characters later as a\n * path: `bash: /.claude/hooks/guard.sh: No such file or directory` — which reads as \"your script is\n * missing\" while the script is present and executable. Nothing in that message contains the name of\n * the variable that was actually missing, so the reader looks in the wrong place.\n *\n * Checked against BOTH the process environment and the variables the dialect supplies, because\n * either is a legitimate source: a hook may reasonably use `$HOME`.\n *\n * ## What it deliberately does not try to be\n *\n * This is not a shell parser. It finds `$NAME` and `${NAME}` outside single quotes, which is the\n * shape a config file's hook commands take. It does NOT understand `${NAME:-default}` (a default\n * makes the variable optional, so it is not reported), assignments earlier in the same command, or\n * variables a sourced script exports. A false NEGATIVE there costs the old behaviour — the confusing\n * path error — and a false positive would deny a hook that would have worked, so the parse errs\n * toward silence and the check only ever ADDS a name to a failure that already happened.\n */\nexport function undefinedVariablesIn(\n command: string,\n supplied: Readonly<Record<string, string>>,\n env: Readonly<Record<string, string | undefined>> = process.env,\n): string[] {\n // Single-quoted spans are literal in `sh`: `echo '$FOO'` prints the dollar sign.\n const unquoted = command.replace(/'[^']*'/g, \" \");\n const names = new Set<string>();\n for (const match of unquoted.matchAll(\n /\\$\\{([A-Za-z_][A-Za-z0-9_]*)\\}|\\$([A-Za-z_][A-Za-z0-9_]*)/g,\n )) {\n const name = match[1] ?? match[2];\n if (name === undefined) continue;\n if (name in supplied) continue;\n if (env[name] !== undefined) continue;\n names.add(name);\n }\n return [...names];\n}\n\n/**\n * Workspaces already reported, so repeated agent construction in one process says it once.\n *\n * Keyed by the resolved directory rather than by dialect kind, so a long-lived host that drives\n * several workspaces still reports each of them.\n */\nconst reported = new Set<string>();\n\n/**\n * Reports a foreign configuration directory that exists in the workspace and was not declared.\n *\n * ## Why the flip needs a voice\n *\n * Before #524 a `.claude/` was read with no opt-in; after it, the same directory is ignored. From\n * inside the repository the two states are indistinguishable — the hook file is there, it is\n * executable, and it does not run. The only remaining way to learn why is a CHANGELOG entry for a\n * version the reader may not know they crossed.\n *\n * ## Why `diagFailure` rather than `diag` (#563)\n *\n * This used `diag`, on the reasoning that ignoring an undeclared directory is not a failure and\n * that a repository which does NOT want the import should not pay a stderr line for behaving as\n * instructed. The reasoning was sound and rested on a premise nobody checked: that a host would\n * have installed a sink.\n *\n * Measured against the published `5.0.0`. `diag` returns without doing anything when no sink is\n * installed. The SDK installs none — `currentSink()` reads a `globalThis` slot only\n * `setDiagnosticsSink` fills. Neither observable host installs one either: `theocode` renamed the\n * key, and `theokit` exports `installDiagnosticSink` and never calls it. Two hosts out of two, and\n * the SDK itself. So the message the CHANGELOG promised — \"says so once, on the diagnostics\n * channel\" — reached nobody, while the consumer lost hooks, skills, subagents and plugins.\n *\n * A mitigation announced in release notes for a silent loss of capability is not a diagnostic. It\n * is the error path of the breaking change itself, and `diagFailure` exists for exactly the message\n * that must not be swallowed.\n *\n * The cost the old reasoning named is real and is now paid: a repository that wants the directory\n * ignored sees a line. What makes that acceptable — ONCE per directory per process, not per turn\n * (`reported` below); and before #524 that repository was having `.claude/` imported anyway, so the\n * line it now sees confirms the fix it wanted. The asymmetry is one line of text against silently\n * losing four subsystems.\n *\n * A host that installs a sink still owns its render surface: `diagFailure` prefers the sink and\n * only falls back to stderr when there is none.\n *\n * NOT solved here: there is no way to say \"I know, and I want none\". `compatSources: []` would be\n * the natural spelling, but `resolveCompatSources` collapses it into the same `[]` an absent option\n * produces, so this function cannot tell them apart. If the noise turns out to matter, threading\n * that distinction through is the shape of the fix.\n */\nexport function reportUndeclaredSources(\n cwd: string,\n declared: readonly CompatSourceDeclaration[],\n): void {\n // A kind named with a NARROW import list has still been declared: the consumer knows the\n // directory is there and chose which surfaces to admit. Warning them anyway would be the noise\n // that gets a warning ignored, and this one has exactly one job — telling somebody who does NOT\n // know the directory is being skipped.\n const declaredKinds = new Set(\n adaptersFor(declared.map((d) => (typeof d === \"string\" ? d : d.kind))).map((a) => a.kind),\n );\n for (const adapter of FOREIGN_SOURCES) {\n if (declaredKinds.has(adapter.kind)) continue;\n const dir = join(cwd, adapter.dirName);\n if (!existsSync(dir)) continue;\n if (reported.has(dir)) continue;\n reported.add(dir);\n // THE FILE IS NAMED FIRST because it is the entry point this message's reader can use.\n //\n // #524 gives the declaration two entry points for one shape: `.theokit/config.json`'s\n // `compat.adapters`, and `local.compatSources` in code. Until this change the warning named\n // only the second — and `local` is an argument the SDK's EMBEDDER passes, not something the\n // person reading the line can reach. Reported by the `theocode` session against 5.0.1: a user\n // of a host that embeds this SDK is told to pass an option that does not exist on their\n // surface, which is advice that is true about the mechanism and unusable as an action.\n //\n // The file is writable by anyone holding the workspace, which is exactly who sees this line.\n //\n // WHAT THIS LINE CANNOT KNOW, and it is a real limit rather than a caveat for form's sake. It\n // reports one fact: this SDK is ignoring the directory because nothing declared it. A HOST\n // embedding the SDK may be withholding the same directory for its own reasons — `theocode`\n // gates repository configuration on a trust posture — and the SDK cannot see that gate.\n //\n // So in a host that is also withholding, following this advice makes the warning stop and\n // changes nothing the user can do. That silence is honest about the SDK (it did stop ignoring\n // the directory) and uninformative about the outcome. Measured by the `theocode` session with\n // the control that settles it: a NATIVE `.theokit/` hook does not fire there either, so the\n // host's gate — not this declaration — is what holds the capability back.\n //\n // Nothing here can fix that. If a host ever gains a way to say \"I am withholding this too\",\n // this is the line where that belongs.\n diagFailure(\n `[theokit] ${adapter.dirName}/ is present but not declared, so its hooks, skills, subagents, ` +\n `plugins and rules are ignored. To read it, add ` +\n `{\"compat\":{\"adapters\":[\"${adapter.kind}\"]}} to .theokit/config.json — or, if you embed ` +\n `this SDK, pass local: { compatSources: [\"${adapter.kind}\"] } ` +\n `(usetheokit/theokit-sdk#524).\\n`,\n );\n }\n}\n","/**\n * Path resolution for SDK state files (ADR D60).\n *\n * Theokit anchors state at `<cwd>/.theokit/` by default (per-cwd). An\n * optional `THEOKIT_HOME` environment variable overrides this, enabling\n * test isolation, profile switching, and multi-tenant deployments.\n *\n * Rules:\n * - `getTheokitHome(cwd)` is the canonical resolver **for cwd-anchored state**. Never hardcode\n * `path.join(cwd, \".theokit\")` in callers — use this function so tests\n * and overrides stay consistent.\n *\n * M94 — this comment said \"the ONLY canonical resolver\", and stopped being true: the\n * transcript gained `transcriptRoot()`, which is **home-anchored** (`~/.theokit`) with the same\n * `THEOKIT_HOME` override. The two defaults differ on purpose — unifying would move the\n * transcript of everyone who does NOT set the variable, which is a data migration and not a\n * re-export.\n *\n * A consequence worth writing down: **without `THEOKIT_HOME` the state stays split in two**\n * — registry in `<cwd>/.theokit`, transcript in `~/.theokit`. M94 unifies only for those who set\n * the variable. Unifying both defaults is another milestone's work.\n * - `getProfilesRoot()` is intentionally home-anchored (not affected by\n * `THEOKIT_HOME`) so `theokit profile list` discovers all profiles\n * regardless of which is active.\n * - `displayTheokitHome(cwd)` returns a human-readable path for logs.\n *\n * @internal\n */\n\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport {\n adaptersForSurface,\n type CompatSourceDeclaration,\n type CompatSurface,\n THEOKIT_DIR_LITERAL,\n} from \"../runtime/compat/foreign-config-sources.js\";\n\n// The directory names live with the dialect registry that owns them — a name is one third of what a\n// configuration dialect is, and keeping the three together is what stops the next one shipping\n// without its runtime contract (#522).\n\n/**\n * Resolve the directory cwd-anchored SDK state lives in.\n *\n * `THEOKIT_HOME` wins when it is set and not blank after trimming; the trimmed value is used, and\n * it is used VERBATIM — it is not resolved against `cwd`, so a relative value stays relative and\n * `.theokit` is not appended to it. Otherwise the answer is `<cwd>/.theokit`.\n *\n * The environment is read on every call, so a change to the variable takes effect immediately\n * rather than being frozen at import.\n *\n * This creates nothing and checks nothing: the returned path may not exist, and the caller owns\n * the `mkdir`. Call it instead of writing `join(cwd, \".theokit\")` by hand, or the override stops\n * working for that one call site and tests silently touch the real home.\n *\n * Not the whole story about where state lives — the transcript is home-anchored via\n * `transcriptRoot()`, honoring the same variable but defaulting to `~/.theokit`. With\n * `THEOKIT_HOME` unset, state is genuinely split between two roots.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function getTheokitHome(cwd: string): string {\n const override = process.env.THEOKIT_HOME?.trim();\n if (override !== undefined && override.length > 0) {\n return override;\n }\n return join(cwd, THEOKIT_DIR_LITERAL);\n}\n\n/**\n * The project's own configuration root: `<cwd>/.theokit`, always — never `THEOKIT_HOME`.\n *\n * `THEOKIT_HOME` relocates cwd-anchored SDK STATE (sessions, credentials). A project's\n * CONFIGURATION belongs to the repository: hooks, MCP servers, context sources, subagents, the\n * personality a project declares, all committed to git and shared by a team. Following the\n * override for any of them would move where a project's declared capabilities come from — a\n * behaviour change wearing the costume of a refactor, which is exactly what this function exists\n * to make impossible to do by accident: every config-class reader calls this instead of writing\n * `join(cwd, \".theokit\")` by hand.\n *\n * NOT for the `.claude/`-style foreign roots {@link adaptersForSurface} adds — those are additive,\n * opt-in, and each has its own directory name.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function theokitConfigRoot(cwd: string): string {\n return join(cwd, THEOKIT_DIR_LITERAL);\n}\n\n/**\n * Every directory a project's configuration may be read from, in precedence order.\n *\n * `.theokit` first — via {@link theokitConfigRoot}, so it is NEVER affected by `THEOKIT_HOME` for\n * the reason documented there — then `.claude`. The order is the whole contract: a project that\n * declares a skill, agent or rule in both means the explicit namespace to win, and a caller merging\n * these roots must therefore keep the FIRST occurrence of a name rather than the last.\n *\n * `.claude` is read because the formats already agree and only the location did not. Measured\n * 2026-08-26: the SKILL.md frontmatter this SDK requires (`name` + `description`) is exactly what\n * the CLI writes, its hook config is the same JSON shape, and 59 of the CLI's agent declarations\n * parse here unchanged. A repository set up for the CLI was failing on the directory name alone.\n *\n * NOT a rename of `.theokit`, and not a migration. Both are read, so nothing that works today stops\n * working — which is why this returns a LIST and not a single resolved answer.\n *\n * Creates nothing and checks nothing; either path may not exist, and the caller owns that.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function projectConfigRoots(\n cwd: string,\n sources: readonly CompatSourceDeclaration[],\n surface: CompatSurface,\n): string[] {\n const own = nativeAdmitsSurface(sources, surface) ? [theokitConfigRoot(cwd)] : [];\n return [\n ...own,\n ...adaptersForSurface(foreignOnly(sources), surface).map((a) => join(cwd, a.dirName)),\n ];\n}\n\n/** The kind a consumer names to declare THIS package's own root. */\nconst NATIVE_KIND = \"theokit\";\n\n/**\n * #631 — whether the native root contributes `surface`.\n *\n * Undeclared means every surface, which is what this function returned unconditionally before and\n * is what every existing caller gets. A consumer that names the kind is opting into the same\n * per-surface contract a foreign dialect already has, and the defaults match on purpose: a bare\n * string admits everything, an object admits exactly what its `import` lists. Two vocabularies that\n * look identical and disagree about the default would be worse than one.\n *\n * The asymmetry this closes had a measured cost. `hookConfigCandidates` reads `settings.json` from\n * every root, so a consumer keeping its own configuration in `.theokit/settings.json` had that\n * file's `hooks` key executed by this package, and `settingSources` gave it no way to decline: it\n * grants a foreign dialect per SOURCE, not per surface, so dropping `claude-code` to avoid its\n * hooks would also drop its skills, agents and rules.\n */\nfunction nativeAdmitsSurface(\n sources: readonly CompatSourceDeclaration[],\n surface: CompatSurface,\n): boolean {\n const declared = sources.filter((s) => (typeof s === \"string\" ? s : s.kind) === NATIVE_KIND);\n if (declared.length === 0) return true;\n return declared.some((s) => (typeof s === \"string\" ? true : (s.import ?? []).includes(surface)));\n}\n\n/**\n * The native declaration is consumed here and must not reach `adaptersForSurface`, which resolves\n * kinds to FOREIGN adapters. It would be dropped there as unrecognised — harmlessly, today — but\n * relying on that would make this behaviour depend on another function failing to find something,\n * which is the kind of coupling that breaks the moment an adapter of that name is added.\n */\nfunction foreignOnly(\n sources: readonly CompatSourceDeclaration[],\n): readonly CompatSourceDeclaration[] {\n return sources.filter((s) => (typeof s === \"string\" ? s : s.kind) !== NATIVE_KIND);\n}\n\n/**\n * Every directory that may hold a plugin BUNDLE contributed by the Claude Code CLI.\n *\n * A CLI plugin is not a JS entry point — it is a folder whose `skills/` and `agents/` are what it\n * exists to provide. Measured 2026-08-26 on an installed one: seven agents and three skills beside\n * a manifest in `.claude-plugin/plugin.json`. Parsing that manifest and stopping there produced a\n * plugin that loaded and did nothing.\n *\n * Project-scoped deliberately. The CLI also keeps plugins under `~/.claude/plugins/cache`, behind\n * its own installer and enable/disable state — reproducing that is an installation system, not\n * reading a project's configuration, and guessing at someone's enablement would run code they\n * turned off.\n */\nexport function pluginBundleRoots(\n cwd: string,\n sources: readonly CompatSourceDeclaration[],\n): string[] {\n // Always the `plugins` surface, including when the caller wants the SKILLS a bundle carries.\n // A bundle is code, and its skills arrive attached to it: admitting `skills` alone must not\n // reach inside a foreign plugin directory, or the narrower permission would silently grant the\n // wider one. `skills-manager` and `subagents-loader` both read bundle contents and both go\n // through here, so the rule holds in one place rather than three.\n return projectConfigRoots(cwd, sources, \"plugins\").map((root) => join(root, \"plugins\"));\n}\n\n/**\n * The directory holding every profile: always `~/.theokit/profiles`, from `os.homedir()`.\n *\n * Deliberately NOT affected by `THEOKIT_HOME`, which is the one thing to remember about it. If it\n * followed the override, a session pointed at one profile would only be able to see that profile,\n * and `theokit profile list` could never enumerate the rest. Profiles are the thing the override\n * switches between, so their index cannot live behind it.\n *\n * Takes no `cwd` for the same reason. Creates nothing; the path may not exist.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function getProfilesRoot(): string {\n return join(homedir(), THEOKIT_DIR_LITERAL, \"profiles\");\n}\n\n/**\n * The same path `getTheokitHome(cwd)` returns, shortened for display: the home directory prefix\n * collapses to `~`, so `/home/ada/.theokit` prints as `~/.theokit`.\n *\n * For humans only — log lines, CLI output, error messages. The result is NOT a usable path: `~`\n * is a shell convention that `fs` does not expand, so passing this to a filesystem call resolves\n * a literal directory named `~` relative to the process cwd. Use `getTheokitHome` for anything\n * that touches disk.\n *\n * Collapsing is a prefix match on the home directory followed by a literal `/`, so a sibling like\n * `/home/adalovelace` is left alone even though `/home/ada` is a string prefix of it. A path\n * outside the home directory comes back unchanged — and so does a Windows path, where the\n * separator is a backslash and the prefix test therefore never matches.\n *\n * Semver-exempt: reachable via the `@theokit/sdk/internal/persistence` sub-path, which the package\n * declares in `exports` but does NOT cover with its semver contract.\n */\nexport function displayTheokitHome(cwd: string): string {\n const resolved = getTheokitHome(cwd);\n const home = homedir();\n if (resolved === home) return \"~\";\n if (resolved.startsWith(`${home}/`)) {\n return `~${resolved.slice(home.length)}`;\n }\n return resolved;\n}\n"]}
|
package/dist/context/index.cjs
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
var
|
|
3
|
+
var chunkEIOMN5VA_cjs = require('../chunk-EIOMN5VA.cjs');
|
|
4
4
|
require('../chunk-KRD3GQAA.cjs');
|
|
5
|
-
var
|
|
5
|
+
var chunkLD6HASA5_cjs = require('../chunk-LD6HASA5.cjs');
|
|
6
6
|
require('../chunk-SA6K24NB.cjs');
|
|
7
7
|
|
|
8
8
|
// src/context/index.ts
|
|
@@ -13,24 +13,24 @@ function resolveContextImports(content, basePath, options) {
|
|
|
13
13
|
maxBytesPerFile: options.maxBytesPerFile,
|
|
14
14
|
projectRoot: options.projectRoot
|
|
15
15
|
};
|
|
16
|
-
return
|
|
16
|
+
return chunkEIOMN5VA_cjs.resolveImports(content, basePath, internalOptions);
|
|
17
17
|
}
|
|
18
18
|
|
|
19
19
|
Object.defineProperty(exports, "parseRules", {
|
|
20
20
|
enumerable: true,
|
|
21
|
-
get: function () { return
|
|
21
|
+
get: function () { return chunkEIOMN5VA_cjs.parseRules; }
|
|
22
22
|
});
|
|
23
23
|
Object.defineProperty(exports, "runDiscovery", {
|
|
24
24
|
enumerable: true,
|
|
25
|
-
get: function () { return
|
|
25
|
+
get: function () { return chunkEIOMN5VA_cjs.runDiscovery; }
|
|
26
26
|
});
|
|
27
27
|
Object.defineProperty(exports, "shouldActivateRule", {
|
|
28
28
|
enumerable: true,
|
|
29
|
-
get: function () { return
|
|
29
|
+
get: function () { return chunkEIOMN5VA_cjs.shouldActivateRule; }
|
|
30
30
|
});
|
|
31
31
|
Object.defineProperty(exports, "DEFAULT_DISCOVERY_SPECS", {
|
|
32
32
|
enumerable: true,
|
|
33
|
-
get: function () { return
|
|
33
|
+
get: function () { return chunkLD6HASA5_cjs.DEFAULT_DISCOVERY_SPECS; }
|
|
34
34
|
});
|
|
35
35
|
exports.resolveContextImports = resolveContextImports;
|
|
36
36
|
//# sourceMappingURL=index.cjs.map
|