@orquentra/codebuddy 2.5.0 → 2.6.2

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