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