@theokit/sdk 5.0.0-next.3 → 5.0.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.
Files changed (52) hide show
  1. package/CHANGELOG.md +978 -0
  2. package/dist/{agent-V6YLX3W6.cjs → agent-5BJF255U.cjs} +6 -6
  3. package/dist/{agent-V6YLX3W6.cjs.map → agent-5BJF255U.cjs.map} +1 -1
  4. package/dist/{agent-2KJ3IGRA.js → agent-HACVHN2V.js} +5 -5
  5. package/dist/{agent-2KJ3IGRA.js.map → agent-HACVHN2V.js.map} +1 -1
  6. package/dist/{chunk-CYKKYNOT.js → chunk-7SZAV6QG.js} +4 -4
  7. package/dist/chunk-7SZAV6QG.js.map +1 -0
  8. package/dist/{chunk-L4RPP6ZC.js → chunk-M3QNTHMV.js} +3 -3
  9. package/dist/{chunk-L4RPP6ZC.js.map → chunk-M3QNTHMV.js.map} +1 -1
  10. package/dist/{chunk-RXZSVNDG.cjs → chunk-NQTNSHSB.cjs} +7 -3
  11. package/dist/chunk-NQTNSHSB.cjs.map +1 -0
  12. package/dist/{chunk-GO5QW4YL.js → chunk-OXQSNOYV.js} +5 -5
  13. package/dist/{chunk-GO5QW4YL.js.map → chunk-OXQSNOYV.js.map} +1 -1
  14. package/dist/{chunk-J2SH3PNH.js → chunk-SADXXGWU.js} +6 -3
  15. package/dist/chunk-SADXXGWU.js.map +1 -0
  16. package/dist/{chunk-VNDJS6I3.cjs → chunk-VPK6PHIE.cjs} +8 -8
  17. package/dist/{chunk-VNDJS6I3.cjs.map → chunk-VPK6PHIE.cjs.map} +1 -1
  18. package/dist/{chunk-K6VDRJ6I.cjs → chunk-VVJ7FQAQ.cjs} +20 -19
  19. package/dist/{chunk-K6VDRJ6I.cjs.map → chunk-VVJ7FQAQ.cjs.map} +1 -1
  20. package/dist/{chunk-DX4RUWOK.js → chunk-WS5ULCL4.js} +3 -3
  21. package/dist/{chunk-DX4RUWOK.js.map → chunk-WS5ULCL4.js.map} +1 -1
  22. package/dist/{chunk-GJKMSGZ7.cjs → chunk-WWZO2TTK.cjs} +4 -4
  23. package/dist/{chunk-GJKMSGZ7.cjs.map → chunk-WWZO2TTK.cjs.map} +1 -1
  24. package/dist/{chunk-KBXADFBJ.cjs → chunk-Z2JFX372.cjs} +15 -15
  25. package/dist/chunk-Z2JFX372.cjs.map +1 -0
  26. package/dist/cron.cjs +5 -5
  27. package/dist/cron.js +4 -4
  28. package/dist/eval.cjs +4 -4
  29. package/dist/eval.js +3 -3
  30. package/dist/{index-manager-OL6HTYAO.cjs → index-manager-3UNPYH34.cjs} +5 -5
  31. package/dist/{index-manager-OL6HTYAO.cjs.map → index-manager-3UNPYH34.cjs.map} +1 -1
  32. package/dist/{index-manager-E56WW5RO.js → index-manager-W7FDMGEG.js} +4 -4
  33. package/dist/{index-manager-E56WW5RO.js.map → index-manager-W7FDMGEG.js.map} +1 -1
  34. package/dist/index.cjs +36 -28
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.d.cts +42 -1
  37. package/dist/index.d.ts +42 -1
  38. package/dist/index.js +18 -11
  39. package/dist/index.js.map +1 -1
  40. package/dist/internal/memory/storage/index.cjs +34 -30
  41. package/dist/internal/memory/storage/index.d.cts +1 -1
  42. package/dist/internal/memory/storage/index.d.ts +1 -1
  43. package/dist/internal/memory/storage/index.js +2 -2
  44. package/dist/internal/memory/storage/memory-root.d.cts +17 -0
  45. package/dist/internal/memory/storage/memory-root.d.ts +17 -0
  46. package/docs/harness-capability-map.md +5 -1
  47. package/docs/memory-decisions.md +41 -20
  48. package/package.json +2 -2
  49. package/dist/chunk-CYKKYNOT.js.map +0 -1
  50. package/dist/chunk-J2SH3PNH.js.map +0 -1
  51. package/dist/chunk-KBXADFBJ.cjs.map +0 -1
  52. package/dist/chunk-RXZSVNDG.cjs.map +0 -1
@@ -1,8 +1,8 @@
1
1
  'use strict';
2
2
 
3
- var chunkVNDJS6I3_cjs = require('../../../chunk-VNDJS6I3.cjs');
3
+ var chunkVPK6PHIE_cjs = require('../../../chunk-VPK6PHIE.cjs');
4
4
  var chunkTMKTSYDS_cjs = require('../../../chunk-TMKTSYDS.cjs');
5
- var chunkRXZSVNDG_cjs = require('../../../chunk-RXZSVNDG.cjs');
5
+ var chunkNQTNSHSB_cjs = require('../../../chunk-NQTNSHSB.cjs');
6
6
  require('../../../chunk-KRD3GQAA.cjs');
7
7
  require('../../../chunk-MUUQ2WFJ.cjs');
8
8
  require('../../../chunk-LOHMT36V.cjs');
@@ -19,23 +19,23 @@ require('../../../chunk-6LHQPOMI.cjs');
19
19
 
20
20
  Object.defineProperty(exports, "appendDiaryEntry", {
21
21
  enumerable: true,
22
- get: function () { return chunkVNDJS6I3_cjs.appendDiaryEntry; }
22
+ get: function () { return chunkVPK6PHIE_cjs.appendDiaryEntry; }
23
23
  });
24
24
  Object.defineProperty(exports, "diaryPath", {
25
25
  enumerable: true,
26
- get: function () { return chunkVNDJS6I3_cjs.diaryPath; }
26
+ get: function () { return chunkVPK6PHIE_cjs.diaryPath; }
27
27
  });
28
28
  Object.defineProperty(exports, "entryHash", {
29
29
  enumerable: true,
30
- get: function () { return chunkVNDJS6I3_cjs.entryHash; }
30
+ get: function () { return chunkVPK6PHIE_cjs.entryHash; }
31
31
  });
32
32
  Object.defineProperty(exports, "readAllSqliteFacts", {
33
33
  enumerable: true,
34
- get: function () { return chunkVNDJS6I3_cjs.readAllSqliteFacts; }
34
+ get: function () { return chunkVPK6PHIE_cjs.readAllSqliteFacts; }
35
35
  });
36
36
  Object.defineProperty(exports, "renderDiaryEntry", {
37
37
  enumerable: true,
38
- get: function () { return chunkVNDJS6I3_cjs.renderDiaryEntry; }
38
+ get: function () { return chunkVPK6PHIE_cjs.renderDiaryEntry; }
39
39
  });
40
40
  Object.defineProperty(exports, "persistActiveMemoryTranscript", {
41
41
  enumerable: true,
@@ -43,95 +43,99 @@ Object.defineProperty(exports, "persistActiveMemoryTranscript", {
43
43
  });
44
44
  Object.defineProperty(exports, "MEMORY_INDEX_MAX_BYTES", {
45
45
  enumerable: true,
46
- get: function () { return chunkRXZSVNDG_cjs.MEMORY_INDEX_MAX_BYTES; }
46
+ get: function () { return chunkNQTNSHSB_cjs.MEMORY_INDEX_MAX_BYTES; }
47
47
  });
48
48
  Object.defineProperty(exports, "MEMORY_INDEX_MAX_LINES", {
49
49
  enumerable: true,
50
- get: function () { return chunkRXZSVNDG_cjs.MEMORY_INDEX_MAX_LINES; }
50
+ get: function () { return chunkNQTNSHSB_cjs.MEMORY_INDEX_MAX_LINES; }
51
51
  });
52
52
  Object.defineProperty(exports, "appendFact", {
53
53
  enumerable: true,
54
- get: function () { return chunkRXZSVNDG_cjs.appendFact; }
54
+ get: function () { return chunkNQTNSHSB_cjs.appendFact; }
55
55
  });
56
56
  Object.defineProperty(exports, "appendFactToMarkdown", {
57
57
  enumerable: true,
58
- get: function () { return chunkRXZSVNDG_cjs.appendFactToMarkdown; }
58
+ get: function () { return chunkNQTNSHSB_cjs.appendFactToMarkdown; }
59
59
  });
60
60
  Object.defineProperty(exports, "asMemoryRoot", {
61
61
  enumerable: true,
62
- get: function () { return chunkRXZSVNDG_cjs.asMemoryRoot; }
62
+ get: function () { return chunkNQTNSHSB_cjs.asMemoryRoot; }
63
63
  });
64
64
  Object.defineProperty(exports, "claudeProjectMemoryDir", {
65
65
  enumerable: true,
66
- get: function () { return chunkRXZSVNDG_cjs.claudeProjectMemoryDir; }
66
+ get: function () { return chunkNQTNSHSB_cjs.claudeProjectMemoryDir; }
67
67
  });
68
68
  Object.defineProperty(exports, "collectMarkdownFiles", {
69
69
  enumerable: true,
70
- get: function () { return chunkRXZSVNDG_cjs.collectMarkdownFiles; }
70
+ get: function () { return chunkNQTNSHSB_cjs.collectMarkdownFiles; }
71
71
  });
72
72
  Object.defineProperty(exports, "defaultIndexPath", {
73
73
  enumerable: true,
74
- get: function () { return chunkRXZSVNDG_cjs.defaultIndexPath; }
74
+ get: function () { return chunkNQTNSHSB_cjs.defaultIndexPath; }
75
75
  });
76
76
  Object.defineProperty(exports, "discoverSessionFiles", {
77
77
  enumerable: true,
78
- get: function () { return chunkRXZSVNDG_cjs.discoverSessionFiles; }
78
+ get: function () { return chunkNQTNSHSB_cjs.discoverSessionFiles; }
79
79
  });
80
80
  Object.defineProperty(exports, "discoverWikiFiles", {
81
81
  enumerable: true,
82
- get: function () { return chunkRXZSVNDG_cjs.discoverWikiFiles; }
82
+ get: function () { return chunkNQTNSHSB_cjs.discoverWikiFiles; }
83
83
  });
84
84
  Object.defineProperty(exports, "indexBudgetWarning", {
85
85
  enumerable: true,
86
- get: function () { return chunkRXZSVNDG_cjs.indexBudgetWarning; }
86
+ get: function () { return chunkNQTNSHSB_cjs.indexBudgetWarning; }
87
87
  });
88
88
  Object.defineProperty(exports, "lanceStoragePath", {
89
89
  enumerable: true,
90
- get: function () { return chunkRXZSVNDG_cjs.lanceStoragePath; }
90
+ get: function () { return chunkNQTNSHSB_cjs.lanceStoragePath; }
91
+ });
92
+ Object.defineProperty(exports, "memoryIndexRoot", {
93
+ enumerable: true,
94
+ get: function () { return chunkNQTNSHSB_cjs.memoryIndexRoot; }
91
95
  });
92
96
  Object.defineProperty(exports, "memoryMdPath", {
93
97
  enumerable: true,
94
- get: function () { return chunkRXZSVNDG_cjs.memoryMdPath; }
98
+ get: function () { return chunkNQTNSHSB_cjs.memoryMdPath; }
95
99
  });
96
100
  Object.defineProperty(exports, "memoryReadRoots", {
97
101
  enumerable: true,
98
- get: function () { return chunkRXZSVNDG_cjs.memoryReadRoots; }
102
+ get: function () { return chunkNQTNSHSB_cjs.memoryReadRoots; }
99
103
  });
100
104
  Object.defineProperty(exports, "notesDir", {
101
105
  enumerable: true,
102
- get: function () { return chunkRXZSVNDG_cjs.notesDir; }
106
+ get: function () { return chunkNQTNSHSB_cjs.notesDir; }
103
107
  });
104
108
  Object.defineProperty(exports, "projectMemoryDir", {
105
109
  enumerable: true,
106
- get: function () { return chunkRXZSVNDG_cjs.projectMemoryDir; }
110
+ get: function () { return chunkNQTNSHSB_cjs.projectMemoryDir; }
107
111
  });
108
112
  Object.defineProperty(exports, "readFacts", {
109
113
  enumerable: true,
110
- get: function () { return chunkRXZSVNDG_cjs.readFacts; }
114
+ get: function () { return chunkNQTNSHSB_cjs.readFacts; }
111
115
  });
112
116
  Object.defineProperty(exports, "readFactsFromMarkdown", {
113
117
  enumerable: true,
114
- get: function () { return chunkRXZSVNDG_cjs.readFactsFromMarkdown; }
118
+ get: function () { return chunkNQTNSHSB_cjs.readFactsFromMarkdown; }
115
119
  });
116
120
  Object.defineProperty(exports, "resolveMemoryRoot", {
117
121
  enumerable: true,
118
- get: function () { return chunkRXZSVNDG_cjs.resolveMemoryRoot; }
122
+ get: function () { return chunkNQTNSHSB_cjs.resolveMemoryRoot; }
119
123
  });
120
124
  Object.defineProperty(exports, "sessionSummaryPath", {
121
125
  enumerable: true,
122
- get: function () { return chunkRXZSVNDG_cjs.sessionSummaryPath; }
126
+ get: function () { return chunkNQTNSHSB_cjs.sessionSummaryPath; }
123
127
  });
124
128
  Object.defineProperty(exports, "sessionsDir", {
125
129
  enumerable: true,
126
- get: function () { return chunkRXZSVNDG_cjs.sessionsDir; }
130
+ get: function () { return chunkNQTNSHSB_cjs.sessionsDir; }
127
131
  });
128
132
  Object.defineProperty(exports, "wikiDir", {
129
133
  enumerable: true,
130
- get: function () { return chunkRXZSVNDG_cjs.wikiDir; }
134
+ get: function () { return chunkNQTNSHSB_cjs.wikiDir; }
131
135
  });
132
136
  Object.defineProperty(exports, "writeSessionSummary", {
133
137
  enumerable: true,
134
- get: function () { return chunkRXZSVNDG_cjs.writeSessionSummary; }
138
+ get: function () { return chunkNQTNSHSB_cjs.writeSessionSummary; }
135
139
  });
136
140
  //# sourceMappingURL=index.cjs.map
137
141
  //# sourceMappingURL=index.cjs.map
@@ -21,7 +21,7 @@ export { collectMarkdownFiles, type DiscoveredFile } from "../index-manager-help
21
21
  export { lanceStoragePath } from "../lance-index.js";
22
22
  export { readAllSqliteFacts, type SqliteFactRow } from "../migrate-sqlite-to-lance.js";
23
23
  export { appendFact, appendFactToMarkdown, memoryMdPath, notesDir, readFacts, readFactsFromMarkdown, } from "./markdown-store.js";
24
- export { asMemoryRoot, claudeProjectMemoryDir, indexBudgetWarning, MEMORY_INDEX_MAX_BYTES, MEMORY_INDEX_MAX_LINES, type MemoryLocationConfig, type MemoryRoot, memoryReadRoots, projectMemoryDir, resolveMemoryRoot, } from "./memory-root.js";
24
+ export { asMemoryRoot, claudeProjectMemoryDir, indexBudgetWarning, MEMORY_INDEX_MAX_BYTES, MEMORY_INDEX_MAX_LINES, type MemoryLocationConfig, type MemoryRoot, memoryIndexRoot, memoryReadRoots, projectMemoryDir, resolveMemoryRoot, } from "./memory-root.js";
25
25
  export { discoverSessionFiles, type SessionFile } from "./session-loader.js";
26
26
  export { type SessionSummaryInput, sessionSummaryPath, sessionsDir, writeSessionSummary, } from "./session-summary-writer.js";
27
27
  export { type ActiveMemoryTranscript, persistActiveMemoryTranscript } from "./transcript-store.js";
@@ -21,7 +21,7 @@ export { collectMarkdownFiles, type DiscoveredFile } from "../index-manager-help
21
21
  export { lanceStoragePath } from "../lance-index.js";
22
22
  export { readAllSqliteFacts, type SqliteFactRow } from "../migrate-sqlite-to-lance.js";
23
23
  export { appendFact, appendFactToMarkdown, memoryMdPath, notesDir, readFacts, readFactsFromMarkdown, } from "./markdown-store.js";
24
- export { asMemoryRoot, claudeProjectMemoryDir, indexBudgetWarning, MEMORY_INDEX_MAX_BYTES, MEMORY_INDEX_MAX_LINES, type MemoryLocationConfig, type MemoryRoot, memoryReadRoots, projectMemoryDir, resolveMemoryRoot, } from "./memory-root.js";
24
+ export { asMemoryRoot, claudeProjectMemoryDir, indexBudgetWarning, MEMORY_INDEX_MAX_BYTES, MEMORY_INDEX_MAX_LINES, type MemoryLocationConfig, type MemoryRoot, memoryIndexRoot, memoryReadRoots, projectMemoryDir, resolveMemoryRoot, } from "./memory-root.js";
25
25
  export { discoverSessionFiles, type SessionFile } from "./session-loader.js";
26
26
  export { type SessionSummaryInput, sessionSummaryPath, sessionsDir, writeSessionSummary, } from "./session-summary-writer.js";
27
27
  export { type ActiveMemoryTranscript, persistActiveMemoryTranscript } from "./transcript-store.js";
@@ -1,6 +1,6 @@
1
- export { appendDiaryEntry, diaryPath, entryHash, readAllSqliteFacts, renderDiaryEntry } from '../../../chunk-DX4RUWOK.js';
1
+ export { appendDiaryEntry, diaryPath, entryHash, readAllSqliteFacts, renderDiaryEntry } from '../../../chunk-WS5ULCL4.js';
2
2
  export { persistActiveMemoryTranscript } from '../../../chunk-OR6XIWLB.js';
3
- export { MEMORY_INDEX_MAX_BYTES, MEMORY_INDEX_MAX_LINES, appendFact, appendFactToMarkdown, asMemoryRoot, claudeProjectMemoryDir, collectMarkdownFiles, defaultIndexPath, discoverSessionFiles, discoverWikiFiles, indexBudgetWarning, lanceStoragePath, memoryMdPath, memoryReadRoots, notesDir, projectMemoryDir, readFacts, readFactsFromMarkdown, resolveMemoryRoot, sessionSummaryPath, sessionsDir, wikiDir, writeSessionSummary } from '../../../chunk-J2SH3PNH.js';
3
+ export { MEMORY_INDEX_MAX_BYTES, MEMORY_INDEX_MAX_LINES, appendFact, appendFactToMarkdown, asMemoryRoot, claudeProjectMemoryDir, collectMarkdownFiles, defaultIndexPath, discoverSessionFiles, discoverWikiFiles, indexBudgetWarning, lanceStoragePath, memoryIndexRoot, memoryMdPath, memoryReadRoots, notesDir, projectMemoryDir, readFacts, readFactsFromMarkdown, resolveMemoryRoot, sessionSummaryPath, sessionsDir, wikiDir, writeSessionSummary } from '../../../chunk-SADXXGWU.js';
4
4
  import '../../../chunk-KVNWIAO4.js';
5
5
  import '../../../chunk-FD2UT76F.js';
6
6
  import '../../../chunk-2XRAWOZZ.js';
@@ -92,6 +92,23 @@ export declare const MEMORY_INDEX_MAX_BYTES: number;
92
92
  * function is testable without a filesystem or a captured stderr.
93
93
  */
94
94
  export declare function indexBudgetWarning(index: string, root: string): string | undefined;
95
+ /**
96
+ * Where the search index belongs for this configuration (theokit-sdk#554).
97
+ *
98
+ * Not always the same root the FACTS use, and the divergence is narrow on purpose.
99
+ *
100
+ * The index is not a pointer — `chunks.text` holds the fact text, because FTS5/BM25 needs it to
101
+ * search. A copy of the index is therefore a copy of the memory. Leaving it in `<cwd>` while the
102
+ * facts move writes one operator's personal store into every repository the agent runs in,
103
+ * untracked and readable with `strings`.
104
+ *
105
+ * So the index follows the store — EXCEPT into the Claude Code CLI's own directory, which is the
106
+ * case `docs/memory-decisions.md` § 1 reasons about and settles: that CLI has no index format, so
107
+ * a binary there is an artefact the partner does not understand inside a directory it manages. The
108
+ * decision keeps exactly the scope its own argument covers, and no more; every other directory is
109
+ * a plain directory this SDK is free to own.
110
+ */
111
+ export declare function memoryIndexRoot(cwd: string, store: MemoryRoot): MemoryRoot;
95
112
  /**
96
113
  * Every directory a read must cover, deduplicated and in precedence order.
97
114
  *
@@ -92,6 +92,23 @@ export declare const MEMORY_INDEX_MAX_BYTES: number;
92
92
  * function is testable without a filesystem or a captured stderr.
93
93
  */
94
94
  export declare function indexBudgetWarning(index: string, root: string): string | undefined;
95
+ /**
96
+ * Where the search index belongs for this configuration (theokit-sdk#554).
97
+ *
98
+ * Not always the same root the FACTS use, and the divergence is narrow on purpose.
99
+ *
100
+ * The index is not a pointer — `chunks.text` holds the fact text, because FTS5/BM25 needs it to
101
+ * search. A copy of the index is therefore a copy of the memory. Leaving it in `<cwd>` while the
102
+ * facts move writes one operator's personal store into every repository the agent runs in,
103
+ * untracked and readable with `strings`.
104
+ *
105
+ * So the index follows the store — EXCEPT into the Claude Code CLI's own directory, which is the
106
+ * case `docs/memory-decisions.md` § 1 reasons about and settles: that CLI has no index format, so
107
+ * a binary there is an artefact the partner does not understand inside a directory it manages. The
108
+ * decision keeps exactly the scope its own argument covers, and no more; every other directory is
109
+ * a plain directory this SDK is free to own.
110
+ */
111
+ export declare function memoryIndexRoot(cwd: string, store: MemoryRoot): MemoryRoot;
95
112
  /**
96
113
  * Every directory a read must cover, deduplicated and in precedence order.
97
114
  *
@@ -4,7 +4,7 @@ Every public symbol the TheoKit workspace publishes, and the exact specifier to
4
4
 
5
5
  A symbol listed under two specifiers is reachable from both, but that does NOT make the two interchangeable: a class emitted separately into a subpath entry is a distinct nominal type from the one in the root bundle, so passing one where the other is expected fails on a private field. When a symbol appears twice, import it and everything it is passed to from the SAME specifier.
6
6
 
7
- 1189 export(s) across 46 entry point(s).
7
+ 1193 export(s) across 46 entry point(s).
8
8
 
9
9
  ## `@theokit/acp`
10
10
 
@@ -291,6 +291,8 @@ A symbol listed under two specifiers is reachable from both, but that does NOT m
291
291
  | `ProviderTransform` | interface | M41 — the one OPTIONAL behavior seam on a provider profile. |
292
292
  | `ProviderTransformContext` | interface | M41 (agent-builder provider framework) — the context a provider's `transform` receives per request. |
293
293
  | `RateLimitError` | class | Too many requests or usage limits exceeded. |
294
+ | `readSessionMessages` | function | Read the messages a session already contains, for a surface that needs to re-render it. |
295
+ | `ReadSessionMessagesOptions` | interface | Which session to read, in the terms a host already has. |
294
296
  | `ReapableArtifact` | interface | One artifact the caller is considering deleting, described well enough to decide about. |
295
297
  | `ReapPlan` | interface | The decision, as three disjoint buckets whose union is exactly the input. |
296
298
  | `ReapPlanInput` | interface | Everything `planReaping` needs: the candidates, the policy, and the current time. |
@@ -621,6 +623,7 @@ A symbol listed under two specifiers is reachable from both, but that does NOT m
621
623
  | `MemoryFileEntry` | interface | Lightweight reference to a markdown file in the memory corpus. |
622
624
  | `MemoryGetToolOptions` | interface | Options for {@link createMemoryGetTool } . |
623
625
  | `MemoryIndex` | interface | The four operations both backends implement, and the type every consumer should hold. |
626
+ | `memoryIndexRoot` | function | Where the search index belongs for this configuration (theokit-sdk#554). |
624
627
  | `MemoryLocationConfig` | type | Only `directory` is read; the full config is accepted so callers pass what they already hold. |
625
628
  | `memoryMdPath` | function | Path to `MEMORY.md`, the index that points at the per-memory files — and, in stores written before #389, the flat `## Facts` list itself. |
626
629
  | `MemoryReadResult` | interface | Result of `reader.readFile`. |
@@ -1049,6 +1052,7 @@ A symbol listed under two specifiers is reachable from both, but that does NOT m
1049
1052
  | `lanceStoragePath` | function | `<memory root>/lance`. |
1050
1053
  | `MEMORY_INDEX_MAX_BYTES` | const | The byte limit the Claude Code CLI applies when it loads a `MEMORY.md`, whichever it reaches first. |
1051
1054
  | `MEMORY_INDEX_MAX_LINES` | const | The line limit the Claude Code CLI applies when it loads a `MEMORY.md`. |
1055
+ | `memoryIndexRoot` | function | Where the search index belongs for this configuration (theokit-sdk#554). |
1052
1056
  | `MemoryLocationConfig` | type | Only `directory` is read; the full config is accepted so callers pass what they already hold. |
1053
1057
  | `memoryMdPath` | function | Path to `MEMORY.md`, the index that points at the per-memory files — and, in stores written before #389, the flat `## Facts` list itself. |
1054
1058
  | `memoryReadRoots` | function | Every directory a read must cover, deduplicated and in precedence order. |
@@ -18,7 +18,7 @@ decision the next refactor deletes.
18
18
  .theokit/memory/.index/memory.sqlite on the first send, when memory is enabled
19
19
  ```
20
20
 
21
- **Why it looks wrong.** With `memory.directory` pointed at the CLI's store, memory *facts* are
21
+ **Why it looks wrong.** With `memory.directory` pointed at the CLI's store, memory _facts_ are
22
22
  written to `<claudeHome>/projects/<encoded-cwd>/memory/` — where the CLI reads them. So a project
23
23
  that never adopted this SDK ends up with a `.theokit/` directory anyway, which reads like the
24
24
  "write where the CLI reads" promise leaking.
@@ -36,10 +36,31 @@ Claude Code shape to be written in:
36
36
  The facts — the thing a user recorded and would lose — go where the CLI reads. The index is derived
37
37
  data that can be rebuilt from them.
38
38
 
39
+ **Scope, narrowed 2026-09-04 (theokit-sdk#554).** This argument reaches the CLI's directory and no
40
+ other. For any other `memory.directory`, the index now follows the store —
41
+ `<directory>/.index/memory.sqlite` — and the reason the old behaviour was wrong is worth keeping:
42
+
43
+ > The index is **not** a pointer. `chunks.text` holds the fact TEXT, because FTS5/BM25 needs it to
44
+ > search, and `files.path` holds the store's absolute path. So a copy of the index is a copy of the
45
+ > memory, readable with `strings`.
46
+
47
+ Leaving it in `<cwd>` while the facts moved therefore wrote one operator's personal store into
48
+ **every repository the agent ran in**, untracked and un-ignored. "Derived data" was true of its
49
+ _derivability_ and false of its _contents_, and the sentence above was doing the work of both.
50
+
51
+ The CLI case survives unchanged, on its own argument: that partner has no index format, so a binary
52
+ there is an artefact it does not understand inside a directory it manages. `memoryIndexRoot`
53
+ (`internal/memory/storage/memory-root.ts`) is the single place that decides, using the same
54
+ path-only test `indexBudgetWarning` relies on.
55
+
56
+ **How to check the narrowed scope still holds:** `tests/memory/index-follows-a-relocated-store.test.ts`
57
+ pins both halves — a plain directory takes its own index, the CLI's does not — and
58
+ `tests/memory/root.test.ts` carries the end-to-end pair through `IndexManager.open`.
59
+
39
60
  **How to check it still holds:** `tests/claude-code-e2e-compat.test.ts`, the pair
40
61
  `test_reading_a_cli_project_creates_nothing_in_it` /
41
62
  `test_running_an_agent_creates_theokit_and_only_sdk_state_in_it`. The second exists so the first is
42
- not vacuous — it asserts the directory contains *only* `agents` and `memory`.
63
+ not vacuous — it asserts the directory contains _only_ `agents` and `memory`.
43
64
 
44
65
  ---
45
66
 
@@ -53,7 +74,7 @@ three retention buckets (atomic / consolidatable / lifecycle-managed). This SDK
53
74
 
54
75
  **Why it has not been widened.** The nine exist to drive differentiated retention, and **this SDK has
55
76
  no retention at all** — no TTL, no pruning, no decay (searched `ttl|prune|expire|retention` across
56
- both packages; the only hits are the recall result cache, which expires *results*, not entries).
77
+ both packages; the only hits are the recall result cache, which expires _results_, not entries).
57
78
  Nine names over a regime where nothing expires are nine names for one behaviour. Retention has to
58
79
  exist before a vocabulary that differentiates it is worth anything.
59
80
 
@@ -76,7 +97,7 @@ emitted. That is evidence about what it WRITES, not proof about what it ACCEPTS
76
97
  means there is no precedent, and the burden belongs to whoever adds one unilaterally.
77
98
 
78
99
  **`failure_heuristic` is the one the retention argument does not cover, and the interop argument
79
- does.** It changes *what is written* (a trigger→resolution pair) rather than how an entry expires, so
100
+ does.** It changes _what is written_ (a trigger→resolution pair) rather than how an entry expires, so
80
101
  "no retention to differentiate" says nothing about it — and nothing has adopted it (`grep
81
102
  failure_heuristic packages/sdk/src` → zero). It is not declined on retention grounds; it is held by
82
103
  the same shared-format question as the other four, and unblocking it means establishing what the CLI
@@ -112,7 +133,7 @@ text: the same text keeps the same file and increments corroboration, different
112
133
  `topic-2`. Found by the golden `multiple appends each get a file`, not by review — the failure was
113
134
  silent data loss, and nothing about the reasoning would have surfaced it.
114
135
 
115
- So the section heading stays true for what it describes, re-recording the *same* fact, and the case
136
+ So the section heading stays true for what it describes, re-recording the _same_ fact, and the case
116
137
  it never covered is now covered.
117
138
 
118
139
  That change closed #446, where a passphrase the model had just refused to store was written into the
@@ -161,11 +182,11 @@ So no dense vector participates in scoring under a default configuration. One do
161
182
  consumer names an embedding provider.
162
183
 
163
184
  **Known divergence,** on the opt-in path: the external contract forbids dense vectors in agent-memory
164
- recall below a measured threshold (>1000 entries *and* demonstrated lexical degradation). Neither has
185
+ recall below a measured threshold (>1000 entries _and_ demonstrated lexical degradation). Neither has
165
186
  been measured here.
166
187
 
167
188
  **The bigger gap WAS the default path, and it was not this divergence.** A contract arbitrating
168
- *between* retrieval methods does not cover the absence of one — and until `721a311f` there was no
189
+ _between_ retrieval methods does not cover the absence of one — and until `721a311f` there was no
169
190
  method on this path at all. That is fixed; the history is kept because the failure mode is worth
170
191
  recognising again, and because it explains why the ranking signal has to depend on the question. A
171
192
  first version cut by recency alone, and a live run showed the answering fact dropped for being old
@@ -197,7 +218,7 @@ where this agent's memory lives. Everything under the root follows it: `MEMORY.m
197
218
  files, `notes/`, `sessions/`, `wiki/`, `transcripts/`, `dream-diary.md` and `.index/memory.sqlite`.
198
219
 
199
220
  **What it replaced.** The location used to be a side effect of `local.sessionDir`, the option that
200
- names the *transcript* home, on the reasoning that a consumer who set it had already opted into CLI
221
+ names the _transcript_ home, on the reasoning that a consumer who set it had already opted into CLI
201
222
  interop. One option answered two questions — and of the fourteen places that computed a memory
202
223
  path, exactly one heard the second answer. `appendFact` relocated; the indexer, the `memory_get`
203
224
  path guard, `MEMORY.md`, `sessions/` and the index database did not. A relocated fact was written,
@@ -230,15 +251,15 @@ that were broken.
230
251
 
231
252
  Each row says what would close it, not only that it is open — the two invite very different work.
232
253
 
233
- | gap | where | what would close it |
234
- |---|---|---|
235
- | ~~The default recall path has no selection at all~~ — **closed** in `721a311f` | `local-agent-send.ts:257-272` | Closed: lexical relevance + recency, capped. Measured end to end against the real model — a 67-entry store went from ~66K to **13,606 tokens on the wire**, and the answering fact is recalled whether it is the oldest or the newest entry. |
236
- | The CLI's store is read whether or not the consumer opted in | `storage/memory-root.ts` — `claudeProjectMemoryDir(cwd)` is an unconditional entry in `memoryReadRoots` | A decision, not a fix: it is deliberate (*write one, read all*, so a consumer's existing memories are never orphaned) and it means a consumer who never opted into CLI interop still receives what the CLI accumulated in that project. Cheap while the cap holds; revisit if the cap is ever removed. |
237
- | No retention of any kind — no TTL, prune, or decay | searched `ttl\|prune\|expire\|retention` across both packages: zero | A per-kind TTL plus a prune step in the sweep. Needs the kind vocabulary to mean something first (§ 2), which is why this orders before widening it. |
238
- | Quarantine marks but does not constrain | `memory-file.ts:96`, `memory-provider.ts:48` | Implemented: three states, and `[unconfirmed]` on entries the store counted once. **Measured against the real model and it does not close the hole** — a planted memory alone is acted on 5/5, and beside a corroborated contradiction it is still asserted ~62% of runs (n=32). Marking influences the model; it does not constrain it. The guarantee is not available at this layer: blocking an uncorroborated entry would break the promise that a fact written once is recallable next session. |
239
- | A planted memory can make the agent ACT | measured: `RELEASE_OVERRIDE.txt` created in 2 of 6 runs | Register the permission layer — `PermissionPlugin.create(new PermissionEngine(…))` — which blocks it every time. This is the half that IS closable at the tool boundary; the informational half above is not. Any deployment where the memory directory is writable by anything other than this agent needs it. |
240
- | `description` is written as a copy of the body | `markdown-store.ts:205-211` — the *reader* (`:174-177`) already handles a distinct description correctly | Stop writing one when nobody declared it. The role is a one-line recall aid; deriving it mechanically would be inferring the situation, which § 2's rule already forbids for `kind`. Absent is a valid state and the reader already falls back to the body. |
241
- | The topic-name deriver filters English function words only | `memory-file.ts:73` | A store in another language keeps that language's function words in the slug and the index title — `de`, `do`, `para` survive, so the name is longer and noisier. **Never lossy:** collisions are caught by `resolveName` comparing text, not by the stopword list. Real stores here are bilingual, so this is a partial parity, not a complete one. Closes with a per-language list, or by not needing one. |
242
- | The dream sweep never filters by kind before dedup | `dreaming/phases.ts:34` — `lightPhase` never reads `kind` | Partition by kind before `lightPhase`. Nothing is deleted today, but a consolidated note can blend two distinct entries, and the note is what search returns. |
243
- | The dream sweep does not update the index | `dreaming/run.ts:53-96` writes `notes/` and never syncs | An `IndexManager.sync` after `writeConsolidatedNotes`. |
244
- | Recall fires every turn, cached on query hash, not on store manifest | `internal/local-agent/local-agent-memory.ts:87`; `sdk-memory/internal/active-memory/active-memory-cache.ts:66` | A second skip condition beside the existing one — hash of the store manifest, so an unchanged store skips even when the question changes. The query cache is not wrong; it answers a different question. |
254
+ | gap | where | what would close it |
255
+ | ------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
256
+ | ~~The default recall path has no selection at all~~ — **closed** in `721a311f` | `local-agent-send.ts:257-272` | Closed: lexical relevance + recency, capped. Measured end to end against the real model — a 67-entry store went from ~66K to **13,606 tokens on the wire**, and the answering fact is recalled whether it is the oldest or the newest entry. |
257
+ | The CLI's store is read whether or not the consumer opted in | `storage/memory-root.ts` — `claudeProjectMemoryDir(cwd)` is an unconditional entry in `memoryReadRoots` | A decision, not a fix: it is deliberate (_write one, read all_, so a consumer's existing memories are never orphaned) and it means a consumer who never opted into CLI interop still receives what the CLI accumulated in that project. Cheap while the cap holds; revisit if the cap is ever removed. |
258
+ | No retention of any kind — no TTL, prune, or decay | searched `ttl\|prune\|expire\|retention` across both packages: zero | A per-kind TTL plus a prune step in the sweep. Needs the kind vocabulary to mean something first (§ 2), which is why this orders before widening it. |
259
+ | Quarantine marks but does not constrain | `memory-file.ts:96`, `memory-provider.ts:48` | Implemented: three states, and `[unconfirmed]` on entries the store counted once. **Measured against the real model and it does not close the hole** — a planted memory alone is acted on 5/5, and beside a corroborated contradiction it is still asserted ~62% of runs (n=32). Marking influences the model; it does not constrain it. The guarantee is not available at this layer: blocking an uncorroborated entry would break the promise that a fact written once is recallable next session. |
260
+ | A planted memory can make the agent ACT | measured: `RELEASE_OVERRIDE.txt` created in 2 of 6 runs | Register the permission layer — `PermissionPlugin.create(new PermissionEngine(…))` — which blocks it every time. This is the half that IS closable at the tool boundary; the informational half above is not. Any deployment where the memory directory is writable by anything other than this agent needs it. |
261
+ | `description` is written as a copy of the body | `markdown-store.ts:205-211` — the _reader_ (`:174-177`) already handles a distinct description correctly | Stop writing one when nobody declared it. The role is a one-line recall aid; deriving it mechanically would be inferring the situation, which § 2's rule already forbids for `kind`. Absent is a valid state and the reader already falls back to the body. |
262
+ | The topic-name deriver filters English function words only | `memory-file.ts:73` | A store in another language keeps that language's function words in the slug and the index title — `de`, `do`, `para` survive, so the name is longer and noisier. **Never lossy:** collisions are caught by `resolveName` comparing text, not by the stopword list. Real stores here are bilingual, so this is a partial parity, not a complete one. Closes with a per-language list, or by not needing one. |
263
+ | The dream sweep never filters by kind before dedup | `dreaming/phases.ts:34` — `lightPhase` never reads `kind` | Partition by kind before `lightPhase`. Nothing is deleted today, but a consolidated note can blend two distinct entries, and the note is what search returns. |
264
+ | The dream sweep does not update the index | `dreaming/run.ts:53-96` writes `notes/` and never syncs | An `IndexManager.sync` after `writeConsolidatedNotes`. |
265
+ | Recall fires every turn, cached on query hash, not on store manifest | `internal/local-agent/local-agent-memory.ts:87`; `sdk-memory/internal/active-memory/active-memory-cache.ts:66` | A second skip condition beside the existing one — hash of the store manifest, so an unchanged store skips even when the question changes. The query cache is not wrong; it answers a different question. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theokit/sdk",
3
- "version": "5.0.0-next.3",
3
+ "version": "5.0.0",
4
4
  "description": "TypeScript SDK for the Theo agent harness — same surface, local or cloud.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/usetheokit/theokit-sdk#readme",
@@ -440,7 +440,7 @@
440
440
  "sqlite-vec": "^0.1.9",
441
441
  "typedoc": "^0.28.19",
442
442
  "ws": "^8.18.0",
443
- "@theokit/sdk-budget": "0.3.5-next.1"
443
+ "@theokit/sdk-budget": "0.3.5"
444
444
  },
445
445
  "scripts": {
446
446
  "build": "tsup && cp src/internal/providers/provider-catalog.json dist/provider-catalog.json && node ../../tools/repair-dts-imports.mjs .",
@@ -1 +0,0 @@
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"],"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,MAAA,EAAU;AACpF,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GA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AA,GAAc;AACZ,IAAA,IAAA,CAAK,KAAK,KAAA,EAAM;AAAA,EAClB;AACF","file":"chunk-CYKKYNOT.js","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, projectMemoryDir, 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 on\n // purpose. The corpus is the configured root; the database stays in the project store, because\n // `memory.directory` may name the directory the Claude Code CLI manages and that CLI has no\n // index format (`docs/memory-decisions.md` § 1). Collapsing them writes a binary the partner\n // does not understand into a directory it owns.\n const filePath = opts.filePath ?? defaultIndexPath(projectMemoryDir(opts.cwd));\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"]}