@edihasaj/recall 0.8.3 → 0.8.5

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 (65) hide show
  1. package/README.md +10 -0
  2. package/dist/{chunk-3OYO5BW3.js → chunk-4VBHVY3D.js} +4 -4
  3. package/dist/chunk-4VBHVY3D.js.map +1 -0
  4. package/dist/{chunk-JRIM7VBY.js → chunk-A4ES3H4Y.js} +2 -2
  5. package/dist/{chunk-72USXFEP.js → chunk-BHTIIKRB.js} +4 -4
  6. package/dist/{chunk-37K4DPRI.js → chunk-BJTLWRZH.js} +2 -2
  7. package/dist/{chunk-DRHHOFBX.js → chunk-DYAQ4RKX.js} +263 -13
  8. package/dist/chunk-DYAQ4RKX.js.map +1 -0
  9. package/dist/{chunk-Z6RT5BUO.js → chunk-EYMC2PDI.js} +2 -2
  10. package/dist/{chunk-QDA5M3AJ.js → chunk-G5IAOZAL.js} +28 -2
  11. package/dist/chunk-G5IAOZAL.js.map +1 -0
  12. package/dist/{chunk-5E3KREDH.js → chunk-ITU4GQDL.js} +46 -10
  13. package/dist/chunk-ITU4GQDL.js.map +1 -0
  14. package/dist/{chunk-R3DJIEID.js → chunk-OR6VZZI6.js} +3 -3
  15. package/dist/chunk-PUMEMKGF.js +29 -0
  16. package/dist/chunk-PUMEMKGF.js.map +1 -0
  17. package/dist/{chunk-L2YIWNLN.js → chunk-Q6CNO5TF.js} +7 -7
  18. package/dist/{chunk-YL23MKB3.js → chunk-SAVLATC5.js} +24 -4
  19. package/dist/chunk-SAVLATC5.js.map +1 -0
  20. package/dist/{chunk-4LZMHQ6Y.js → chunk-VPZ4OZKK.js} +531 -597
  21. package/dist/chunk-VPZ4OZKK.js.map +1 -0
  22. package/dist/chunk-WC7S7BOP.js +328 -0
  23. package/dist/chunk-WC7S7BOP.js.map +1 -0
  24. package/dist/{cleanup-XOIYUPHS.js → cleanup-MPSAZNDH.js} +10 -6
  25. package/dist/cli.js +49 -31
  26. package/dist/cli.js.map +1 -1
  27. package/dist/daemon.js +31 -18
  28. package/dist/daemon.js.map +1 -1
  29. package/dist/{dispatcher-43DWN3ZP.js → dispatcher-RCCPGNDO.js} +6 -6
  30. package/dist/{embeddings-GKNH2E3N.js → embeddings-MNNECV6B.js} +3 -3
  31. package/dist/{ingest-QOZDSJOA.js → ingest-KVLFQ6J7.js} +6 -6
  32. package/dist/mcp.js +11 -9
  33. package/dist/mcp.js.map +1 -1
  34. package/dist/{quality-2JOLSIC3.js → quality-OXFQ7JXM.js} +8 -4
  35. package/dist/retrieval-27YV546Y.js +13 -0
  36. package/dist/{store-2BPQPOOZ.js → store-KU5H2RA2.js} +3 -3
  37. package/dist/sync-server.js +6 -0
  38. package/dist/sync-server.js.map +1 -1
  39. package/dist/{tasks-IFHV6EBT.js → tasks-SCYA2PJJ.js} +8 -6
  40. package/dist/{usage-YBS74UEU.js → usage-VVXTCJHT.js} +3 -3
  41. package/drizzle/0009_memory_value_events.sql +23 -0
  42. package/drizzle/meta/_journal.json +8 -1
  43. package/package.json +2 -1
  44. package/dist/chunk-3OYO5BW3.js.map +0 -1
  45. package/dist/chunk-4LZMHQ6Y.js.map +0 -1
  46. package/dist/chunk-5E3KREDH.js.map +0 -1
  47. package/dist/chunk-DRHHOFBX.js.map +0 -1
  48. package/dist/chunk-QDA5M3AJ.js.map +0 -1
  49. package/dist/chunk-YL23MKB3.js.map +0 -1
  50. package/dist/retrieval-PQE7OHHJ.js +0 -13
  51. /package/dist/{chunk-JRIM7VBY.js.map → chunk-A4ES3H4Y.js.map} +0 -0
  52. /package/dist/{chunk-72USXFEP.js.map → chunk-BHTIIKRB.js.map} +0 -0
  53. /package/dist/{chunk-37K4DPRI.js.map → chunk-BJTLWRZH.js.map} +0 -0
  54. /package/dist/{chunk-Z6RT5BUO.js.map → chunk-EYMC2PDI.js.map} +0 -0
  55. /package/dist/{chunk-R3DJIEID.js.map → chunk-OR6VZZI6.js.map} +0 -0
  56. /package/dist/{chunk-L2YIWNLN.js.map → chunk-Q6CNO5TF.js.map} +0 -0
  57. /package/dist/{cleanup-XOIYUPHS.js.map → cleanup-MPSAZNDH.js.map} +0 -0
  58. /package/dist/{dispatcher-43DWN3ZP.js.map → dispatcher-RCCPGNDO.js.map} +0 -0
  59. /package/dist/{embeddings-GKNH2E3N.js.map → embeddings-MNNECV6B.js.map} +0 -0
  60. /package/dist/{ingest-QOZDSJOA.js.map → ingest-KVLFQ6J7.js.map} +0 -0
  61. /package/dist/{quality-2JOLSIC3.js.map → quality-OXFQ7JXM.js.map} +0 -0
  62. /package/dist/{retrieval-PQE7OHHJ.js.map → retrieval-27YV546Y.js.map} +0 -0
  63. /package/dist/{store-2BPQPOOZ.js.map → store-KU5H2RA2.js.map} +0 -0
  64. /package/dist/{tasks-IFHV6EBT.js.map → tasks-SCYA2PJJ.js.map} +0 -0
  65. /package/dist/{usage-YBS74UEU.js.map → usage-VVXTCJHT.js.map} +0 -0
@@ -0,0 +1,328 @@
1
+ import {
2
+ getMemory,
3
+ promoteMemory,
4
+ queryMemories
5
+ } from "./chunk-4VBHVY3D.js";
6
+ import {
7
+ asc,
8
+ desc
9
+ } from "./chunk-BJTLWRZH.js";
10
+ import {
11
+ and,
12
+ eq,
13
+ gte,
14
+ inArray,
15
+ isNull,
16
+ memories,
17
+ memoryInjections,
18
+ memoryValueEvents,
19
+ sql
20
+ } from "./chunk-G5IAOZAL.js";
21
+
22
+ // src/models/memory-value.ts
23
+ import { randomUUID as randomUUID2 } from "crypto";
24
+
25
+ // src/models/memory-injections.ts
26
+ import { randomUUID } from "crypto";
27
+ function recordMemoryInjections(db, input) {
28
+ if (!input.session_id || input.memory_ids.length === 0) return 0;
29
+ const injectedAt = (/* @__PURE__ */ new Date()).toISOString();
30
+ let inserted = 0;
31
+ for (const memoryId of input.memory_ids) {
32
+ const result = db.insert(memoryInjections).values({
33
+ id: randomUUID(),
34
+ memory_id: memoryId,
35
+ session_id: input.session_id,
36
+ repo: input.repo ?? null,
37
+ injected_at: injectedAt,
38
+ outcome: null,
39
+ outcome_at: null
40
+ }).onConflictDoNothing({
41
+ target: [memoryInjections.memory_id, memoryInjections.session_id]
42
+ }).run();
43
+ inserted += Number(result.changes ?? 0);
44
+ }
45
+ return inserted;
46
+ }
47
+ function listInjectedMemoryIdsForSession(db, sessionId) {
48
+ const rows = db.select({ memory_id: memoryInjections.memory_id }).from(memoryInjections).where(eq(memoryInjections.session_id, sessionId)).all();
49
+ return new Set(rows.map((row) => row.memory_id));
50
+ }
51
+ function listPendingMemoryInjections(db, sessionId) {
52
+ const rows = db.select().from(memoryInjections).where(and(
53
+ eq(memoryInjections.session_id, sessionId),
54
+ isNull(memoryInjections.outcome)
55
+ )).orderBy(asc(memoryInjections.injected_at)).all();
56
+ return rows.map((row) => ({
57
+ ...rowToMemoryInjection(row),
58
+ memory: getMemory(db, row.memory_id) ?? null
59
+ }));
60
+ }
61
+ function resolveMemoryInjectionOutcome(db, memoryId, sessionId, outcome) {
62
+ const outcomeAt = (/* @__PURE__ */ new Date()).toISOString();
63
+ const result = db.update(memoryInjections).set({
64
+ outcome,
65
+ outcome_at: outcomeAt
66
+ }).where(and(
67
+ eq(memoryInjections.memory_id, memoryId),
68
+ eq(memoryInjections.session_id, sessionId),
69
+ isNull(memoryInjections.outcome)
70
+ )).run();
71
+ return Number(result.changes ?? 0) > 0;
72
+ }
73
+ function pathMatchesMemory(mem, targetPath) {
74
+ if (!targetPath) return mem.scope === "repo" || mem.scope === "team" || mem.scope === "global";
75
+ if (mem.scope === "repo" || mem.scope === "team" || mem.scope === "global") return true;
76
+ if (!mem.path_scope) return true;
77
+ const pattern = mem.path_scope;
78
+ if (pattern.endsWith("**")) {
79
+ return targetPath.startsWith(pattern.slice(0, -2));
80
+ }
81
+ if (pattern.includes("*")) {
82
+ const regex = new RegExp(
83
+ "^" + pattern.replace(/\*/g, "[^/]*").replace(/\*\*/g, ".*") + "$"
84
+ );
85
+ return regex.test(targetPath);
86
+ }
87
+ return targetPath.startsWith(pattern);
88
+ }
89
+ function toolCallTouchesMemory(mem, toolCall) {
90
+ if (toolCall.path && pathMatchesMemory(mem, toolCall.path)) return true;
91
+ if (toolCall.input_summary) {
92
+ const inferredPath = extractPath(toolCall.input_summary);
93
+ if (inferredPath && pathMatchesMemory(mem, inferredPath)) return true;
94
+ }
95
+ return mem.scope === "repo" || mem.scope === "team" || mem.scope === "global";
96
+ }
97
+ function rowToMemoryInjection(row) {
98
+ return {
99
+ id: row.id,
100
+ memory_id: row.memory_id,
101
+ session_id: row.session_id,
102
+ repo: row.repo,
103
+ injected_at: row.injected_at,
104
+ outcome: row.outcome,
105
+ outcome_at: row.outcome_at
106
+ };
107
+ }
108
+ function extractPath(text) {
109
+ const match = text.match(
110
+ /\b((?:src|lib|app|components|utils|test|spec)\/[\w./-]+|[\w./-]+\.(?:ts|tsx|js|jsx|py|rs|go|swift|java|rb|json|toml|ya?ml))\b/
111
+ );
112
+ return match?.[1];
113
+ }
114
+
115
+ // src/models/memory-value.ts
116
+ function estimateTokens(text) {
117
+ const trimmed = text?.trim();
118
+ if (!trimmed) return 0;
119
+ return Math.max(1, Math.ceil(trimmed.length / 4));
120
+ }
121
+ function recordMemoryValueEvent(db, input) {
122
+ const id = randomUUID2();
123
+ db.insert(memoryValueEvents).values({
124
+ id,
125
+ memory_id: input.memory_id ?? null,
126
+ injection_id: input.injection_id ?? null,
127
+ feedback_id: input.feedback_id ?? null,
128
+ session_id: input.session_id,
129
+ repo: input.repo ?? null,
130
+ event_type: input.event_type,
131
+ source: input.source,
132
+ injected_tokens_estimate: Math.max(0, Math.round(input.injected_tokens_estimate ?? 0)),
133
+ saved_tokens_estimate: Math.max(0, Math.round(input.saved_tokens_estimate ?? 0)),
134
+ evidence: input.evidence ?? {},
135
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
136
+ }).run();
137
+ return id;
138
+ }
139
+ function recordInjectionValueEvents(db, input) {
140
+ if (!input.session_id || input.memory_ids.length === 0) return 0;
141
+ const rows = db.select({
142
+ id: memoryInjections.id,
143
+ memory_id: memoryInjections.memory_id
144
+ }).from(memoryInjections).where(and(
145
+ eq(memoryInjections.session_id, input.session_id),
146
+ inArray(memoryInjections.memory_id, [...input.memory_ids])
147
+ )).all();
148
+ const existingValueRows = db.select({
149
+ injection_id: memoryValueEvents.injection_id
150
+ }).from(memoryValueEvents).where(and(
151
+ eq(memoryValueEvents.session_id, input.session_id),
152
+ eq(memoryValueEvents.event_type, "injected")
153
+ )).all();
154
+ const seen = new Set(existingValueRows.map((row) => row.injection_id).filter(Boolean));
155
+ let recorded = 0;
156
+ for (const row of rows) {
157
+ if (seen.has(row.id)) continue;
158
+ const memory = getMemory(db, row.memory_id);
159
+ recordMemoryValueEvent(db, {
160
+ memory_id: row.memory_id,
161
+ injection_id: row.id,
162
+ session_id: input.session_id,
163
+ repo: input.repo ?? memory?.repo ?? null,
164
+ event_type: "injected",
165
+ source: input.source ?? "system",
166
+ injected_tokens_estimate: estimateTokens(memory?.text),
167
+ evidence: {
168
+ matched_memory_text: memory?.text,
169
+ pack_tokens_estimate: input.pack_tokens_estimate
170
+ }
171
+ });
172
+ recorded += 1;
173
+ }
174
+ return recorded;
175
+ }
176
+ function recordOutcomeValueEvent(db, input) {
177
+ const memory = getMemory(db, input.memory_id);
178
+ const injection = input.injected ? db.select().from(memoryInjections).where(and(
179
+ eq(memoryInjections.memory_id, input.memory_id),
180
+ eq(memoryInjections.session_id, input.session_id)
181
+ )).get() : void 0;
182
+ const savedTokens = input.outcome === "followed" ? estimateTokens(memory?.text) : 0;
183
+ return recordMemoryValueEvent(db, {
184
+ memory_id: input.memory_id,
185
+ injection_id: injection?.id ?? null,
186
+ feedback_id: input.feedback_id,
187
+ session_id: input.session_id,
188
+ repo: memory?.repo ?? injection?.repo ?? null,
189
+ event_type: input.outcome,
190
+ source: input.source,
191
+ injected_tokens_estimate: 0,
192
+ saved_tokens_estimate: savedTokens,
193
+ evidence: {
194
+ context: input.context,
195
+ matched_memory_text: memory?.text
196
+ }
197
+ });
198
+ }
199
+ function detectAndRecordRetrievalMisses(db, input) {
200
+ if (input.correction_texts.length === 0) return [];
201
+ const injected = listInjectedMemoryIdsForSession(db, input.session_id);
202
+ const candidates = candidateMemoriesForMissDetection(db, input.repo ?? null);
203
+ const out = [];
204
+ for (const correctionText of input.correction_texts) {
205
+ const match = bestTextMatch(correctionText, candidates);
206
+ if (!match || match.score < 0.62) continue;
207
+ if (injected.has(match.memory.id)) {
208
+ out.push({ recorded: false, memory_id: match.memory.id, promoted: false });
209
+ continue;
210
+ }
211
+ let promoted = false;
212
+ if (match.memory.status === "candidate") {
213
+ promoted = promoteMemory(db, match.memory.id, "repeat_correction", {
214
+ type: "repeated_correction",
215
+ count: match.memory.repetition_count + 1,
216
+ sessions: [input.session_id],
217
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
218
+ });
219
+ }
220
+ recordMemoryValueEvent(db, {
221
+ memory_id: match.memory.id,
222
+ session_id: input.session_id,
223
+ repo: match.memory.repo ?? input.repo ?? null,
224
+ event_type: "retrieval_miss",
225
+ source: input.source,
226
+ saved_tokens_estimate: 0,
227
+ evidence: {
228
+ correction_text: correctionText,
229
+ query_text: input.prompt_text,
230
+ prompt_path: input.path,
231
+ matched_memory_text: match.memory.text,
232
+ injected_memory_ids: [...injected],
233
+ reason: promoted ? "matching candidate was repeated but not injected; promoted for future turns" : "matching memory existed but was not injected before the correction repeated"
234
+ }
235
+ });
236
+ out.push({ recorded: true, memory_id: match.memory.id, promoted });
237
+ }
238
+ return out;
239
+ }
240
+ function computeMemoryValueReport(db, opts = {}) {
241
+ const now = /* @__PURE__ */ new Date();
242
+ const start = opts.sinceIso ?? new Date(now.getTime() - 14 * 864e5).toISOString();
243
+ const end = now.toISOString();
244
+ const totals = db.select({
245
+ events_total: sql`count(*)`.as("events_total"),
246
+ injections: sql`sum(case when ${memoryValueEvents.event_type} = 'injected' then 1 else 0 end)`.as("injections"),
247
+ retrieval_misses: sql`sum(case when ${memoryValueEvents.event_type} = 'retrieval_miss' then 1 else 0 end)`.as("retrieval_misses"),
248
+ injected_tokens_estimate: sql`coalesce(sum(${memoryValueEvents.injected_tokens_estimate}), 0)`.as("injected_tokens_estimate"),
249
+ saved_tokens_estimate: sql`coalesce(sum(${memoryValueEvents.saved_tokens_estimate}), 0)`.as("saved_tokens_estimate")
250
+ }).from(memoryValueEvents).where(gte(memoryValueEvents.created_at, start)).get();
251
+ const outcomeRows = db.select({
252
+ outcome: memoryValueEvents.event_type,
253
+ count: sql`count(*)`.as("count")
254
+ }).from(memoryValueEvents).where(and(
255
+ gte(memoryValueEvents.created_at, start),
256
+ inArray(memoryValueEvents.event_type, ["followed", "overridden", "ignored", "contradicted"])
257
+ )).groupBy(memoryValueEvents.event_type).all();
258
+ const topRows = db.select({
259
+ memory_id: memoryValueEvents.memory_id,
260
+ text: memories.text,
261
+ saved_tokens_estimate: sql`coalesce(sum(${memoryValueEvents.saved_tokens_estimate}), 0)`.as("saved_tokens_estimate"),
262
+ followed: sql`sum(case when ${memoryValueEvents.event_type} = 'followed' then 1 else 0 end)`.as("followed")
263
+ }).from(memoryValueEvents).leftJoin(memories, eq(memoryValueEvents.memory_id, memories.id)).where(and(
264
+ gte(memoryValueEvents.created_at, start),
265
+ eq(memoryValueEvents.event_type, "followed")
266
+ )).groupBy(memoryValueEvents.memory_id, memories.text).orderBy(desc(sql`coalesce(sum(${memoryValueEvents.saved_tokens_estimate}), 0)`)).limit(5).all();
267
+ const outcomes = {};
268
+ for (const row of outcomeRows) outcomes[row.outcome] = row.count;
269
+ const injectedTokens = Number(totals?.injected_tokens_estimate ?? 0);
270
+ const savedTokens = Number(totals?.saved_tokens_estimate ?? 0);
271
+ return {
272
+ window_start: start,
273
+ window_end: end,
274
+ events_total: Number(totals?.events_total ?? 0),
275
+ injections: Number(totals?.injections ?? 0),
276
+ outcomes,
277
+ retrieval_misses: Number(totals?.retrieval_misses ?? 0),
278
+ injected_tokens_estimate: injectedTokens,
279
+ saved_tokens_estimate: savedTokens,
280
+ net_tokens_estimate: savedTokens - injectedTokens,
281
+ top_savers: topRows.filter((row) => row.memory_id && row.text).map((row) => ({
282
+ memory_id: row.memory_id,
283
+ text: row.text,
284
+ saved_tokens_estimate: Number(row.saved_tokens_estimate ?? 0),
285
+ followed: Number(row.followed ?? 0)
286
+ }))
287
+ };
288
+ }
289
+ function candidateMemoriesForMissDetection(db, repo) {
290
+ const repoMemories = repo ? queryMemories(db, { repo }) : [];
291
+ const globalMemories = queryMemories(db, { scope: "global" });
292
+ return [...repoMemories, ...globalMemories].filter(
293
+ (memory, index, rows) => (memory.status === "active" || memory.status === "candidate") && rows.findIndex((candidate) => candidate.id === memory.id) === index
294
+ );
295
+ }
296
+ function bestTextMatch(text, memoriesToCheck) {
297
+ let best = null;
298
+ for (const memory of memoriesToCheck) {
299
+ const score = jaccard(text, memory.text);
300
+ if (!best || score > best.score) best = { memory, score };
301
+ }
302
+ return best;
303
+ }
304
+ function jaccard(a, b) {
305
+ const wordsA = new Set(tokens(a));
306
+ const wordsB = new Set(tokens(b));
307
+ if (wordsA.size === 0 || wordsB.size === 0) return 0;
308
+ const intersection = [...wordsA].filter((word) => wordsB.has(word));
309
+ const union = /* @__PURE__ */ new Set([...wordsA, ...wordsB]);
310
+ return intersection.length / union.size;
311
+ }
312
+ function tokens(text) {
313
+ return text.toLowerCase().split(/[^a-z0-9]+/).filter((token) => token.length > 2);
314
+ }
315
+
316
+ export {
317
+ recordMemoryInjections,
318
+ listInjectedMemoryIdsForSession,
319
+ listPendingMemoryInjections,
320
+ resolveMemoryInjectionOutcome,
321
+ pathMatchesMemory,
322
+ toolCallTouchesMemory,
323
+ recordInjectionValueEvents,
324
+ recordOutcomeValueEvent,
325
+ detectAndRecordRetrievalMisses,
326
+ computeMemoryValueReport
327
+ };
328
+ //# sourceMappingURL=chunk-WC7S7BOP.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/models/memory-value.ts","../src/models/memory-injections.ts"],"sourcesContent":["import { and, desc, eq, gte, inArray, sql } from \"drizzle-orm\";\nimport { randomUUID } from \"node:crypto\";\nimport type { RecallDb } from \"../db/client.js\";\nimport { memories, memoryInjections, memoryValueEvents } from \"../db/schema.js\";\nimport type { ActivitySource, FeedbackOutcome, MemoryItem } from \"../types.js\";\nimport { getMemory, queryMemories, promoteMemory } from \"./memory.js\";\nimport { listInjectedMemoryIdsForSession } from \"./memory-injections.js\";\n\nexport type MemoryValueEventType =\n | \"injected\"\n | FeedbackOutcome\n | \"retrieval_miss\";\n\nexport interface MemoryValueEvidence {\n context?: string;\n query_text?: string;\n correction_text?: string;\n prompt_path?: string;\n reason?: string;\n matched_memory_text?: string;\n injected_memory_ids?: string[];\n pack_tokens_estimate?: number;\n}\n\nexport interface RecordMemoryValueEventInput {\n memory_id?: string | null;\n injection_id?: string | null;\n feedback_id?: string | null;\n session_id: string;\n repo?: string | null;\n event_type: MemoryValueEventType;\n source: ActivitySource;\n injected_tokens_estimate?: number;\n saved_tokens_estimate?: number;\n evidence?: MemoryValueEvidence;\n}\n\nexport function estimateTokens(text: string | null | undefined): number {\n const trimmed = text?.trim();\n if (!trimmed) return 0;\n return Math.max(1, Math.ceil(trimmed.length / 4));\n}\n\nexport function recordMemoryValueEvent(\n db: RecallDb,\n input: RecordMemoryValueEventInput,\n): string {\n const id = randomUUID();\n db.insert(memoryValueEvents)\n .values({\n id,\n memory_id: input.memory_id ?? null,\n injection_id: input.injection_id ?? null,\n feedback_id: input.feedback_id ?? null,\n session_id: input.session_id,\n repo: input.repo ?? null,\n event_type: input.event_type,\n source: input.source,\n injected_tokens_estimate: Math.max(0, Math.round(input.injected_tokens_estimate ?? 0)),\n saved_tokens_estimate: Math.max(0, Math.round(input.saved_tokens_estimate ?? 0)),\n evidence: (input.evidence ?? {}) as any,\n created_at: new Date().toISOString(),\n })\n .run();\n return id;\n}\n\nexport function recordInjectionValueEvents(\n db: RecallDb,\n input: {\n memory_ids: readonly string[];\n session_id?: string;\n repo?: string | null;\n pack_tokens_estimate?: number;\n source?: ActivitySource;\n },\n): number {\n if (!input.session_id || input.memory_ids.length === 0) return 0;\n\n const rows = db.select({\n id: memoryInjections.id,\n memory_id: memoryInjections.memory_id,\n })\n .from(memoryInjections)\n .where(and(\n eq(memoryInjections.session_id, input.session_id),\n inArray(memoryInjections.memory_id, [...input.memory_ids]),\n ))\n .all();\n\n const existingValueRows = db.select({\n injection_id: memoryValueEvents.injection_id,\n })\n .from(memoryValueEvents)\n .where(and(\n eq(memoryValueEvents.session_id, input.session_id),\n eq(memoryValueEvents.event_type, \"injected\"),\n ))\n .all();\n const seen = new Set(existingValueRows.map((row) => row.injection_id).filter(Boolean));\n\n let recorded = 0;\n for (const row of rows) {\n if (seen.has(row.id)) continue;\n const memory = getMemory(db, row.memory_id);\n recordMemoryValueEvent(db, {\n memory_id: row.memory_id,\n injection_id: row.id,\n session_id: input.session_id,\n repo: input.repo ?? memory?.repo ?? null,\n event_type: \"injected\",\n source: input.source ?? \"system\",\n injected_tokens_estimate: estimateTokens(memory?.text),\n evidence: {\n matched_memory_text: memory?.text,\n pack_tokens_estimate: input.pack_tokens_estimate,\n },\n });\n recorded += 1;\n }\n return recorded;\n}\n\nexport function recordOutcomeValueEvent(\n db: RecallDb,\n input: {\n memory_id: string;\n session_id: string;\n injected: boolean;\n outcome: FeedbackOutcome;\n feedback_id: string;\n context?: string;\n source: ActivitySource;\n },\n): string {\n const memory = getMemory(db, input.memory_id);\n const injection = input.injected\n ? db.select().from(memoryInjections)\n .where(and(\n eq(memoryInjections.memory_id, input.memory_id),\n eq(memoryInjections.session_id, input.session_id),\n ))\n .get()\n : undefined;\n\n const savedTokens = input.outcome === \"followed\"\n ? estimateTokens(memory?.text)\n : 0;\n\n return recordMemoryValueEvent(db, {\n memory_id: input.memory_id,\n injection_id: injection?.id ?? null,\n feedback_id: input.feedback_id,\n session_id: input.session_id,\n repo: memory?.repo ?? injection?.repo ?? null,\n event_type: input.outcome,\n source: input.source,\n injected_tokens_estimate: 0,\n saved_tokens_estimate: savedTokens,\n evidence: {\n context: input.context,\n matched_memory_text: memory?.text,\n },\n });\n}\n\nexport interface RetrievalMissResult {\n recorded: boolean;\n memory_id: string | null;\n promoted: boolean;\n}\n\nexport function detectAndRecordRetrievalMisses(\n db: RecallDb,\n input: {\n correction_texts: readonly string[];\n prompt_text: string;\n session_id: string;\n repo?: string | null;\n path?: string;\n source: ActivitySource;\n },\n): RetrievalMissResult[] {\n if (input.correction_texts.length === 0) return [];\n\n const injected = listInjectedMemoryIdsForSession(db, input.session_id);\n const candidates = candidateMemoriesForMissDetection(db, input.repo ?? null);\n const out: RetrievalMissResult[] = [];\n\n for (const correctionText of input.correction_texts) {\n const match = bestTextMatch(correctionText, candidates);\n if (!match || match.score < 0.62) continue;\n if (injected.has(match.memory.id)) {\n out.push({ recorded: false, memory_id: match.memory.id, promoted: false });\n continue;\n }\n\n let promoted = false;\n if (match.memory.status === \"candidate\") {\n promoted = promoteMemory(db, match.memory.id, \"repeat_correction\", {\n type: \"repeated_correction\",\n count: match.memory.repetition_count + 1,\n sessions: [input.session_id],\n timestamp: new Date().toISOString(),\n });\n }\n\n recordMemoryValueEvent(db, {\n memory_id: match.memory.id,\n session_id: input.session_id,\n repo: match.memory.repo ?? input.repo ?? null,\n event_type: \"retrieval_miss\",\n source: input.source,\n saved_tokens_estimate: 0,\n evidence: {\n correction_text: correctionText,\n query_text: input.prompt_text,\n prompt_path: input.path,\n matched_memory_text: match.memory.text,\n injected_memory_ids: [...injected],\n reason: promoted\n ? \"matching candidate was repeated but not injected; promoted for future turns\"\n : \"matching memory existed but was not injected before the correction repeated\",\n },\n });\n\n out.push({ recorded: true, memory_id: match.memory.id, promoted });\n }\n\n return out;\n}\n\nexport interface MemoryValueReport {\n window_start: string;\n window_end: string;\n events_total: number;\n injections: number;\n outcomes: Record<string, number>;\n retrieval_misses: number;\n injected_tokens_estimate: number;\n saved_tokens_estimate: number;\n net_tokens_estimate: number;\n top_savers: Array<{\n memory_id: string;\n text: string;\n saved_tokens_estimate: number;\n followed: number;\n }>;\n}\n\nexport function computeMemoryValueReport(\n db: RecallDb,\n opts: { sinceIso?: string } = {},\n): MemoryValueReport {\n const now = new Date();\n const start = opts.sinceIso ?? new Date(now.getTime() - 14 * 86_400_000).toISOString();\n const end = now.toISOString();\n\n const totals = db.select({\n events_total: sql<number>`count(*)`.as(\"events_total\"),\n injections: sql<number>`sum(case when ${memoryValueEvents.event_type} = 'injected' then 1 else 0 end)`.as(\"injections\"),\n retrieval_misses: sql<number>`sum(case when ${memoryValueEvents.event_type} = 'retrieval_miss' then 1 else 0 end)`.as(\"retrieval_misses\"),\n injected_tokens_estimate: sql<number>`coalesce(sum(${memoryValueEvents.injected_tokens_estimate}), 0)`.as(\"injected_tokens_estimate\"),\n saved_tokens_estimate: sql<number>`coalesce(sum(${memoryValueEvents.saved_tokens_estimate}), 0)`.as(\"saved_tokens_estimate\"),\n })\n .from(memoryValueEvents)\n .where(gte(memoryValueEvents.created_at, start))\n .get();\n\n const outcomeRows = db.select({\n outcome: memoryValueEvents.event_type,\n count: sql<number>`count(*)`.as(\"count\"),\n })\n .from(memoryValueEvents)\n .where(and(\n gte(memoryValueEvents.created_at, start),\n inArray(memoryValueEvents.event_type, [\"followed\", \"overridden\", \"ignored\", \"contradicted\"]),\n ))\n .groupBy(memoryValueEvents.event_type)\n .all();\n\n const topRows = db.select({\n memory_id: memoryValueEvents.memory_id,\n text: memories.text,\n saved_tokens_estimate: sql<number>`coalesce(sum(${memoryValueEvents.saved_tokens_estimate}), 0)`.as(\"saved_tokens_estimate\"),\n followed: sql<number>`sum(case when ${memoryValueEvents.event_type} = 'followed' then 1 else 0 end)`.as(\"followed\"),\n })\n .from(memoryValueEvents)\n .leftJoin(memories, eq(memoryValueEvents.memory_id, memories.id))\n .where(and(\n gte(memoryValueEvents.created_at, start),\n eq(memoryValueEvents.event_type, \"followed\"),\n ))\n .groupBy(memoryValueEvents.memory_id, memories.text)\n .orderBy(desc(sql`coalesce(sum(${memoryValueEvents.saved_tokens_estimate}), 0)`))\n .limit(5)\n .all();\n\n const outcomes: Record<string, number> = {};\n for (const row of outcomeRows) outcomes[row.outcome] = row.count;\n\n const injectedTokens = Number(totals?.injected_tokens_estimate ?? 0);\n const savedTokens = Number(totals?.saved_tokens_estimate ?? 0);\n\n return {\n window_start: start,\n window_end: end,\n events_total: Number(totals?.events_total ?? 0),\n injections: Number(totals?.injections ?? 0),\n outcomes,\n retrieval_misses: Number(totals?.retrieval_misses ?? 0),\n injected_tokens_estimate: injectedTokens,\n saved_tokens_estimate: savedTokens,\n net_tokens_estimate: savedTokens - injectedTokens,\n top_savers: topRows\n .filter((row) => row.memory_id && row.text)\n .map((row) => ({\n memory_id: row.memory_id!,\n text: row.text!,\n saved_tokens_estimate: Number(row.saved_tokens_estimate ?? 0),\n followed: Number(row.followed ?? 0),\n })),\n };\n}\n\nfunction candidateMemoriesForMissDetection(\n db: RecallDb,\n repo: string | null,\n): MemoryItem[] {\n const repoMemories = repo ? queryMemories(db, { repo }) : [];\n const globalMemories = queryMemories(db, { scope: \"global\" });\n return [...repoMemories, ...globalMemories]\n .filter((memory, index, rows) =>\n (memory.status === \"active\" || memory.status === \"candidate\") &&\n rows.findIndex((candidate) => candidate.id === memory.id) === index\n );\n}\n\nfunction bestTextMatch(\n text: string,\n memoriesToCheck: readonly MemoryItem[],\n): { memory: MemoryItem; score: number } | null {\n let best: { memory: MemoryItem; score: number } | null = null;\n for (const memory of memoriesToCheck) {\n const score = jaccard(text, memory.text);\n if (!best || score > best.score) best = { memory, score };\n }\n return best;\n}\n\nfunction jaccard(a: string, b: string): number {\n const wordsA = new Set(tokens(a));\n const wordsB = new Set(tokens(b));\n if (wordsA.size === 0 || wordsB.size === 0) return 0;\n const intersection = [...wordsA].filter((word) => wordsB.has(word));\n const union = new Set([...wordsA, ...wordsB]);\n return intersection.length / union.size;\n}\n\nfunction tokens(text: string): string[] {\n return text\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((token) => token.length > 2);\n}\n","import { and, asc, eq, gt, isNull } from \"drizzle-orm\";\nimport { randomUUID } from \"node:crypto\";\nimport type { RecallDb } from \"../db/client.js\";\nimport { memoryInjections } from \"../db/schema.js\";\nimport type { FeedbackOutcome, MemoryInjection, MemoryItem } from \"../types.js\";\nimport { getMemory } from \"./memory.js\";\nimport type { RecentToolCall } from \"../agents/types.js\";\n\ntype MemoryInjectionRow = typeof memoryInjections.$inferSelect;\n\nexport function recordMemoryInjections(\n db: RecallDb,\n input: {\n memory_ids: readonly string[];\n session_id?: string;\n repo?: string | null;\n },\n): number {\n if (!input.session_id || input.memory_ids.length === 0) return 0;\n\n const injectedAt = new Date().toISOString();\n let inserted = 0;\n for (const memoryId of input.memory_ids) {\n const result = db.insert(memoryInjections)\n .values({\n id: randomUUID(),\n memory_id: memoryId,\n session_id: input.session_id,\n repo: input.repo ?? null,\n injected_at: injectedAt,\n outcome: null,\n outcome_at: null,\n })\n .onConflictDoNothing({\n target: [memoryInjections.memory_id, memoryInjections.session_id],\n })\n .run();\n inserted += Number(result.changes ?? 0);\n }\n\n return inserted;\n}\n\nexport function listInjectedMemoryIdsForSession(\n db: RecallDb,\n sessionId: string,\n): Set<string> {\n const rows = db.select({ memory_id: memoryInjections.memory_id })\n .from(memoryInjections)\n .where(eq(memoryInjections.session_id, sessionId))\n .all();\n return new Set(rows.map((row) => row.memory_id));\n}\n\nexport function listPendingMemoryInjections(\n db: RecallDb,\n sessionId: string,\n): Array<MemoryInjection & { memory: MemoryItem | null }> {\n const rows = db.select()\n .from(memoryInjections)\n .where(and(\n eq(memoryInjections.session_id, sessionId),\n isNull(memoryInjections.outcome),\n ))\n .orderBy(asc(memoryInjections.injected_at))\n .all();\n\n return rows.map((row) => ({\n ...rowToMemoryInjection(row),\n memory: getMemory(db, row.memory_id) ?? null,\n }));\n}\n\nexport function resolveMemoryInjectionOutcome(\n db: RecallDb,\n memoryId: string,\n sessionId: string,\n outcome: FeedbackOutcome,\n): boolean {\n const outcomeAt = new Date().toISOString();\n const result = db.update(memoryInjections)\n .set({\n outcome,\n outcome_at: outcomeAt,\n })\n .where(and(\n eq(memoryInjections.memory_id, memoryId),\n eq(memoryInjections.session_id, sessionId),\n isNull(memoryInjections.outcome),\n ))\n .run();\n\n return Number(result.changes ?? 0) > 0;\n}\n\nexport function listToolCallsSince(\n db: RecallDb,\n sessionId: string,\n injectedAt: string,\n): RecentToolCall[] {\n const rows = db.select()\n .from(memoryInjections)\n .where(gt(memoryInjections.injected_at, injectedAt))\n .all();\n void rows;\n return [];\n}\n\nexport function pathMatchesMemory(mem: MemoryItem, targetPath?: string): boolean {\n // Keep in sync with compiler/context.ts pathMatches(): repo, team, and\n // global memories are path-independent. Omitting global here meant global\n // rules could never resolve as followed/relevant after injection.\n if (!targetPath) return mem.scope === \"repo\" || mem.scope === \"team\" || mem.scope === \"global\";\n if (mem.scope === \"repo\" || mem.scope === \"team\" || mem.scope === \"global\") return true;\n if (!mem.path_scope) return true;\n\n const pattern = mem.path_scope;\n if (pattern.endsWith(\"**\")) {\n return targetPath.startsWith(pattern.slice(0, -2));\n }\n if (pattern.includes(\"*\")) {\n const regex = new RegExp(\n \"^\" + pattern.replace(/\\*/g, \"[^/]*\").replace(/\\*\\*/g, \".*\") + \"$\",\n );\n return regex.test(targetPath);\n }\n return targetPath.startsWith(pattern);\n}\n\nexport function toolCallTouchesMemory(\n mem: MemoryItem,\n toolCall: RecentToolCall,\n): boolean {\n if (toolCall.path && pathMatchesMemory(mem, toolCall.path)) return true;\n if (toolCall.input_summary) {\n const inferredPath = extractPath(toolCall.input_summary);\n if (inferredPath && pathMatchesMemory(mem, inferredPath)) return true;\n }\n return mem.scope === \"repo\" || mem.scope === \"team\" || mem.scope === \"global\";\n}\n\nfunction rowToMemoryInjection(row: MemoryInjectionRow): MemoryInjection {\n return {\n id: row.id,\n memory_id: row.memory_id,\n session_id: row.session_id,\n repo: row.repo,\n injected_at: row.injected_at,\n outcome: row.outcome,\n outcome_at: row.outcome_at,\n };\n}\n\nfunction extractPath(text: string): string | undefined {\n const match = text.match(\n /\\b((?:src|lib|app|components|utils|test|spec)\\/[\\w./-]+|[\\w./-]+\\.(?:ts|tsx|js|jsx|py|rs|go|swift|java|rb|json|toml|ya?ml))\\b/,\n );\n return match?.[1];\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,cAAAA,mBAAkB;;;ACA3B,SAAS,kBAAkB;AASpB,SAAS,uBACd,IACA,OAKQ;AACR,MAAI,CAAC,MAAM,cAAc,MAAM,WAAW,WAAW,EAAG,QAAO;AAE/D,QAAM,cAAa,oBAAI,KAAK,GAAE,YAAY;AAC1C,MAAI,WAAW;AACf,aAAW,YAAY,MAAM,YAAY;AACvC,UAAM,SAAS,GAAG,OAAO,gBAAgB,EACtC,OAAO;AAAA,MACN,IAAI,WAAW;AAAA,MACf,WAAW;AAAA,MACX,YAAY,MAAM;AAAA,MAClB,MAAM,MAAM,QAAQ;AAAA,MACpB,aAAa;AAAA,MACb,SAAS;AAAA,MACT,YAAY;AAAA,IACd,CAAC,EACA,oBAAoB;AAAA,MACnB,QAAQ,CAAC,iBAAiB,WAAW,iBAAiB,UAAU;AAAA,IAClE,CAAC,EACA,IAAI;AACP,gBAAY,OAAO,OAAO,WAAW,CAAC;AAAA,EACxC;AAEA,SAAO;AACT;AAEO,SAAS,gCACd,IACA,WACa;AACb,QAAM,OAAO,GAAG,OAAO,EAAE,WAAW,iBAAiB,UAAU,CAAC,EAC7D,KAAK,gBAAgB,EACrB,MAAM,GAAG,iBAAiB,YAAY,SAAS,CAAC,EAChD,IAAI;AACP,SAAO,IAAI,IAAI,KAAK,IAAI,CAAC,QAAQ,IAAI,SAAS,CAAC;AACjD;AAEO,SAAS,4BACd,IACA,WACwD;AACxD,QAAM,OAAO,GAAG,OAAO,EACpB,KAAK,gBAAgB,EACrB,MAAM;AAAA,IACL,GAAG,iBAAiB,YAAY,SAAS;AAAA,IACzC,OAAO,iBAAiB,OAAO;AAAA,EACjC,CAAC,EACA,QA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IAAI,CAAC,GAAG,QAAQ,GAAG,MAAM,CAAC;AAC5C,SAAO,aAAa,SAAS,MAAM;AACrC;AAEA,SAAS,OAAO,MAAwB;AACtC,SAAO,KACJ,YAAY,EACZ,MAAM,YAAY,EAClB,OAAO,CAAC,UAAU,MAAM,SAAS,CAAC;AACvC;","names":["randomUUID","randomUUID"]}
@@ -5,15 +5,17 @@ import {
5
5
  planGlobalizeCrossRepo,
6
6
  planPromoteRepeats,
7
7
  planRejectFragments,
8
+ planRejectInvalidScopes,
9
+ planRejectTestFixtureRepos,
8
10
  planSuppressCommands,
9
11
  qualityReasons,
10
12
  revertCleanupRun,
11
13
  runDeterministicCleanup
12
- } from "./chunk-DRHHOFBX.js";
13
- import "./chunk-3OYO5BW3.js";
14
- import "./chunk-37K4DPRI.js";
15
- import "./chunk-JRIM7VBY.js";
16
- import "./chunk-QDA5M3AJ.js";
14
+ } from "./chunk-DYAQ4RKX.js";
15
+ import "./chunk-4VBHVY3D.js";
16
+ import "./chunk-BJTLWRZH.js";
17
+ import "./chunk-A4ES3H4Y.js";
18
+ import "./chunk-G5IAOZAL.js";
17
19
  import "./chunk-DNFKAHS6.js";
18
20
  import "./chunk-4CV4JOE5.js";
19
21
  export {
@@ -23,9 +25,11 @@ export {
23
25
  planGlobalizeCrossRepo,
24
26
  planPromoteRepeats,
25
27
  planRejectFragments,
28
+ planRejectInvalidScopes,
29
+ planRejectTestFixtureRepos,
26
30
  planSuppressCommands,
27
31
  qualityReasons,
28
32
  revertCleanupRun,
29
33
  runDeterministicCleanup
30
34
  };
31
- //# sourceMappingURL=cleanup-XOIYUPHS.js.map
35
+ //# sourceMappingURL=cleanup-MPSAZNDH.js.map
package/dist/cli.js CHANGED
@@ -22,7 +22,7 @@ import {
22
22
  readCodexSessionStartInputFromStdin,
23
23
  readCodexToolInputFromStdin,
24
24
  restoreBackup
25
- } from "./chunk-5E3KREDH.js";
25
+ } from "./chunk-ITU4GQDL.js";
26
26
  import {
27
27
  RECALL_DB_USER_VERSION,
28
28
  compileContext,
@@ -58,10 +58,13 @@ import {
58
58
  runRetrievalEval,
59
59
  scanAndStore,
60
60
  searchHistorySnippets,
61
+ signalOutcomeFallback,
61
62
  startEvalSession,
62
63
  togglePolicy,
63
64
  writeRepoContextArtifact
64
- } from "./chunk-4LZMHQ6Y.js";
65
+ } from "./chunk-VPZ4OZKK.js";
66
+ import "./chunk-WC7S7BOP.js";
67
+ import "./chunk-PUMEMKGF.js";
65
68
  import {
66
69
  autoResolveContradictions,
67
70
  computeAllHealthScores,
@@ -79,7 +82,7 @@ import {
79
82
  recordAudit,
80
83
  resolveContradiction,
81
84
  rollbackMemory
82
- } from "./chunk-DRHHOFBX.js";
85
+ } from "./chunk-DYAQ4RKX.js";
83
86
  import {
84
87
  confirmMemory,
85
88
  createMemory,
@@ -88,8 +91,8 @@ import {
88
91
  listRepos,
89
92
  queryMemories,
90
93
  rejectMemory
91
- } from "./chunk-3OYO5BW3.js";
92
- import "./chunk-37K4DPRI.js";
94
+ } from "./chunk-4VBHVY3D.js";
95
+ import "./chunk-BJTLWRZH.js";
93
96
  import {
94
97
  bootstrapEmbeddings,
95
98
  ensureEmbeddingProviderReady,
@@ -102,13 +105,13 @@ import {
102
105
  searchMemoryFtsIndex,
103
106
  semanticSearch,
104
107
  verifyEmbeddings
105
- } from "./chunk-JRIM7VBY.js";
108
+ } from "./chunk-A4ES3H4Y.js";
106
109
  import {
107
110
  eq,
108
111
  gt,
109
112
  memories,
110
113
  syncState
111
- } from "./chunk-QDA5M3AJ.js";
114
+ } from "./chunk-G5IAOZAL.js";
112
115
  import {
113
116
  init_keychain,
114
117
  keychain_exports
@@ -130,7 +133,7 @@ import {
130
133
  createHttpServer,
131
134
  createMcpServer
132
135
  } from "@universalmemoryprotocol/core";
133
- import { RecallStore } from "@universalmemoryprotocol/core/adapters/recall";
136
+ import { RecallStore, fromAmpId } from "@universalmemoryprotocol/core/adapters/recall";
134
137
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
135
138
 
136
139
  // src/ump/backend.ts
@@ -239,10 +242,29 @@ function makeRecallBackend(db) {
239
242
  }
240
243
 
241
244
  // src/ump/serve.ts
242
- async function runUmpServer(opts = {}) {
243
- const db = initDb();
245
+ function createRecallUmpServer(db, opts = {}) {
244
246
  const key = generateKeyPair();
245
247
  const owner = key.did;
248
+ const server = new UmpServer({
249
+ name: "recall",
250
+ version: "ump-0.1",
251
+ conformance: "L1",
252
+ store: new RecallStore(makeRecallBackend(db), { owner, smart: opts.smart }),
253
+ key,
254
+ onFeedback: async (req) => {
255
+ signalOutcomeFallback(db, {
256
+ memory_id: fromAmpId(req.id),
257
+ session_id: req.session ?? `ump:${process.pid}`,
258
+ injected: true,
259
+ outcome: req.outcome,
260
+ context: "ump.feedback"
261
+ }, "mcp:ump");
262
+ }
263
+ });
264
+ return { server, owner };
265
+ }
266
+ async function runUmpServer(opts = {}) {
267
+ const db = initDb();
246
268
  const embedCfg = loadEmbeddingConfigFromEnv();
247
269
  if (embedCfg) {
248
270
  try {
@@ -259,13 +281,7 @@ async function runUmpServer(opts = {}) {
259
281
  );
260
282
  }
261
283
  }
262
- const server = new UmpServer({
263
- name: "recall",
264
- version: "ump-0.1",
265
- conformance: "L1",
266
- store: new RecallStore(makeRecallBackend(db), { owner, smart: opts.smart }),
267
- key
268
- });
284
+ const { server, owner } = createRecallUmpServer(db, opts);
269
285
  if (opts.http) {
270
286
  createHttpServer(server, { wellKnown: { owner } }).listen(opts.http, () => {
271
287
  process.stderr.write(
@@ -2747,6 +2763,7 @@ program.command("compile").description("Compile active memories into injection p
2747
2763
  const result = opts.query || opts.includeCandidates ? await compileContextHybrid(db, {
2748
2764
  repo: opts.repo,
2749
2765
  path: opts.path,
2766
+ session_id: opts.session,
2750
2767
  query_text: opts.query,
2751
2768
  config: {
2752
2769
  ...opts.threshold ? { confidence_threshold: parseFloat(opts.threshold) } : {},
@@ -2755,6 +2772,7 @@ program.command("compile").description("Compile active memories into injection p
2755
2772
  }) : compileContext(db, {
2756
2773
  repo: opts.repo,
2757
2774
  path: opts.path,
2775
+ session_id: opts.session,
2758
2776
  config: opts.threshold ? { confidence_threshold: parseFloat(opts.threshold) } : {}
2759
2777
  });
2760
2778
  createActivityEvent(db, {
@@ -3470,13 +3488,13 @@ uiCmd.command("status").description("Show WebUI status").option("--daemon-port <
3470
3488
  var graphCmd = program.command("graph").description("Inspect and rebuild the knowledge graph (entities + relations)");
3471
3489
  graphCmd.command("stats").description("Show entity/relation counts").action(async () => {
3472
3490
  const db = initDb();
3473
- const { countEntities, countRelations } = await import("./store-2BPQPOOZ.js");
3491
+ const { countEntities, countRelations } = await import("./store-KU5H2RA2.js");
3474
3492
  console.log(`entities: ${countEntities(db)}`);
3475
3493
  console.log(`relations: ${countRelations(db)}`);
3476
3494
  });
3477
3495
  graphCmd.command("backfill").description("Run the heuristic extractor over every active memory (idempotent)").option("--repo <repo>", "Limit to a single repo").option("--limit <n>", "Cap rows processed", "10000").action(async (opts) => {
3478
3496
  const db = initDb();
3479
- const { ingestMemoryHeuristic } = await import("./ingest-QOZDSJOA.js");
3497
+ const { ingestMemoryHeuristic } = await import("./ingest-KVLFQ6J7.js");
3480
3498
  const rows = queryMemories(db, {
3481
3499
  repo: opts.repo,
3482
3500
  status: "active",
@@ -3495,7 +3513,7 @@ graphCmd.command("backfill").description("Run the heuristic extractor over every
3495
3513
  });
3496
3514
  graphCmd.command("entities").description("List entities").option("--repo <repo>", "Filter by repo").option("--kind <kind>", "Filter by entity kind").option("--search <q>", "Substring filter on name").option("--limit <n>", "Max rows", "50").action(async (opts) => {
3497
3515
  const db = initDb();
3498
- const { listEntities } = await import("./store-2BPQPOOZ.js");
3516
+ const { listEntities } = await import("./store-KU5H2RA2.js");
3499
3517
  const rows = listEntities(db, {
3500
3518
  repo: opts.repo,
3501
3519
  kind: opts.kind,
@@ -3514,8 +3532,8 @@ graphCmd.command("entities").description("List entities").option("--repo <repo>"
3514
3532
  });
3515
3533
  graphCmd.command("query <query...>").description("Run graph-aware retrieval for a query").option("--repo <repo>", "Restrict to repo").option("--hops <n>", "Graph hops", "2").option("--limit <n>", "Max hits", "10").action(async (queryTokens, opts) => {
3516
3534
  const db = initDb();
3517
- const { graphQuery } = await import("./retrieval-PQE7OHHJ.js");
3518
- const { loadEmbeddingConfigFromEnv: loadEmbeddingConfigFromEnv2 } = await import("./embeddings-GKNH2E3N.js");
3535
+ const { graphQuery } = await import("./retrieval-27YV546Y.js");
3536
+ const { loadEmbeddingConfigFromEnv: loadEmbeddingConfigFromEnv2 } = await import("./embeddings-MNNECV6B.js");
3519
3537
  const embeddingConfig = loadEmbeddingConfigFromEnv2();
3520
3538
  const result = await graphQuery(db, queryTokens.join(" "), embeddingConfig, {
3521
3539
  repo: opts.repo,
@@ -3531,7 +3549,7 @@ graphCmd.command("query <query...>").description("Run graph-aware retrieval for
3531
3549
  });
3532
3550
  var maintenanceCmd = program.command("maintenance").description("Inspect and manage the delegated maintenance task queue");
3533
3551
  maintenanceCmd.command("stats").description("Show backlog counts, completion stats, and mean latency").action(async () => {
3534
- const { getTaskStats } = await import("./tasks-IFHV6EBT.js");
3552
+ const { getTaskStats } = await import("./tasks-SCYA2PJJ.js");
3535
3553
  const db = initDb();
3536
3554
  const stats = getTaskStats(db);
3537
3555
  console.log(`Total tasks: ${stats.total}`);
@@ -3557,7 +3575,7 @@ maintenanceCmd.command("stats").description("Show backlog counts, completion sta
3557
3575
  }
3558
3576
  });
3559
3577
  maintenanceCmd.command("list").description("List tasks (default: pending)").option("-s, --status <status>", "pending|claimed|completed|abandoned", "pending").option("-k, --kind <kind>", "Filter by kind").option("-r, --repo <repo>", "Filter by repo").option("-n, --limit <n>", "Max entries", "20").action(async (opts) => {
3560
- const { listTasks } = await import("./tasks-IFHV6EBT.js");
3578
+ const { listTasks } = await import("./tasks-SCYA2PJJ.js");
3561
3579
  const db = initDb();
3562
3580
  const tasks = listTasks(db, {
3563
3581
  status: opts.status,
@@ -3579,7 +3597,7 @@ maintenanceCmd.command("list").description("List tasks (default: pending)").opti
3579
3597
  }
3580
3598
  });
3581
3599
  maintenanceCmd.command("drop").description("Delete a task by id (or id prefix)").argument("<task-id>", "Task id or prefix").action(async (taskIdArg) => {
3582
- const { deleteTask, listTasks } = await import("./tasks-IFHV6EBT.js");
3600
+ const { deleteTask, listTasks } = await import("./tasks-SCYA2PJJ.js");
3583
3601
  const db = initDb();
3584
3602
  const all = listTasks(db, { limit: 1e4 });
3585
3603
  const matches = all.filter((t) => t.id === taskIdArg || t.id.startsWith(taskIdArg));
@@ -3685,8 +3703,8 @@ credentialsCmd.command("clear").description("Remove provider credentials from th
3685
3703
  else console.log(`No ${provider} credentials found in Keychain.`);
3686
3704
  });
3687
3705
  maintenanceCmd.command("dispatch").description("Run the daemon-owned dispatcher once against pending maintenance tasks (requires a configured LLM provider)").option("--provider <provider>", "openai|anthropic|azure-openai (defaults to whichever is configured)").option("--model <model>", "Model override").option("--kind <kind>", "Restrict to a single task kind (repeatable)", (value, acc = []) => [...acc, value], []).option("--repo <repo>", "Restrict to a single repo").option("--max <n>", "Max tasks to run this round", "5").option("--dry-run", "Show which tasks would be dispatched; do not call the LLM").option("--preview", "Show the actual prompts that would be sent (no provider needed; no LLM call)").option("--json", "Emit the raw JSON report").action(async (opts) => {
3688
- const { dispatchPendingTasks, formatDispatchReport, buildPrompt } = await import("./dispatcher-43DWN3ZP.js");
3689
- const { listTasks } = await import("./tasks-IFHV6EBT.js");
3706
+ const { dispatchPendingTasks, formatDispatchReport, buildPrompt } = await import("./dispatcher-RCCPGNDO.js");
3707
+ const { listTasks } = await import("./tasks-SCYA2PJJ.js");
3690
3708
  const db = initDb();
3691
3709
  if (opts.preview) {
3692
3710
  const pending = listTasks(db, {
@@ -3742,8 +3760,8 @@ ${p.prompt.max_output_tokens}
3742
3760
  }
3743
3761
  console.log(formatDispatchReport(report));
3744
3762
  });
3745
- maintenanceCmd.command("cleanup").description("Run deterministic, LLM-free cleanup: exact-text dedupe, fragment rejection, repeat-correction promotion").option("--apply", "Persist changes (default is dry-run)").option("--only <action>", "Restrict to one action: dedupe_exact_merge|reject_fragment_candidate|promote_repeat_correction").option("--revert <run-id>", "Revert a previous cleanup run (id or 8-char prefix)").option("--list", "List recent cleanup runs").option("--json", "Emit the raw JSON report").action(async (opts) => {
3746
- const { runDeterministicCleanup, formatCleanupReport, revertCleanupRun, listCleanupRuns } = await import("./cleanup-XOIYUPHS.js");
3763
+ maintenanceCmd.command("cleanup").description("Run deterministic, LLM-free cleanup for duplicate, low-quality, stale, and mis-scoped memories").option("--apply", "Persist changes (default is dry-run)").option("--only <action>", "Restrict to one action: dedupe_exact_merge|reject_fragment_candidate|promote_repeat_correction|suppress_unproductive_command|globalize_cross_repo|reject_test_fixture_repo|reject_invalid_scope").option("--revert <run-id>", "Revert a previous cleanup run (id or 8-char prefix)").option("--list", "List recent cleanup runs").option("--json", "Emit the raw JSON report").action(async (opts) => {
3764
+ const { runDeterministicCleanup, formatCleanupReport, revertCleanupRun, listCleanupRuns } = await import("./cleanup-MPSAZNDH.js");
3747
3765
  const db = initDb();
3748
3766
  if (opts.list) {
3749
3767
  const runs = listCleanupRuns(db);
@@ -3797,7 +3815,7 @@ maintenanceCmd.command("quality").description("Show injection outcome distributi
3797
3815
  recordQualitySnapshot,
3798
3816
  listQualitySnapshots,
3799
3817
  diffQualitySnapshots
3800
- } = await import("./quality-2JOLSIC3.js");
3818
+ } = await import("./quality-OXFQ7JXM.js");
3801
3819
  const db = initDb();
3802
3820
  if (opts.history) {
3803
3821
  const snaps = listQualitySnapshots(db);
@@ -3847,7 +3865,7 @@ maintenanceCmd.command("quality").description("Show injection outcome distributi
3847
3865
  console.log(formatQualityReport(report));
3848
3866
  });
3849
3867
  maintenanceCmd.command("usage").description("Summarize LLM API usage (tokens, cost) across recent maintenance runs").option("--since <iso>", "Window start (default: last 30 days)").option("--limit <n>", "Recent-call rows to show", "10").option("--json", "Emit raw JSON summary").action(async (opts) => {
3850
- const { summarizeUsage, formatUsageReport } = await import("./usage-YBS74UEU.js");
3868
+ const { summarizeUsage, formatUsageReport } = await import("./usage-VVXTCJHT.js");
3851
3869
  const db = initDb();
3852
3870
  const summary = summarizeUsage(db, {
3853
3871
  sinceIso: opts.since,