@orquentra/codebuddy 2.6.0 → 2.7.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 (117) hide show
  1. package/CLAUDE_CODEX.md +6 -4
  2. package/WORKFLOW.md +5 -5
  3. package/dist/{chunk-U4HAJLIB.js → chunk-3QGW53GD.js} +16 -3
  4. package/dist/chunk-3QGW53GD.js.map +1 -0
  5. package/dist/{chunk-L5AYZC3F.js → chunk-5EDGAZQN.js} +438 -68
  6. package/dist/chunk-5EDGAZQN.js.map +1 -0
  7. package/dist/chunk-5UH3BEQR.js +32 -0
  8. package/dist/chunk-5UH3BEQR.js.map +1 -0
  9. package/dist/{chunk-JFDRBPYF.js → chunk-6JCKMIQY.js} +2 -2
  10. package/dist/{chunk-UN57FKQX.js → chunk-AK2UAE32.js} +152 -862
  11. package/dist/chunk-AK2UAE32.js.map +1 -0
  12. package/dist/{chunk-GDJH7XJC.js → chunk-AL6VBTNA.js} +77 -3
  13. package/dist/chunk-AL6VBTNA.js.map +1 -0
  14. package/dist/{chunk-WHZSVY2L.js → chunk-AQHPEJR6.js} +94 -23
  15. package/dist/chunk-AQHPEJR6.js.map +1 -0
  16. package/dist/{chunk-PCE4STAY.js → chunk-BQM7FJ7D.js} +6 -6
  17. package/dist/chunk-BQM7FJ7D.js.map +1 -0
  18. package/dist/{chunk-XBJQKCLU.js → chunk-CAEPHLHC.js} +13 -9
  19. package/dist/chunk-CAEPHLHC.js.map +1 -0
  20. package/dist/chunk-CG5B3LYG.js +66 -0
  21. package/dist/chunk-CG5B3LYG.js.map +1 -0
  22. package/dist/chunk-CSRD5OQA.js +79 -0
  23. package/dist/chunk-CSRD5OQA.js.map +1 -0
  24. package/dist/{chunk-IHQM2ZDV.js → chunk-DFV2SK6C.js} +1 -1
  25. package/dist/{chunk-IHQM2ZDV.js.map → chunk-DFV2SK6C.js.map} +1 -1
  26. package/dist/chunk-EEUFU7KV.js +1634 -0
  27. package/dist/chunk-EEUFU7KV.js.map +1 -0
  28. package/dist/{chunk-UFZD3JAA.js → chunk-ESZXCZIN.js} +3 -3
  29. package/dist/{chunk-PYLH4MH5.js → chunk-FJOTP632.js} +1 -1
  30. package/dist/{chunk-SYWJG5NA.js → chunk-GKNYMNFM.js} +17 -7
  31. package/dist/{chunk-SYWJG5NA.js.map → chunk-GKNYMNFM.js.map} +1 -1
  32. package/dist/{chunk-JPHJBCZB.js → chunk-HPOR6YXA.js} +3 -2
  33. package/dist/chunk-HPOR6YXA.js.map +1 -0
  34. package/dist/chunk-JUAFCLRB.js +1014 -0
  35. package/dist/chunk-JUAFCLRB.js.map +1 -0
  36. package/dist/{chunk-776EQXDV.js → chunk-KNR2P2UY.js} +110 -83
  37. package/dist/chunk-KNR2P2UY.js.map +1 -0
  38. package/dist/{chunk-N34XHWBA.js → chunk-LCSBL5TT.js} +24 -11
  39. package/dist/chunk-LCSBL5TT.js.map +1 -0
  40. package/dist/{chunk-QDBDYCM2.js → chunk-MSUAVR3R.js} +76 -11
  41. package/dist/chunk-MSUAVR3R.js.map +1 -0
  42. package/dist/{chunk-6MKEIDX5.js → chunk-SFMIMLXR.js} +2 -2
  43. package/dist/chunk-TGFTKWOR.js +16 -0
  44. package/dist/chunk-TGFTKWOR.js.map +1 -0
  45. package/dist/chunk-TUR6YKEE.js +55 -0
  46. package/dist/chunk-TUR6YKEE.js.map +1 -0
  47. package/dist/chunk-Y7D7PUBE.js +321 -0
  48. package/dist/chunk-Y7D7PUBE.js.map +1 -0
  49. package/dist/{chunk-VAKBJV26.js → chunk-YJIA2MFL.js} +918 -2238
  50. package/dist/chunk-YJIA2MFL.js.map +1 -0
  51. package/dist/cli/index.js +14 -3
  52. package/dist/cli/index.js.map +1 -1
  53. package/dist/{cloud-7WM3YLI4.js → cloud-LXZUR3U2.js} +3 -3
  54. package/dist/{codebuddy-DM-i0Fu5.d.ts → codebuddy-DO7ZhoWn.d.ts} +37 -3
  55. package/dist/config-GEZFLXK6.js +12 -0
  56. package/dist/docker-autostart-KDME7TVC.js +12 -0
  57. package/dist/index.d.ts +48 -3
  58. package/dist/index.js +32 -25
  59. package/dist/langgraph/index.d.ts +1 -1
  60. package/dist/lean-command-CWJAVQ5G.js +18 -0
  61. package/dist/local-ST4WMRCG.js +17 -0
  62. package/dist/{main-HFHLGID4.js → main-AHNGHC4L.js} +327 -329
  63. package/dist/main-AHNGHC4L.js.map +1 -0
  64. package/dist/{memory-4RGVLPKG.js → memory-TGHVTBME.js} +9 -8
  65. package/dist/memory-TGHVTBME.js.map +1 -0
  66. package/dist/operations-7BTAAUHF.js +26 -0
  67. package/dist/postgres-docker-QQZQ2ABK.js +16 -0
  68. package/dist/pretool-command-3SXQSMAO.js +13 -0
  69. package/dist/{rerank-3P3C2UHN.js → rerank-IQAEWLQR.js} +6 -5
  70. package/dist/rerank-IQAEWLQR.js.map +1 -0
  71. package/dist/runtime-E7JQZ2BZ.js +46 -0
  72. package/dist/runtime-E7JQZ2BZ.js.map +1 -0
  73. package/dist/stdio-HOV4P3DQ.js +12 -0
  74. package/dist/stdio-HOV4P3DQ.js.map +1 -0
  75. package/dist/summaries-XV3JGGCC.js +20 -0
  76. package/dist/summaries-XV3JGGCC.js.map +1 -0
  77. package/dist/{zvec-MAPSJQSR.js → zvec-KP4KNB7Y.js} +10 -3
  78. package/dist/zvec-KP4KNB7Y.js.map +1 -0
  79. package/package.json +7 -10
  80. package/src/db/migrations/0006_fact_idempotency_key.sql +2 -0
  81. package/src/db/migrations/meta/0006_snapshot.json +1258 -0
  82. package/src/db/migrations/meta/_journal.json +7 -0
  83. package/dist/chunk-776EQXDV.js.map +0 -1
  84. package/dist/chunk-GDJH7XJC.js.map +0 -1
  85. package/dist/chunk-JPHJBCZB.js.map +0 -1
  86. package/dist/chunk-L5AYZC3F.js.map +0 -1
  87. package/dist/chunk-N34XHWBA.js.map +0 -1
  88. package/dist/chunk-PCE4STAY.js.map +0 -1
  89. package/dist/chunk-PQK3GKZH.js +0 -98
  90. package/dist/chunk-PQK3GKZH.js.map +0 -1
  91. package/dist/chunk-QDBDYCM2.js.map +0 -1
  92. package/dist/chunk-U4HAJLIB.js.map +0 -1
  93. package/dist/chunk-UN57FKQX.js.map +0 -1
  94. package/dist/chunk-VAKBJV26.js.map +0 -1
  95. package/dist/chunk-WHZSVY2L.js.map +0 -1
  96. package/dist/chunk-XBJQKCLU.js.map +0 -1
  97. package/dist/config-KFEHLV6W.js +0 -11
  98. package/dist/lean-command-C5YPFKHP.js +0 -15
  99. package/dist/local-OTOY56B4.js +0 -13
  100. package/dist/main-HFHLGID4.js.map +0 -1
  101. package/dist/memory-4RGVLPKG.js.map +0 -1
  102. package/dist/operations-LOBAQRLO.js +0 -24
  103. package/dist/pretool-command-MQQ2UNQM.js +0 -10
  104. package/dist/rerank-3P3C2UHN.js.map +0 -1
  105. package/dist/summaries-ZBV5IN7Y.js +0 -18
  106. /package/dist/{chunk-JFDRBPYF.js.map → chunk-6JCKMIQY.js.map} +0 -0
  107. /package/dist/{chunk-UFZD3JAA.js.map → chunk-ESZXCZIN.js.map} +0 -0
  108. /package/dist/{chunk-PYLH4MH5.js.map → chunk-FJOTP632.js.map} +0 -0
  109. /package/dist/{chunk-6MKEIDX5.js.map → chunk-SFMIMLXR.js.map} +0 -0
  110. /package/dist/{cloud-7WM3YLI4.js.map → cloud-LXZUR3U2.js.map} +0 -0
  111. /package/dist/{config-KFEHLV6W.js.map → config-GEZFLXK6.js.map} +0 -0
  112. /package/dist/{lean-command-C5YPFKHP.js.map → docker-autostart-KDME7TVC.js.map} +0 -0
  113. /package/dist/{local-OTOY56B4.js.map → lean-command-CWJAVQ5G.js.map} +0 -0
  114. /package/dist/{operations-LOBAQRLO.js.map → local-ST4WMRCG.js.map} +0 -0
  115. /package/dist/{pretool-command-MQQ2UNQM.js.map → operations-7BTAAUHF.js.map} +0 -0
  116. /package/dist/{summaries-ZBV5IN7Y.js.map → postgres-docker-QQZQ2ABK.js.map} +0 -0
  117. /package/dist/{zvec-MAPSJQSR.js.map → pretool-command-3SXQSMAO.js.map} +0 -0
@@ -0,0 +1,1014 @@
1
+ import {
2
+ redactPersisted
3
+ } from "./chunk-AL6VBTNA.js";
4
+ import {
5
+ assertNoSymlinkBetween,
6
+ composeMarkdown,
7
+ parseFrontMatter,
8
+ writeAtomic
9
+ } from "./chunk-CG5B3LYG.js";
10
+ import {
11
+ __export
12
+ } from "./chunk-PZ5AY32C.js";
13
+
14
+ // package.json
15
+ var package_default = {
16
+ name: "@orquentra/codebuddy",
17
+ version: "2.7.0",
18
+ description: "Local-first project context and memory for AI coding agents.",
19
+ type: "module",
20
+ license: "MIT",
21
+ publishConfig: {
22
+ access: "public"
23
+ },
24
+ author: "Orquentra Inc",
25
+ repository: {
26
+ type: "git",
27
+ url: "https://github.com/Orquentra-Inc/CodeBuddy"
28
+ },
29
+ engines: {
30
+ node: ">=20"
31
+ },
32
+ bin: {
33
+ codebuddy: "./dist/cli/index.js"
34
+ },
35
+ exports: {
36
+ ".": {
37
+ types: "./dist/index.d.ts",
38
+ import: "./dist/index.js"
39
+ },
40
+ "./langgraph": {
41
+ types: "./dist/langgraph/index.d.ts",
42
+ import: "./dist/langgraph/index.js"
43
+ }
44
+ },
45
+ files: [
46
+ "dist",
47
+ "src/db/migrations",
48
+ "README.md",
49
+ "CLAUDE_CODEX.md",
50
+ "ARCHITECTURE.md",
51
+ "WORKFLOW.md",
52
+ "LICENSE",
53
+ "docker-compose.yml",
54
+ "examples"
55
+ ],
56
+ scripts: {
57
+ build: "tsup",
58
+ dev: "tsx src/cli/index.ts",
59
+ "db:generate": "drizzle-kit generate",
60
+ "db:migrate": "drizzle-kit migrate",
61
+ typecheck: "tsc --noEmit",
62
+ test: "vitest run --passWithNoTests",
63
+ "test:pg": "bash scripts/test-pg-recovery.sh",
64
+ "eval:agent-ab": "tsx scripts/eval-agent-ab.mts",
65
+ "eval:memory-ab": "tsx scripts/eval-memory-ab.mts",
66
+ "eval:retrieval": "tsx scripts/eval-retrieval.mts",
67
+ "eval:savings": "tsx scripts/eval-task-savings.mts",
68
+ "branches:prune": "bash scripts/prune-merged-branches.sh",
69
+ lint: "biome check .",
70
+ format: "biome format --write .",
71
+ prepublishOnly: "node scripts/check-release.mjs && npm run typecheck && npm test && npm run build",
72
+ "eval:semantic": "tsx scripts/eval-semantic.mts"
73
+ },
74
+ keywords: [
75
+ "mcp",
76
+ "memory",
77
+ "agent",
78
+ "multi-agent",
79
+ "huggingface",
80
+ "pgvector",
81
+ "postgres",
82
+ "langgraph",
83
+ "claude"
84
+ ],
85
+ homepage: "https://github.com/Orquentra-Inc/CodeBuddy",
86
+ bugs: {
87
+ url: "https://github.com/Orquentra-Inc/CodeBuddy/issues"
88
+ },
89
+ dependencies: {
90
+ "@clack/prompts": "^1.8.1",
91
+ "@huggingface/inference": "^4.13.19",
92
+ "@modelcontextprotocol/sdk": "^1.17.5",
93
+ commander: "^14.0.0",
94
+ "drizzle-orm": "^0.45.2",
95
+ "js-tiktoken": "^1.0.21",
96
+ "p-queue": "^10.0.0",
97
+ "p-retry": "^8.0.1",
98
+ "p-timeout": "^8.1.0",
99
+ picocolors: "^1.1.1",
100
+ pino: "^10.4.0",
101
+ postgres: "^3.4.7",
102
+ yaml: "^2.9.0",
103
+ zod: "^4.6.7"
104
+ },
105
+ peerDependencies: {
106
+ "@langchain/langgraph": "^0.2.0 || ^0.3.0"
107
+ },
108
+ peerDependenciesMeta: {
109
+ "@langchain/langgraph": {
110
+ optional: true
111
+ }
112
+ },
113
+ devDependencies: {
114
+ "@biomejs/biome": "^2.5.0",
115
+ "@types/node": "^24.3.0",
116
+ "drizzle-kit": "^0.31.10",
117
+ tsup: "^8.5.0",
118
+ tsx: "^4.20.5",
119
+ typescript: "^5.9.2",
120
+ vitest: "^4.1.12"
121
+ },
122
+ optionalDependencies: {
123
+ "@huggingface/transformers": "^4.3.2"
124
+ }
125
+ };
126
+
127
+ // src/version.ts
128
+ var VERSION = package_default.version;
129
+
130
+ // src/core/memory-file-store.ts
131
+ import { mkdir, readdir, readFile, rm, stat } from "fs/promises";
132
+ import { dirname, join, relative, resolve, sep } from "path";
133
+ import { parse as parseYaml, stringify as stringifyYaml } from "yaml";
134
+ import { z } from "zod";
135
+
136
+ // src/core/memory-lifecycle.ts
137
+ function isEligibleMemory(fact, options = {}) {
138
+ if (options.namespace && fact.namespace !== options.namespace) return false;
139
+ if (fact.sourceDeleted || fact.supersededBy) return false;
140
+ if (fact.category === "incident" && fact.resolvedBy && !options.includeResolved) return false;
141
+ return true;
142
+ }
143
+
144
+ // src/core/memory-file-store.ts
145
+ var FACT_CATEGORIES = ["general", "incident"];
146
+ var INCIDENT_SEVERITIES = ["low", "medium", "high", "critical"];
147
+ var factFrontMatterSchema = z.object({
148
+ schemaVersion: z.literal(1),
149
+ id: z.string().regex(/^fact_[a-z0-9]+$/),
150
+ namespace: z.string().min(1),
151
+ type: z.literal("fact"),
152
+ subject: z.string(),
153
+ predicate: z.string(),
154
+ object: z.string(),
155
+ /** Explicit single-valued claim identity; facts sharing it are rival assertions. */
156
+ propositionKey: z.string().min(1).nullable().default(null),
157
+ /** The caller's `remember` idempotency key, so a retry after reindex dedupes. */
158
+ idempotencyKey: z.string().min(1).max(200).nullable().default(null),
159
+ confidence: z.number().min(0).max(1),
160
+ createdAt: z.preprocess(
161
+ (value) => value instanceof Date ? value.toISOString() : value,
162
+ z.string().datetime()
163
+ ),
164
+ createdByAgent: z.string().nullable(),
165
+ sourceInteractionId: z.string().nullable(),
166
+ sourceDeleted: z.boolean(),
167
+ category: z.enum(FACT_CATEGORIES).default("general"),
168
+ paths: z.array(z.string().min(1)).default([]),
169
+ severity: z.enum(INCIDENT_SEVERITIES).nullable().default(null),
170
+ introducedBy: z.string().nullable().default(null),
171
+ resolvedBy: z.string().nullable().default(null),
172
+ fingerprint: z.string().regex(/^[a-f0-9]{64}$/).nullable().default(null),
173
+ sourcePlanId: z.string().nullable().default(null),
174
+ sourceSessionId: z.string().nullable().default(null),
175
+ verification: z.array(z.string()).default([]),
176
+ supersededBy: z.string().nullable().default(null),
177
+ /** Namespaces granted a live reference to this fact (durable form of reference shares). */
178
+ sharedWith: z.array(z.string().min(1)).default([])
179
+ });
180
+ var summaryFrontMatterSchema = z.object({
181
+ schemaVersion: z.literal(1),
182
+ id: z.string().regex(/^sum_[a-z0-9]+$/),
183
+ namespace: z.string().min(1),
184
+ type: z.literal("summary"),
185
+ sessionId: z.string().min(1),
186
+ version: z.number().int().positive(),
187
+ tokenCount: z.number().int().nonnegative(),
188
+ createdAt: z.preprocess(
189
+ (value) => value instanceof Date ? value.toISOString() : value,
190
+ z.string().datetime()
191
+ ),
192
+ createdByAgent: z.string().nullable()
193
+ });
194
+ var SCAN_BATCH = 64;
195
+ var parsedFiles = /* @__PURE__ */ new Map();
196
+ var loadedCaches = /* @__PURE__ */ new Set();
197
+ function parseCachePath(root, directory) {
198
+ return join(
199
+ root,
200
+ ".codebuddy",
201
+ "cache",
202
+ `parsed-${directory.split(sep).at(-1) ?? "memory"}.json`
203
+ );
204
+ }
205
+ async function loadParseCache(root, directory) {
206
+ if (loadedCaches.has(directory)) return;
207
+ loadedCaches.add(directory);
208
+ try {
209
+ const raw = JSON.parse(await readFile(parseCachePath(root, directory), "utf8"));
210
+ if (raw.version !== VERSION) return;
211
+ for (const [name, entry] of Object.entries(raw.files)) {
212
+ const path = join(directory, name);
213
+ if (!parsedFiles.has(path)) parsedFiles.set(path, entry);
214
+ }
215
+ } catch {
216
+ }
217
+ }
218
+ async function saveParseCache(root, directory) {
219
+ const files = {};
220
+ for (const [path, entry] of parsedFiles) {
221
+ if (dirname(path) === directory) files[relative(directory, path)] = entry;
222
+ }
223
+ try {
224
+ const path = parseCachePath(root, directory);
225
+ await mkdir(dirname(path), { recursive: true });
226
+ await writeAtomic(path, JSON.stringify({ version: VERSION, files }));
227
+ } catch {
228
+ }
229
+ }
230
+ var MemoryFileStore = class {
231
+ repositoryRoot;
232
+ factsDirectory;
233
+ summariesDirectory;
234
+ constructor(repositoryRoot = process.cwd()) {
235
+ this.repositoryRoot = resolve(repositoryRoot);
236
+ this.factsDirectory = join(this.repositoryRoot, ".codebuddy", "memory", "facts");
237
+ this.summariesDirectory = join(this.repositoryRoot, ".codebuddy", "memory", "summaries");
238
+ }
239
+ async writeFact(raw) {
240
+ const input = redactPersisted(raw);
241
+ const path = this.factPath(input.id);
242
+ await this.prepareDirectory(this.factsDirectory);
243
+ await assertNoSymlinkBetween(this.repositoryRoot, dirname(path));
244
+ const metadata = {
245
+ schemaVersion: 1,
246
+ id: input.id,
247
+ namespace: input.namespace,
248
+ type: "fact",
249
+ subject: input.subject,
250
+ predicate: input.predicate,
251
+ object: input.object,
252
+ propositionKey: input.propositionKey,
253
+ idempotencyKey: input.idempotencyKey,
254
+ confidence: input.confidence,
255
+ createdAt: input.createdAt,
256
+ createdByAgent: input.createdByAgent,
257
+ sourceInteractionId: input.sourceInteractionId,
258
+ sourceDeleted: input.sourceDeleted,
259
+ category: input.category,
260
+ paths: input.paths,
261
+ severity: input.severity,
262
+ introducedBy: input.introducedBy,
263
+ resolvedBy: input.resolvedBy,
264
+ fingerprint: input.fingerprint,
265
+ sourcePlanId: input.sourcePlanId,
266
+ sourceSessionId: input.sourceSessionId,
267
+ verification: input.verification,
268
+ supersededBy: input.supersededBy,
269
+ sharedWith: input.sharedWith
270
+ };
271
+ const frontMatter = stringifyYaml(stripUndefinedAndDefaultIncidentFields(metadata));
272
+ await writeAtomic(path, composeMarkdown(frontMatter, input.content));
273
+ return path;
274
+ }
275
+ async writeSummary(input) {
276
+ const path = this.summaryPath(input.id);
277
+ await this.prepareDirectory(this.summariesDirectory);
278
+ await assertNoSymlinkBetween(this.repositoryRoot, dirname(path));
279
+ const metadata = stringifyYaml({
280
+ schemaVersion: 1,
281
+ id: input.id,
282
+ namespace: input.namespace,
283
+ type: "summary",
284
+ sessionId: input.sessionId,
285
+ version: input.version,
286
+ tokenCount: input.tokenCount,
287
+ createdAt: input.createdAt,
288
+ createdByAgent: input.createdByAgent
289
+ });
290
+ await writeAtomic(path, composeMarkdown(metadata, input.content));
291
+ return path;
292
+ }
293
+ async readFact(pathOrId) {
294
+ return this.readFactFile(pathOrId, false);
295
+ }
296
+ /** `trusted`: the caller (scan) already proved the path is a regular file in a checked directory. */
297
+ async readFactFile(pathOrId, trusted) {
298
+ const path = pathOrId.endsWith(".md") ? this.safePath(pathOrId) : this.factPath(pathOrId);
299
+ if (!trusted) await assertNoSymlinkBetween(this.repositoryRoot, path);
300
+ const parsed = parseFrontMatter(await readFile(path, "utf8"));
301
+ const metadata = factFrontMatterSchema.parse(parseYaml(parsed.frontMatter));
302
+ return {
303
+ ...metadata,
304
+ content: parsed.content.trim(),
305
+ path
306
+ };
307
+ }
308
+ async listFacts() {
309
+ return (await this.scanFacts()).facts;
310
+ }
311
+ /**
312
+ * Parse every managed fact file. Hand-written markdown is ignored, and a
313
+ * schema-invalid/corrupt fact is reported in `invalid` (not thrown) so one
314
+ * bad file can't break recall, capture or reindexing for the whole project.
315
+ * Invalid files stay on disk for manual repair.
316
+ */
317
+ async scanFacts() {
318
+ const scan = await this.scan(
319
+ this.factsDirectory,
320
+ /^fact_[a-z0-9]+\.md$/,
321
+ (path, trusted) => this.readFactFile(path, trusted)
322
+ );
323
+ return { facts: scan.items, invalid: scan.invalid };
324
+ }
325
+ /**
326
+ * List incident facts for the namespace, ranked by severity then recency.
327
+ * Unlike {@link findIncidentFactsForPaths} this does not filter by path, so
328
+ * callers (e.g. the context engine's project bootstrap) can surface the
329
+ * repository's incident hotspots before any specific edit target is known.
330
+ */
331
+ async listIncidentFacts(input = {}) {
332
+ const incidents = (await this.listFacts()).filter(
333
+ (fact) => fact.category === "incident" && Boolean(fact.severity) && isEligibleMemory(fact, input)
334
+ );
335
+ return incidents.sort((left, right) => {
336
+ const severity = severityRank(right.severity) - severityRank(left.severity);
337
+ if (severity !== 0) return severity;
338
+ return right.createdAt.localeCompare(left.createdAt);
339
+ });
340
+ }
341
+ async findIncidentFactsForPaths(input) {
342
+ const wanted = new Set(input.paths.map(normalizeMemoryPath));
343
+ if (wanted.size === 0) return [];
344
+ return (await this.listIncidentFacts({
345
+ ...input.namespace !== void 0 ? { namespace: input.namespace } : {},
346
+ ...input.includeResolved !== void 0 ? { includeResolved: input.includeResolved } : {}
347
+ })).filter((fact) => fact.paths.map(normalizeMemoryPath).some((path) => wanted.has(path)));
348
+ }
349
+ async readSummary(pathOrId) {
350
+ const path = pathOrId.endsWith(".md") ? this.safePath(pathOrId) : this.summaryPath(pathOrId);
351
+ await assertNoSymlinkBetween(this.repositoryRoot, path);
352
+ const parsed = parseFrontMatter(await readFile(path, "utf8"));
353
+ return {
354
+ ...summaryFrontMatterSchema.parse(parseYaml(parsed.frontMatter)),
355
+ content: parsed.content.trim(),
356
+ path
357
+ };
358
+ }
359
+ async listSummaries() {
360
+ return (await this.scanSummaries()).summaries;
361
+ }
362
+ async scanSummaries() {
363
+ const scan = await this.scan(
364
+ this.summariesDirectory,
365
+ /^sum_[a-z0-9]+\.md$/,
366
+ (path) => this.readSummary(path)
367
+ );
368
+ return { summaries: scan.items, invalid: scan.invalid };
369
+ }
370
+ /**
371
+ * Parse every managed file in `directory`. Hot path: the prompt hook and
372
+ * capture scan facts several times per process, and the MCP server for its
373
+ * lifetime, so each parsed file is cached by path, mtime and size (a changed
374
+ * file is re-read, from any process) and files are read in parallel batches.
375
+ * The directory chain is checked for symlinks once; a `withFileTypes` entry
376
+ * that is a symlink is never `isFile()`, so no file escapes through one.
377
+ */
378
+ async scan(directory, managedName, read) {
379
+ try {
380
+ await this.prepareDirectory(directory);
381
+ await assertNoSymlinkBetween(this.repositoryRoot, directory);
382
+ await loadParseCache(this.repositoryRoot, directory);
383
+ let reparsed = false;
384
+ const entries = (await readdir(directory, { withFileTypes: true })).filter((entry) => entry.isFile() && managedName.test(entry.name)).sort((left, right) => left.name.localeCompare(right.name));
385
+ const live = new Set(entries.map((entry) => join(directory, entry.name)));
386
+ for (const path of [...parsedFiles.keys()]) {
387
+ if (dirname(path) === directory && !live.has(path)) {
388
+ parsedFiles.delete(path);
389
+ reparsed = true;
390
+ }
391
+ }
392
+ const outcomes = [];
393
+ for (let start = 0; start < entries.length; start += SCAN_BATCH) {
394
+ const batch = entries.slice(start, start + SCAN_BATCH);
395
+ outcomes.push(
396
+ ...await Promise.all(
397
+ batch.map(async (entry) => {
398
+ const path = join(directory, entry.name);
399
+ const id = entry.name.slice(0, -".md".length);
400
+ try {
401
+ const info = await stat(path);
402
+ const cached = parsedFiles.get(path);
403
+ const fresh = cached !== void 0 && cached.mtimeMs === info.mtimeMs && cached.size === info.size;
404
+ const item = fresh ? cached.item : await read(path, true);
405
+ if (!fresh) reparsed = true;
406
+ if (item.id !== id) {
407
+ throw new Error(`file ID ${id} differs from front matter ID ${item.id}`);
408
+ }
409
+ parsedFiles.set(path, { mtimeMs: info.mtimeMs, size: info.size, item });
410
+ return { item: { ...item } };
411
+ } catch (error) {
412
+ parsedFiles.delete(path);
413
+ return {
414
+ invalid: {
415
+ id,
416
+ path,
417
+ error: error.message.split("\n")[0]?.slice(0, 300) ?? "unreadable"
418
+ }
419
+ };
420
+ }
421
+ })
422
+ )
423
+ );
424
+ }
425
+ if (reparsed) await saveParseCache(this.repositoryRoot, directory);
426
+ const result = { items: [], invalid: [] };
427
+ for (const outcome of outcomes) {
428
+ if ("item" in outcome) result.items.push(outcome.item);
429
+ else result.invalid.push(outcome.invalid);
430
+ }
431
+ return result;
432
+ } catch (error) {
433
+ if (error.code === "ENOENT") return { items: [], invalid: [] };
434
+ throw error;
435
+ }
436
+ }
437
+ async deleteFact(id) {
438
+ await rm(this.factPath(id), { force: true });
439
+ }
440
+ async markIncidentResolved(id, resolvedBy) {
441
+ const fact = await this.readFact(id);
442
+ await this.writeFact(copyFact(fact, { resolvedBy }));
443
+ }
444
+ async markFactSuperseded(id, supersededBy) {
445
+ const fact = await this.readFact(id);
446
+ await this.writeFact(copyFact(fact, { supersededBy }));
447
+ }
448
+ async setFactSharedWith(id, sharedWith) {
449
+ const fact = await this.readFact(id);
450
+ await this.writeFact(copyFact(fact, { sharedWith: [...new Set(sharedWith)].sort() }));
451
+ }
452
+ /** Persist interaction deletion in Markdown before the derived DB is updated. */
453
+ async markSourceInteractionDeleted(namespace, sourceInteractionId) {
454
+ const { facts: facts2 } = await this.scanFacts();
455
+ for (const fact of facts2) {
456
+ if (fact.namespace !== namespace || fact.sourceInteractionId !== sourceInteractionId)
457
+ continue;
458
+ if (fact.sourceDeleted) continue;
459
+ await this.writeFact(copyFact(fact, { sourceDeleted: true }));
460
+ }
461
+ }
462
+ /** Persist that a fact's source interaction was forgotten, keeping its provenance id. */
463
+ async markFactSourceDeleted(id) {
464
+ const fact = await this.readFact(id);
465
+ await this.writeFact(copyFact(fact, { sourceDeleted: true }));
466
+ }
467
+ factPath(id) {
468
+ if (!/^fact_[a-z0-9]+$/.test(id)) {
469
+ throw new Error(`Invalid fact id: ${id}`);
470
+ }
471
+ return this.safePath(join(this.factsDirectory, `${id}.md`));
472
+ }
473
+ summaryPath(id) {
474
+ if (!/^sum_[a-z0-9]+$/.test(id)) throw new Error(`Invalid summary id: ${id}`);
475
+ return this.safePath(join(this.summariesDirectory, `${id}.md`));
476
+ }
477
+ safePath(path) {
478
+ const absolute = resolve(path);
479
+ const relativePath = relative(this.repositoryRoot, absolute);
480
+ if (relativePath === ".." || relativePath.startsWith(`..${sep}`) || relativePath === "") {
481
+ throw new Error(`Memory path escapes repository root: ${path}`);
482
+ }
483
+ return absolute;
484
+ }
485
+ async prepareDirectory(directory) {
486
+ await assertNoSymlinkBetween(this.repositoryRoot, dirname(directory));
487
+ await mkdir(directory, { recursive: true, mode: 448 });
488
+ }
489
+ };
490
+ function copyFact(fact, patch) {
491
+ const { path: _path, schemaVersion: _schemaVersion, type: _type, ...write } = fact;
492
+ return { ...write, ...patch };
493
+ }
494
+ function stripUndefinedAndDefaultIncidentFields(metadata) {
495
+ return Object.fromEntries(
496
+ Object.entries(metadata).filter(([key, value]) => {
497
+ if (value === void 0) return false;
498
+ if (key === "category" && value === "general") return false;
499
+ if ((key === "paths" || key === "sharedWith") && Array.isArray(value) && value.length === 0)
500
+ return false;
501
+ if (["severity", "introducedBy", "resolvedBy", "propositionKey", "idempotencyKey"].includes(
502
+ key
503
+ ) && (value === null || value === void 0)) {
504
+ return false;
505
+ }
506
+ return true;
507
+ })
508
+ );
509
+ }
510
+ function normalizeMemoryPath(path) {
511
+ return path.replace(/\\/g, "/").replace(/^\.\//, "");
512
+ }
513
+ function severityRank(severity) {
514
+ switch (severity) {
515
+ case "critical":
516
+ return 4;
517
+ case "high":
518
+ return 3;
519
+ case "medium":
520
+ return 2;
521
+ case "low":
522
+ return 1;
523
+ }
524
+ }
525
+
526
+ // src/db/schema.ts
527
+ var schema_exports = {};
528
+ __export(schema_exports, {
529
+ HNSW_EF_CONSTRUCTION: () => HNSW_EF_CONSTRUCTION,
530
+ HNSW_M: () => HNSW_M,
531
+ VECTOR_DIMENSIONS: () => VECTOR_DIMENSIONS,
532
+ auditActionEnum: () => auditActionEnum,
533
+ auditLog: () => auditLog,
534
+ checkpoints: () => checkpoints,
535
+ embeddingOwnerTypeEnum: () => embeddingOwnerTypeEnum,
536
+ embeddingStatusEnum: () => embeddingStatusEnum,
537
+ embeddings: () => embeddings,
538
+ facts: () => facts,
539
+ interactionRoleEnum: () => interactionRoleEnum,
540
+ interactions: () => interactions,
541
+ memoryTypeEnum: () => memoryTypeEnum,
542
+ modelCallStatusEnum: () => modelCallStatusEnum,
543
+ modelCallTypeEnum: () => modelCallTypeEnum,
544
+ modelCalls: () => modelCalls,
545
+ namespaces: () => namespaces,
546
+ sessionSummaries: () => sessionSummaries,
547
+ shareModeEnum: () => shareModeEnum,
548
+ shares: () => shares
549
+ });
550
+ import { sql } from "drizzle-orm";
551
+ import {
552
+ boolean,
553
+ customType,
554
+ index,
555
+ integer,
556
+ jsonb,
557
+ numeric,
558
+ pgEnum,
559
+ pgTable,
560
+ text,
561
+ timestamp,
562
+ uniqueIndex
563
+ } from "drizzle-orm/pg-core";
564
+ var VECTOR_DIMENSIONS = 384;
565
+ var HNSW_M = 16;
566
+ var HNSW_EF_CONSTRUCTION = 64;
567
+ var vector = customType({
568
+ dataType() {
569
+ return `vector(${VECTOR_DIMENSIONS})`;
570
+ }
571
+ });
572
+ var memoryTypeEnum = pgEnum("memory_type", ["interaction", "fact", "summary"]);
573
+ var interactionRoleEnum = pgEnum("interaction_role", ["user", "assistant", "system"]);
574
+ var embeddingOwnerTypeEnum = pgEnum("embedding_owner_type", [
575
+ "interaction",
576
+ "fact",
577
+ "summary"
578
+ ]);
579
+ var embeddingStatusEnum = pgEnum("embedding_status", [
580
+ "pending",
581
+ "processing",
582
+ "ready",
583
+ "failed"
584
+ ]);
585
+ var shareModeEnum = pgEnum("share_mode", ["reference", "snapshot"]);
586
+ var modelCallTypeEnum = pgEnum("model_call_type", ["embedding", "llm"]);
587
+ var modelCallStatusEnum = pgEnum("model_call_status", [
588
+ "success",
589
+ "failed",
590
+ "timeout",
591
+ "rate_limited",
592
+ "gated",
593
+ "fallback"
594
+ ]);
595
+ var auditActionEnum = pgEnum("audit_action", [
596
+ "remember",
597
+ "remember_batch",
598
+ "share",
599
+ "forget",
600
+ "config"
601
+ ]);
602
+ var createdAt = timestamp("created_at", { withTimezone: true }).notNull().defaultNow();
603
+ var updatedAt = timestamp("updated_at", { withTimezone: true }).notNull().defaultNow();
604
+ var namespaces = pgTable(
605
+ "namespaces",
606
+ {
607
+ id: text("id").primaryKey(),
608
+ name: text("name").notNull(),
609
+ createdAt,
610
+ updatedAt
611
+ },
612
+ (table) => ({
613
+ nameUnique: uniqueIndex("namespaces_name_unique").on(table.name)
614
+ })
615
+ );
616
+ var interactions = pgTable(
617
+ "interactions",
618
+ {
619
+ id: text("id").primaryKey(),
620
+ namespaceId: text("namespace_id").notNull().references(() => namespaces.id, { onDelete: "cascade" }),
621
+ sessionId: text("session_id").notNull(),
622
+ role: interactionRoleEnum("role").notNull().default("user"),
623
+ content: text("content").notNull(),
624
+ contentHash: text("content_hash").notNull(),
625
+ tokenCount: integer("token_count").notNull().default(0),
626
+ createdByAgent: text("created_by_agent"),
627
+ createdAt
628
+ },
629
+ (table) => ({
630
+ namespaceContentHashUnique: uniqueIndex("interactions_namespace_content_hash_unique").on(
631
+ table.namespaceId,
632
+ table.contentHash
633
+ ),
634
+ namespaceSessionCreatedIdx: index("interactions_namespace_session_created_idx").on(
635
+ table.namespaceId,
636
+ table.sessionId,
637
+ table.createdAt
638
+ )
639
+ })
640
+ );
641
+ var sessionSummaries = pgTable(
642
+ "session_summaries",
643
+ {
644
+ id: text("id").primaryKey(),
645
+ namespaceId: text("namespace_id").notNull().references(() => namespaces.id, { onDelete: "cascade" }),
646
+ sessionId: text("session_id").notNull(),
647
+ content: text("content").notNull(),
648
+ version: integer("version").notNull().default(1),
649
+ tokenCount: integer("token_count").notNull().default(0),
650
+ createdByAgent: text("created_by_agent"),
651
+ /** See facts.fileBacked. */
652
+ fileBacked: boolean("file_backed").notNull().default(false),
653
+ createdAt
654
+ },
655
+ (table) => ({
656
+ namespaceSessionVersionIdx: index("session_summaries_namespace_session_version_idx").on(
657
+ table.namespaceId,
658
+ table.sessionId,
659
+ table.version
660
+ )
661
+ })
662
+ );
663
+ var facts = pgTable(
664
+ "facts",
665
+ {
666
+ id: text("id").primaryKey(),
667
+ namespaceId: text("namespace_id").notNull().references(() => namespaces.id, { onDelete: "cascade" }),
668
+ subject: text("subject").notNull(),
669
+ predicate: text("predicate").notNull(),
670
+ object: text("object").notNull(),
671
+ propositionKey: text("proposition_key"),
672
+ /** Kept apart from content_hash so a reindex (which recomputes the hash) keeps it. */
673
+ idempotencyKey: text("idempotency_key"),
674
+ content: text("content").notNull(),
675
+ contentHash: text("content_hash").notNull(),
676
+ confidence: numeric("confidence", { precision: 5, scale: 4 }).notNull().default("1"),
677
+ /**
678
+ * Historical provenance only — deliberately not a foreign key. Interactions
679
+ * are ephemeral DB rows; Markdown facts must re-import after a rebuild that
680
+ * lost them, and the ID must survive so `sourceDeleted` can be tracked.
681
+ */
682
+ sourceInteractionId: text("source_interaction_id"),
683
+ sourceDeleted: boolean("source_deleted").notNull().default(false),
684
+ supersededBy: text("superseded_by"),
685
+ /**
686
+ * True once a reindex imported this row from its Markdown file. Only such
687
+ * rows are deleted when the file disappears; DB-only legacy rows are kept.
688
+ */
689
+ fileBacked: boolean("file_backed").notNull().default(false),
690
+ embeddingModel: text("embedding_model"),
691
+ createdByAgent: text("created_by_agent"),
692
+ createdAt,
693
+ updatedAt
694
+ },
695
+ (table) => ({
696
+ namespaceContentHashUnique: uniqueIndex("facts_namespace_content_hash_unique").on(
697
+ table.namespaceId,
698
+ table.contentHash
699
+ ),
700
+ namespaceSubjectIdx: index("facts_namespace_subject_idx").on(table.namespaceId, table.subject),
701
+ namespaceIdempotencyIdx: index("facts_namespace_idempotency_idx").on(
702
+ table.namespaceId,
703
+ table.idempotencyKey
704
+ ),
705
+ sourceInteractionIdx: index("facts_source_interaction_idx").on(table.sourceInteractionId)
706
+ })
707
+ );
708
+ var embeddings = pgTable(
709
+ "embeddings",
710
+ {
711
+ id: text("id").primaryKey(),
712
+ namespaceId: text("namespace_id").notNull().references(() => namespaces.id, { onDelete: "cascade" }),
713
+ ownerType: embeddingOwnerTypeEnum("owner_type").notNull(),
714
+ ownerId: text("owner_id").notNull(),
715
+ vector: vector("vector").notNull(),
716
+ embeddingModel: text("embedding_model").notNull(),
717
+ embeddingSpace: text("embedding_space"),
718
+ status: embeddingStatusEnum("status").notNull().default("pending"),
719
+ attempts: integer("attempts").notNull().default(0),
720
+ lastError: text("last_error"),
721
+ /** Lease deadline while status='processing'; null otherwise. */
722
+ leaseUntil: timestamp("lease_until", { withTimezone: true }),
723
+ leaseToken: text("lease_token"),
724
+ createdAt,
725
+ updatedAt
726
+ },
727
+ (table) => ({
728
+ ownerUnique: uniqueIndex("embeddings_owner_unique").on(table.ownerType, table.ownerId),
729
+ namespaceModelStatusIdx: index("embeddings_namespace_model_status_idx").on(
730
+ table.namespaceId,
731
+ table.embeddingModel,
732
+ table.status
733
+ ),
734
+ namespaceSpaceStatusIdx: index("embeddings_namespace_space_status_idx").on(
735
+ table.namespaceId,
736
+ table.embeddingSpace,
737
+ table.status
738
+ ),
739
+ vectorHnswIdx: index("embeddings_vector_hnsw_idx").using(
740
+ "hnsw",
741
+ sql`${table.vector} vector_cosine_ops`
742
+ )
743
+ })
744
+ );
745
+ var shares = pgTable(
746
+ "shares",
747
+ {
748
+ id: text("id").primaryKey(),
749
+ fromNamespaceId: text("from_namespace_id").notNull().references(() => namespaces.id, { onDelete: "cascade" }),
750
+ toNamespaceId: text("to_namespace_id").notNull().references(() => namespaces.id, { onDelete: "cascade" }),
751
+ sourceFactId: text("source_fact_id").notNull().references(() => facts.id, { onDelete: "cascade" }),
752
+ snapshotFactId: text("snapshot_fact_id").references(() => facts.id, { onDelete: "set null" }),
753
+ mode: shareModeEnum("mode").notNull().default("reference"),
754
+ tombstoned: boolean("tombstoned").notNull().default(false),
755
+ createdByAgent: text("created_by_agent"),
756
+ createdAt
757
+ },
758
+ (table) => ({
759
+ shareUnique: uniqueIndex("shares_target_source_unique").on(
760
+ table.toNamespaceId,
761
+ table.sourceFactId,
762
+ table.mode
763
+ ),
764
+ fromNamespaceIdx: index("shares_from_namespace_idx").on(table.fromNamespaceId)
765
+ })
766
+ );
767
+ var checkpoints = pgTable(
768
+ "checkpoints",
769
+ {
770
+ id: text("id").primaryKey(),
771
+ namespaceId: text("namespace_id").notNull().references(() => namespaces.id, { onDelete: "cascade" }),
772
+ threadId: text("thread_id").notNull(),
773
+ checkpointId: text("checkpoint_id").notNull(),
774
+ parentId: text("parent_id"),
775
+ channelValues: jsonb("channel_values").notNull().default(sql`'{}'::jsonb`),
776
+ metadata: jsonb("metadata").notNull().default(sql`'{}'::jsonb`),
777
+ createdAt
778
+ },
779
+ (table) => ({
780
+ checkpointUnique: uniqueIndex("checkpoints_thread_checkpoint_unique").on(
781
+ table.namespaceId,
782
+ table.threadId,
783
+ table.checkpointId
784
+ )
785
+ })
786
+ );
787
+ var modelCalls = pgTable(
788
+ "model_calls",
789
+ {
790
+ id: text("id").primaryKey(),
791
+ namespaceId: text("namespace_id").references(() => namespaces.id, { onDelete: "set null" }),
792
+ model: text("model").notNull(),
793
+ type: modelCallTypeEnum("type").notNull(),
794
+ latencyMs: integer("latency_ms"),
795
+ tokens: integer("tokens"),
796
+ status: modelCallStatusEnum("status").notNull(),
797
+ error: text("error"),
798
+ metadata: jsonb("metadata").notNull().default(sql`'{}'::jsonb`),
799
+ createdAt
800
+ },
801
+ (table) => ({
802
+ modelCreatedIdx: index("model_calls_model_created_idx").on(table.model, table.createdAt),
803
+ namespaceCreatedIdx: index("model_calls_namespace_created_idx").on(
804
+ table.namespaceId,
805
+ table.createdAt
806
+ )
807
+ })
808
+ );
809
+ var auditLog = pgTable(
810
+ "audit_log",
811
+ {
812
+ id: text("id").primaryKey(),
813
+ namespaceId: text("namespace_id").references(() => namespaces.id, { onDelete: "set null" }),
814
+ action: auditActionEnum("action").notNull(),
815
+ entityType: text("entity_type").notNull(),
816
+ entityId: text("entity_id"),
817
+ createdByAgent: text("created_by_agent"),
818
+ metadata: jsonb("metadata").notNull().default(sql`'{}'::jsonb`),
819
+ createdAt
820
+ },
821
+ (table) => ({
822
+ namespaceActionCreatedIdx: index("audit_log_namespace_action_created_idx").on(
823
+ table.namespaceId,
824
+ table.action,
825
+ table.createdAt
826
+ )
827
+ })
828
+ );
829
+
830
+ // src/core/memory-search.ts
831
+ function candidateLimit(limit) {
832
+ if (!Number.isFinite(limit)) return 256;
833
+ return Math.max(1, Math.min(1024, Math.trunc(limit)));
834
+ }
835
+ function validSearchVector(vector2) {
836
+ return vector2.length === VECTOR_DIMENSIONS && vector2.every((value) => Number.isFinite(Math.fround(value))) && vector2.some((value) => value !== 0);
837
+ }
838
+ var QUERY_STOPWORDS = /* @__PURE__ */ new Set([
839
+ "a",
840
+ "about",
841
+ "after",
842
+ "again",
843
+ "all",
844
+ "also",
845
+ "always",
846
+ "an",
847
+ "and",
848
+ "any",
849
+ "are",
850
+ "as",
851
+ "at",
852
+ "back",
853
+ "be",
854
+ "been",
855
+ "before",
856
+ "being",
857
+ "but",
858
+ "by",
859
+ "can",
860
+ "could",
861
+ "did",
862
+ "do",
863
+ "does",
864
+ "done",
865
+ "each",
866
+ "even",
867
+ "ever",
868
+ "for",
869
+ "from",
870
+ "get",
871
+ "gets",
872
+ "got",
873
+ "had",
874
+ "has",
875
+ "have",
876
+ "here",
877
+ "how",
878
+ "i",
879
+ "if",
880
+ "in",
881
+ "into",
882
+ "is",
883
+ "it",
884
+ "its",
885
+ "just",
886
+ "like",
887
+ "make",
888
+ "me",
889
+ "more",
890
+ "most",
891
+ "my",
892
+ "never",
893
+ "no",
894
+ "not",
895
+ "now",
896
+ "of",
897
+ "on",
898
+ "only",
899
+ "or",
900
+ "other",
901
+ "our",
902
+ "out",
903
+ "over",
904
+ "please",
905
+ "really",
906
+ "same",
907
+ "should",
908
+ "so",
909
+ "some",
910
+ "sometimes",
911
+ "still",
912
+ "such",
913
+ "than",
914
+ "that",
915
+ "the",
916
+ "their",
917
+ "them",
918
+ "then",
919
+ "there",
920
+ "these",
921
+ "they",
922
+ "this",
923
+ "those",
924
+ "through",
925
+ "to",
926
+ "too",
927
+ "under",
928
+ "up",
929
+ "us",
930
+ "very",
931
+ "was",
932
+ "we",
933
+ "were",
934
+ "what",
935
+ "when",
936
+ "where",
937
+ "which",
938
+ "while",
939
+ "who",
940
+ "why",
941
+ "will",
942
+ "with",
943
+ "would",
944
+ "yet",
945
+ "you",
946
+ "your"
947
+ ]);
948
+ function lexicalTerms(query) {
949
+ return [
950
+ ...new Set(
951
+ query.slice(0, 4096).toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? []
952
+ )
953
+ ].filter((term) => !QUERY_STOPWORDS.has(term)).slice(0, 32).map((term) => term.slice(0, 64));
954
+ }
955
+ var GENERIC_TERMS = new Set(
956
+ "add added adding bug build call change changed changes check code config configure configuration create data default delete error errors feature file files fix fixed handle issue line load logic new option options problem project read remove result return run running save set setting settings show step support test tests thing time update updated use used value values version want way work works write".split(" ")
957
+ );
958
+ var RARE_TERM_SHARE = 5e-3;
959
+ var RARE_TERM_MIN_DF = 2;
960
+ function admitsLexically(shared, documentFrequency, corpusSize) {
961
+ const specific = shared.filter((term) => !GENERIC_TERMS.has(term));
962
+ if (specific.length >= 2) return true;
963
+ const rare = Math.max(RARE_TERM_MIN_DF, Math.floor(RARE_TERM_SHARE * corpusSize));
964
+ return specific.some((term) => (documentFrequency.get(term) ?? 0) <= rare);
965
+ }
966
+ var CLAIM_BOILERPLATE = /* @__PURE__ */ new Set([
967
+ "decided",
968
+ "decide",
969
+ "decision",
970
+ "made",
971
+ "use",
972
+ "uses",
973
+ "used",
974
+ "using",
975
+ "now",
976
+ "going",
977
+ "will"
978
+ ]);
979
+ function termOverlap(a, b) {
980
+ const terms = (text2) => new Set(
981
+ (text2.toLowerCase().match(/[\p{L}\p{N}_]+/gu) ?? []).filter(
982
+ (term) => !QUERY_STOPWORDS.has(term) && !CLAIM_BOILERPLATE.has(term)
983
+ )
984
+ );
985
+ const left = terms(a);
986
+ const right = terms(b);
987
+ if (left.size === 0 || right.size === 0) return 0;
988
+ let shared = 0;
989
+ for (const term of left) if (right.has(term)) shared += 1;
990
+ return shared / (left.size + right.size - shared);
991
+ }
992
+
993
+ export {
994
+ isEligibleMemory,
995
+ namespaces,
996
+ interactions,
997
+ sessionSummaries,
998
+ facts,
999
+ embeddings,
1000
+ shares,
1001
+ modelCalls,
1002
+ auditLog,
1003
+ schema_exports,
1004
+ candidateLimit,
1005
+ validSearchVector,
1006
+ lexicalTerms,
1007
+ admitsLexically,
1008
+ termOverlap,
1009
+ VERSION,
1010
+ FACT_CATEGORIES,
1011
+ INCIDENT_SEVERITIES,
1012
+ MemoryFileStore
1013
+ };
1014
+ //# sourceMappingURL=chunk-JUAFCLRB.js.map