@edihasaj/recall 1.4.0 → 1.4.1

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 (44) hide show
  1. package/dist/{chunk-7Q5CBVUT.js → chunk-4UHRAQFG.js} +34 -13
  2. package/dist/{chunk-7Q5CBVUT.js.map → chunk-4UHRAQFG.js.map} +1 -1
  3. package/dist/{chunk-53GKSF42.js → chunk-7CFX774S.js} +9 -9
  4. package/dist/{chunk-MMYLXICL.js → chunk-AFD43EOE.js} +2 -2
  5. package/dist/{chunk-UWERS646.js → chunk-LWY4Z626.js} +3 -3
  6. package/dist/{chunk-JO5LRCA2.js → chunk-NAYFAUSM.js} +149 -6
  7. package/dist/chunk-NAYFAUSM.js.map +1 -0
  8. package/dist/{chunk-6QFOCUEJ.js → chunk-T274LVWB.js} +104 -18
  9. package/dist/chunk-T274LVWB.js.map +1 -0
  10. package/dist/{chunk-65XK27KK.js → chunk-TA4WSV6A.js} +46 -155
  11. package/dist/chunk-TA4WSV6A.js.map +1 -0
  12. package/dist/{chunk-JKWK73GY.js → chunk-ZBQGZCFL.js} +3 -3
  13. package/dist/chunk-ZBQGZCFL.js.map +1 -0
  14. package/dist/{chunk-JSTZKFZR.js → chunk-ZXCKMEJA.js} +7 -7
  15. package/dist/{cleanup-RHNBHBNP.js → cleanup-RTL2UETA.js} +4 -4
  16. package/dist/cli.js +28 -28
  17. package/dist/cli.js.map +1 -1
  18. package/dist/daemon.js +17 -17
  19. package/dist/daemon.js.map +1 -1
  20. package/dist/{dispatcher-ON7LNX6X.js → dispatcher-PP5OKOLS.js} +4 -4
  21. package/dist/{embeddings-HDNAGCOS.js → embeddings-MILTROKW.js} +2 -2
  22. package/dist/{ingest-MHPMJPUA.js → ingest-HEXVIAL6.js} +4 -3
  23. package/dist/mcp.js +8 -8
  24. package/dist/{memory-value-6JUQEYJZ.js → memory-value-WXI2Q6TO.js} +4 -4
  25. package/dist/{quality-HVTIOIXP.js → quality-VKQUCL66.js} +5 -5
  26. package/dist/{retrieval-72EIHKRF.js → retrieval-4MEIABHC.js} +5 -4
  27. package/dist/{tasks-AJ62N26N.js → tasks-7SE6VHSQ.js} +4 -4
  28. package/package.json +1 -1
  29. package/dist/chunk-65XK27KK.js.map +0 -1
  30. package/dist/chunk-6QFOCUEJ.js.map +0 -1
  31. package/dist/chunk-JKWK73GY.js.map +0 -1
  32. package/dist/chunk-JO5LRCA2.js.map +0 -1
  33. /package/dist/{chunk-53GKSF42.js.map → chunk-7CFX774S.js.map} +0 -0
  34. /package/dist/{chunk-MMYLXICL.js.map → chunk-AFD43EOE.js.map} +0 -0
  35. /package/dist/{chunk-UWERS646.js.map → chunk-LWY4Z626.js.map} +0 -0
  36. /package/dist/{chunk-JSTZKFZR.js.map → chunk-ZXCKMEJA.js.map} +0 -0
  37. /package/dist/{cleanup-RHNBHBNP.js.map → cleanup-RTL2UETA.js.map} +0 -0
  38. /package/dist/{dispatcher-ON7LNX6X.js.map → dispatcher-PP5OKOLS.js.map} +0 -0
  39. /package/dist/{embeddings-HDNAGCOS.js.map → embeddings-MILTROKW.js.map} +0 -0
  40. /package/dist/{ingest-MHPMJPUA.js.map → ingest-HEXVIAL6.js.map} +0 -0
  41. /package/dist/{memory-value-6JUQEYJZ.js.map → memory-value-WXI2Q6TO.js.map} +0 -0
  42. /package/dist/{quality-HVTIOIXP.js.map → quality-VKQUCL66.js.map} +0 -0
  43. /package/dist/{retrieval-72EIHKRF.js.map → retrieval-4MEIABHC.js.map} +0 -0
  44. /package/dist/{tasks-AJ62N26N.js.map → tasks-7SE6VHSQ.js.map} +0 -0
@@ -11,7 +11,7 @@ import {
11
11
  listInjectedHistoryIdsForSession,
12
12
  signalOutcomeFallback,
13
13
  startSessionLifecycle
14
- } from "./chunk-7Q5CBVUT.js";
14
+ } from "./chunk-4UHRAQFG.js";
15
15
  import {
16
16
  detectCorrections,
17
17
  isHighRiskRule,
@@ -19,7 +19,7 @@ import {
19
19
  isWorkspaceRootAlias,
20
20
  peekTasks,
21
21
  redactSensitiveText
22
- } from "./chunk-65XK27KK.js";
22
+ } from "./chunk-TA4WSV6A.js";
23
23
  import {
24
24
  detectAndRecordRetrievalMissesSemantic,
25
25
  listInjectedMemoryIdsForSession,
@@ -27,20 +27,20 @@ import {
27
27
  pathMatchesMemory,
28
28
  recordCompletionUseValueEventsSemantic,
29
29
  toolCallTouchesMemory
30
- } from "./chunk-JSTZKFZR.js";
30
+ } from "./chunk-ZXCKMEJA.js";
31
31
  import {
32
32
  textMatches
33
33
  } from "./chunk-FHEH6QDU.js";
34
- import {
35
- desc
36
- } from "./chunk-CW3XJDH7.js";
37
34
  import {
38
35
  hookCallDedupeKey,
39
36
  queryMemories
40
- } from "./chunk-JO5LRCA2.js";
37
+ } from "./chunk-NAYFAUSM.js";
38
+ import {
39
+ desc
40
+ } from "./chunk-CW3XJDH7.js";
41
41
  import {
42
42
  tagActivitySource
43
- } from "./chunk-JKWK73GY.js";
43
+ } from "./chunk-ZBQGZCFL.js";
44
44
  import {
45
45
  and,
46
46
  eq,
@@ -1196,4 +1196,4 @@ export {
1196
1196
  readCodexSessionEndInputFromStdin,
1197
1197
  dispatchCodexNotify
1198
1198
  };
1199
- //# sourceMappingURL=chunk-53GKSF42.js.map
1199
+ //# sourceMappingURL=chunk-7CFX774S.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  computeMemoryValueReport
3
- } from "./chunk-JSTZKFZR.js";
3
+ } from "./chunk-ZXCKMEJA.js";
4
4
  import {
5
5
  desc
6
6
  } from "./chunk-CW3XJDH7.js";
@@ -180,4 +180,4 @@ export {
180
180
  diffQualitySnapshots,
181
181
  formatQualityReport
182
182
  };
183
- //# sourceMappingURL=chunk-MMYLXICL.js.map
183
+ //# sourceMappingURL=chunk-AFD43EOE.js.map
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  getMemory
3
- } from "./chunk-JO5LRCA2.js";
3
+ } from "./chunk-NAYFAUSM.js";
4
4
  import {
5
5
  hybridSearch,
6
6
  searchMemoryFtsIndex
7
- } from "./chunk-JKWK73GY.js";
7
+ } from "./chunk-ZBQGZCFL.js";
8
8
  import {
9
9
  listEntitiesForMemory,
10
10
  listMemoryIdsForEntity,
@@ -120,4 +120,4 @@ async function graphQuery(db, query, embeddingConfig, options = {}) {
120
120
  export {
121
121
  graphQuery
122
122
  };
123
- //# sourceMappingURL=chunk-UWERS646.js.map
123
+ //# sourceMappingURL=chunk-LWY4Z626.js.map
@@ -1,8 +1,11 @@
1
+ import {
2
+ desc
3
+ } from "./chunk-CW3XJDH7.js";
1
4
  import {
2
5
  CONFIDENCE,
3
6
  PROMOTION,
4
7
  queueMemoryEmbeddingSync
5
- } from "./chunk-JKWK73GY.js";
8
+ } from "./chunk-ZBQGZCFL.js";
6
9
  import {
7
10
  isPlausibleEntityName,
8
11
  linkMemoryToEntity,
@@ -11,6 +14,7 @@ import {
11
14
  } from "./chunk-EAFRT7RX.js";
12
15
  import {
13
16
  and,
17
+ auditTrail,
14
18
  eq,
15
19
  feedbackEvents,
16
20
  gte,
@@ -21,7 +25,7 @@ import {
21
25
  } from "./chunk-LUIYWYOT.js";
22
26
 
23
27
  // src/models/memory.ts
24
- import { randomUUID } from "crypto";
28
+ import { randomUUID as randomUUID2 } from "crypto";
25
29
 
26
30
  // src/security/object.ts
27
31
  function defineOwn(target, key, value) {
@@ -109,6 +113,118 @@ function stableDedupeJson(value) {
109
113
  return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableDedupeJson(record[key])}`).join(",")}}`;
110
114
  }
111
115
 
116
+ // src/audit/trail.ts
117
+ import { randomUUID } from "crypto";
118
+ function recordAudit(db, memoryId, action, actor, reason, beforeSnapshot, afterSnapshot) {
119
+ const id = randomUUID();
120
+ if (afterSnapshot === void 0) {
121
+ const mem = getMemory(db, memoryId);
122
+ if (mem) {
123
+ afterSnapshot = JSON.stringify(mem);
124
+ }
125
+ }
126
+ db.insert(auditTrail).values({
127
+ id,
128
+ memory_id: memoryId,
129
+ action,
130
+ actor,
131
+ before_snapshot: beforeSnapshot ?? null,
132
+ after_snapshot: afterSnapshot ?? null,
133
+ reason: reason ?? null,
134
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
135
+ }).run();
136
+ return id;
137
+ }
138
+ function recordAuditWithSnapshot(db, memoryId, action, actor, reason, before, after) {
139
+ return recordAudit(
140
+ db,
141
+ memoryId,
142
+ action,
143
+ actor,
144
+ reason,
145
+ before ? JSON.stringify(before) : null,
146
+ after ? JSON.stringify(after) : null
147
+ );
148
+ }
149
+ function getAuditTrail(db, memoryId) {
150
+ return db.select().from(auditTrail).where(eq(auditTrail.memory_id, memoryId)).orderBy(desc(auditTrail.timestamp)).all().map(rowToAudit);
151
+ }
152
+ function getRecentAudit(db, limit = 50) {
153
+ return db.select().from(auditTrail).orderBy(desc(auditTrail.timestamp)).limit(limit).all().map(rowToAudit);
154
+ }
155
+ function diffSnapshots(before, after) {
156
+ if (!before || !after) return [];
157
+ const a = JSON.parse(before);
158
+ const b = JSON.parse(after);
159
+ const diffs = [];
160
+ const keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
161
+ for (const key of keys) {
162
+ if (key === "evidence" || key === "embedding") continue;
163
+ const va = JSON.stringify(a[key]);
164
+ const vb = JSON.stringify(b[key]);
165
+ if (va !== vb) {
166
+ diffs.push({ field: key, before: a[key], after: b[key] });
167
+ }
168
+ }
169
+ return diffs;
170
+ }
171
+ function rollbackMemory(db, memoryId, auditEntryId, actor) {
172
+ const entry = db.select().from(auditTrail).where(eq(auditTrail.id, auditEntryId)).get();
173
+ if (!entry) return false;
174
+ const snapshot = entry.before_snapshot;
175
+ if (!snapshot) return false;
176
+ const beforeRollback = getMemory(db, memoryId);
177
+ const restored = JSON.parse(snapshot);
178
+ db.update(memories).set({
179
+ text: restored.text,
180
+ type: restored.type,
181
+ scope: restored.scope,
182
+ path_scope: restored.path_scope,
183
+ status: restored.status,
184
+ confidence: restored.confidence,
185
+ source: restored.source,
186
+ evidence: restored.evidence,
187
+ capture_context: restored.capture_context,
188
+ repetition_count: restored.repetition_count,
189
+ updated_at: (/* @__PURE__ */ new Date()).toISOString()
190
+ }).where(eq(memories.id, memoryId)).run();
191
+ queueMemoryEmbeddingSync(db, memoryId);
192
+ recordAuditWithSnapshot(
193
+ db,
194
+ memoryId,
195
+ "rolled_back",
196
+ actor,
197
+ `Rolled back to state from ${entry.timestamp}`,
198
+ beforeRollback ?? null,
199
+ getMemory(db, memoryId) ?? null
200
+ );
201
+ return true;
202
+ }
203
+ function formatAuditTrail(entries) {
204
+ if (entries.length === 0) return "No audit entries.";
205
+ const lines = ["# Audit Trail", ""];
206
+ for (const e of entries) {
207
+ const diffs = diffSnapshots(e.before_snapshot, e.after_snapshot);
208
+ const diffStr = diffs.length > 0 ? ` [${diffs.map((d) => `${d.field}: ${JSON.stringify(d.before)} \u2192 ${JSON.stringify(d.after)}`).join(", ")}]` : "";
209
+ lines.push(
210
+ `${e.timestamp.slice(0, 19)} ${e.action.padEnd(22)} by ${e.actor}${e.reason ? ` \u2014 ${e.reason}` : ""}${diffStr}`
211
+ );
212
+ }
213
+ return lines.join("\n");
214
+ }
215
+ function rowToAudit(row) {
216
+ return {
217
+ id: row.id,
218
+ memory_id: row.memory_id,
219
+ action: row.action,
220
+ actor: row.actor,
221
+ before_snapshot: row.before_snapshot,
222
+ after_snapshot: row.after_snapshot,
223
+ reason: row.reason,
224
+ timestamp: row.timestamp
225
+ };
226
+ }
227
+
112
228
  // src/models/memory.ts
113
229
  function statusFromConfidence(confidence) {
114
230
  if (confidence < CONFIDENCE.TRANSIENT_MAX) return "transient";
@@ -117,7 +233,7 @@ function statusFromConfidence(confidence) {
117
233
  }
118
234
  function createMemory(db, input) {
119
235
  const now = (/* @__PURE__ */ new Date()).toISOString();
120
- const id = randomUUID();
236
+ const id = randomUUID2();
121
237
  const confidence = input.confidence ?? 0.35;
122
238
  const status = statusFromConfidence(confidence);
123
239
  let scope = input.scope;
@@ -286,15 +402,17 @@ function demoteGlobalMemory(db, id, opts = {}) {
286
402
  const updated = getMemory(db, id);
287
403
  return { ok: true, outcome: targetRepo ? "rescoped" : "rejected", memory: updated };
288
404
  }
289
- function rejectMemory(db, id) {
405
+ function rejectMemory(db, id, actor = "system") {
290
406
  const mem = getMemory(db, id);
291
407
  if (!mem) return false;
408
+ const beforeSnapshot = JSON.stringify(mem);
292
409
  db.update(memories).set({
293
410
  status: "rejected",
294
411
  confidence: 0,
295
412
  dedupe_key: null,
296
413
  updated_at: (/* @__PURE__ */ new Date()).toISOString()
297
414
  }).where(eq(memories.id, id)).run();
415
+ recordAudit(db, id, "rejected", actor, null, beforeSnapshot);
298
416
  queueMemoryEmbeddingSync(db, id);
299
417
  return true;
300
418
  }
@@ -306,6 +424,24 @@ function confirmMemory(db, id) {
306
424
  context: "user explicitly confirmed"
307
425
  });
308
426
  }
427
+ function reactivateMemory(db, id, evidence) {
428
+ const mem = getMemory(db, id);
429
+ if (!mem) return false;
430
+ if (mem.status !== "rejected") return false;
431
+ const now = (/* @__PURE__ */ new Date()).toISOString();
432
+ const dedupeKey = memoryDedupeKey(mem);
433
+ const existing = db.select().from(memories).where(and(eq(memories.dedupe_key, dedupeKey), sql`${memories.status} != 'rejected'`)).get();
434
+ if (existing && existing.id !== id) return false;
435
+ db.update(memories).set({
436
+ status: "candidate",
437
+ confidence: CONFIDENCE.TRANSIENT_MAX + 0.05,
438
+ dedupe_key: dedupeKey,
439
+ evidence: [...mem.evidence, evidence],
440
+ updated_at: now
441
+ }).where(eq(memories.id, id)).run();
442
+ queueMemoryEmbeddingSync(db, id);
443
+ return true;
444
+ }
309
445
  function appendEvidence(db, id, evidence) {
310
446
  const mem = getMemory(db, id);
311
447
  if (!mem) return false;
@@ -356,7 +492,7 @@ function countDistinctCorrectionSessions(mem) {
356
492
  return sessions.size;
357
493
  }
358
494
  function recordFeedback(db, memoryId, sessionId, injected, outcome) {
359
- const id = randomUUID();
495
+ const id = randomUUID2();
360
496
  const now = (/* @__PURE__ */ new Date()).toISOString();
361
497
  db.insert(feedbackEvents).values({
362
498
  id,
@@ -789,6 +925,12 @@ export {
789
925
  historySnippetDedupeKey,
790
926
  activityEventDedupeKey,
791
927
  hookCallDedupeKey,
928
+ recordAudit,
929
+ recordAuditWithSnapshot,
930
+ getAuditTrail,
931
+ getRecentAudit,
932
+ rollbackMemory,
933
+ formatAuditTrail,
792
934
  ingestMemoryHeuristic,
793
935
  ingestMemoryExtraction,
794
936
  mergeAndIngest,
@@ -804,6 +946,7 @@ export {
804
946
  demoteGlobalMemory,
805
947
  rejectMemory,
806
948
  confirmMemory,
949
+ reactivateMemory,
807
950
  appendEvidence,
808
951
  restoreAutoInject,
809
952
  updateMemoryCaptureContext,
@@ -813,4 +956,4 @@ export {
813
956
  getMemoryFeedbackSummaries,
814
957
  feedbackWeightedScore
815
958
  };
816
- //# sourceMappingURL=chunk-JO5LRCA2.js.map
959
+ //# sourceMappingURL=chunk-NAYFAUSM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/models/memory.ts","../src/security/object.ts","../src/models/dedupe.ts","../src/audit/trail.ts","../src/graph/extractor.ts","../src/graph/ingest.ts"],"sourcesContent":["import { eq, and, gte, inArray, like, sql } from \"drizzle-orm\";\nimport { randomUUID } from \"node:crypto\";\nimport type { RecallDb } from \"../db/client.js\";\nimport { memories, feedbackEvents } from \"../db/schema.js\";\nimport { memoryDedupeKey } from \"./dedupe.js\";\nimport { recordAudit } from \"../audit/trail.js\";\nimport { queueMemoryEmbeddingSync } from \"../embeddings/embeddings.js\";\nimport { safeIngestMemoryById } from \"../graph/ingest.js\";\nimport {\n CONFIDENCE,\n PROMOTION,\n type MemoryItem,\n type MemoryQuery,\n type MemoryStatus,\n type MemoryType,\n type MemoryScope,\n type MemorySource,\n type EvidenceEntry,\n type CaptureContext,\n type FeedbackOutcome,\n} from \"../types.js\";\n\ntype MemoryRow = typeof memories.$inferSelect;\n\n// --- Create ---\n\nexport interface CreateMemoryInput {\n type: MemoryType;\n text: string;\n scope: MemoryScope;\n path_scope?: string | null;\n repo?: string | null;\n source: MemorySource;\n confidence?: number;\n evidence?: EvidenceEntry[];\n capture_context?: CaptureContext | null;\n supersedes?: string | null;\n dedupe?: boolean;\n}\n\nexport function statusFromConfidence(confidence: number): MemoryStatus {\n if (confidence < CONFIDENCE.TRANSIENT_MAX) return \"transient\";\n if (confidence < CONFIDENCE.CANDIDATE_MAX) return \"candidate\";\n return \"active\";\n}\n\nexport function createMemory(db: RecallDb, input: CreateMemoryInput): string {\n const now = new Date().toISOString();\n const id = randomUUID();\n const confidence = input.confidence ?? 0.35; // default: low candidate\n const status = statusFromConfidence(confidence);\n let scope = input.scope;\n let repo = input.repo ?? null;\n let pathScope = input.path_scope ?? null;\n if (scope === \"path\" && !pathScope) scope = repo ? \"repo\" : \"global\";\n if (scope === \"repo\" && !repo) scope = \"global\";\n if (scope === \"global\") {\n repo = null;\n pathScope = null;\n }\n const dedupeKey = input.dedupe === false\n ? null\n : memoryDedupeKey({\n type: input.type,\n scope,\n repo,\n path_scope: pathScope,\n text: input.text,\n });\n\n if (dedupeKey) {\n const existing = db.select().from(memories)\n .where(and(eq(memories.dedupe_key, dedupeKey), sql`${memories.status} != 'rejected'`))\n .get();\n if (existing) return existing.id;\n }\n\n // onConflictDoNothing closes the TOCTOU window between the pre-check SELECT\n // and this INSERT: when two writers race (e.g. concurrent Claude + Codex\n // session-start scans bootstrapping the same repo), both pass the SELECT\n // above, then one INSERT wins and the other previously threw\n // \"UNIQUE constraint failed: memories.dedupe_key\", crashing the whole hook.\n const result = db.insert(memories)\n .values({\n id,\n type: input.type,\n text: input.text,\n scope,\n path_scope: pathScope,\n repo,\n status,\n confidence,\n source: input.source,\n evidence: (input.evidence ?? []) as any,\n capture_context: input.capture_context ? input.capture_context as any : null,\n supersedes: input.supersedes ?? null,\n dedupe_key: dedupeKey,\n created_at: now,\n updated_at: now,\n last_validated_at: null,\n last_injected_at: null,\n injection_count: 0,\n override_count: 0,\n repetition_count: 0,\n })\n .onConflictDoNothing({ target: memories.dedupe_key })\n .run();\n\n if (dedupeKey && result.changes === 0) {\n // Lost the race (or a stale rejected row still holds the key): return the\n // existing memory's id rather than the uninserted one, and don't queue an\n // embedding for a row that was never written.\n const winner = db.select().from(memories)\n .where(eq(memories.dedupe_key, dedupeKey))\n .get();\n if (winner) return winner.id;\n }\n\n queueMemoryEmbeddingSync(db, id);\n return id;\n}\n\n// --- Read ---\n\nexport function getMemory(\n db: RecallDb,\n id: string,\n): MemoryItem | undefined {\n const row = db.select().from(memories).where(eq(memories.id, id)).get();\n if (!row) return undefined;\n return rowToMemory(row);\n}\n\nexport function queryMemories(\n db: RecallDb,\n query: MemoryQuery,\n): MemoryItem[] {\n const conditions = [];\n\n if (query.repo) conditions.push(eq(memories.repo, query.repo));\n if (query.status) conditions.push(eq(memories.status, query.status));\n if (query.type) conditions.push(eq(memories.type, query.type));\n if (query.scope) conditions.push(eq(memories.scope, query.scope));\n if (query.min_confidence != null)\n conditions.push(gte(memories.confidence, query.min_confidence));\n if (query.path) conditions.push(like(memories.path_scope, `%${query.path}%`));\n if (query.auto_inject != null) conditions.push(eq(memories.auto_inject, query.auto_inject));\n\n let statement = db.select().from(memories).$dynamic();\n if (conditions.length > 0) {\n statement = statement.where(and(...conditions));\n }\n if (query.offset != null) {\n statement = statement.offset(query.offset);\n }\n if (query.limit != null) {\n statement = statement.limit(query.limit);\n }\n\n const rows = statement.all();\n\n return rows.map(rowToMemory);\n}\n\nexport function listMemories(\n db: RecallDb,\n repo?: string,\n options: Pick<MemoryQuery, \"limit\" | \"offset\"> = {},\n): MemoryItem[] {\n return queryMemories(db, {\n repo,\n limit: options.limit,\n offset: options.offset,\n });\n}\n\nexport function listRepos(db: RecallDb): string[] {\n return [...new Set(\n db.select({ repo: memories.repo }).from(memories)\n .where(sql`${memories.status} != 'rejected'`)\n .all()\n .map((row) => row.repo)\n .filter((repo): repo is string => Boolean(repo)),\n )].sort();\n}\n\n// --- State transitions ---\n\nexport function promoteMemory(\n db: RecallDb,\n id: string,\n reason: \"explicit_confirm\" | \"repeat_correction\" | \"review_feedback\" | \"passive_gain\",\n evidence?: EvidenceEntry,\n): boolean {\n const mem = getMemory(db, id);\n if (!mem) return false;\n if (mem.status === \"rejected\") return false; // must use reactivate\n\n let newConfidence: number;\n if (reason === \"explicit_confirm\") {\n newConfidence = Math.max(mem.confidence, PROMOTION.EXPLICIT_CONFIRM);\n } else if (reason === \"repeat_correction\") {\n newConfidence = Math.min(1, mem.confidence + PROMOTION.REPEAT_CORRECTION);\n } else if (reason === \"review_feedback\") {\n newConfidence = Math.min(1, mem.confidence + PROMOTION.REVIEW_FEEDBACK);\n } else {\n newConfidence = Math.min(1, mem.confidence + PROMOTION.PASSIVE_GAIN);\n }\n\n const newStatus = statusFromConfidence(newConfidence);\n const now = new Date().toISOString();\n\n const newEvidence = evidence\n ? [...mem.evidence, evidence]\n : mem.evidence;\n\n db.update(memories)\n .set({\n confidence: newConfidence,\n status: newStatus,\n evidence: newEvidence as any,\n updated_at: now,\n last_validated_at: now,\n })\n .where(eq(memories.id, id))\n .run();\n\n queueMemoryEmbeddingSync(db, id);\n\n // A memory only enters the (verified-only) knowledge graph once it becomes\n // active. Ingest on the candidate→active transition so promoted memories\n // appear without waiting for the next daemon restart / reconcile.\n if (newStatus === \"active\" && mem.status !== \"active\") {\n safeIngestMemoryById(db, id);\n }\n return true;\n}\n\nexport function demoteMemory(\n db: RecallDb,\n id: string,\n reason: string,\n): boolean {\n const mem = getMemory(db, id);\n if (!mem) return false;\n\n const newConfidence = Math.max(0, mem.confidence - 0.3);\n const newStatus = statusFromConfidence(newConfidence);\n const now = new Date().toISOString();\n\n db.update(memories)\n .set({\n confidence: newConfidence,\n status: newStatus === \"transient\" ? \"candidate\" : newStatus, // don't lose it completely\n updated_at: now,\n })\n .where(eq(memories.id, id))\n .run();\n\n queueMemoryEmbeddingSync(db, id);\n return true;\n}\n\nexport type DemoteGlobalResult =\n | { ok: true; outcome: \"rescoped\" | \"rejected\"; memory: MemoryItem }\n | { ok: false; reason: \"not_found\" | \"not_global\" };\n\nexport function demoteGlobalMemory(\n db: RecallDb,\n id: string,\n opts: { repo?: string | null } = {},\n): DemoteGlobalResult {\n const mem = getMemory(db, id);\n if (!mem) return { ok: false, reason: \"not_found\" };\n if (mem.scope !== \"global\") return { ok: false, reason: \"not_global\" };\n\n const targetRepo = opts.repo?.trim() || null;\n const now = new Date().toISOString();\n\n if (targetRepo) {\n const newDedupe = memoryDedupeKey({\n type: mem.type,\n scope: \"repo\",\n repo: targetRepo,\n path_scope: mem.path_scope,\n text: mem.text,\n });\n db.update(memories)\n .set({\n scope: \"repo\",\n repo: targetRepo,\n dedupe_key: newDedupe,\n updated_at: now,\n })\n .where(eq(memories.id, id))\n .run();\n } else {\n db.update(memories)\n .set({\n status: \"rejected\",\n confidence: 0,\n dedupe_key: null,\n updated_at: now,\n })\n .where(eq(memories.id, id))\n .run();\n }\n\n queueMemoryEmbeddingSync(db, id);\n const updated = getMemory(db, id)!;\n return { ok: true, outcome: targetRepo ? \"rescoped\" : \"rejected\", memory: updated };\n}\n\n/**\n * Reject a memory.\n *\n * `actor` records who decided. This matters beyond bookkeeping: a rejection a\n * human issued becomes a \"never capture this again\" exemplar for the capture\n * path, while a machine retirement (staleness, policy, pruning) must not. This\n * function previously wrote no audit row at all, so provenance was simply\n * absent for most rejections and the capture path had to guess — it guessed\n * \"human\", which turned routine cleanup into permanent capture blocks.\n *\n * Defaults to \"system\" so an unattributed caller is never mistaken for a\n * deliberate human verdict.\n */\nexport function rejectMemory(db: RecallDb, id: string, actor = \"system\"): boolean {\n const mem = getMemory(db, id);\n if (!mem) return false;\n\n const beforeSnapshot = JSON.stringify(mem);\n\n db.update(memories)\n .set({\n status: \"rejected\",\n confidence: 0,\n dedupe_key: null,\n updated_at: new Date().toISOString(),\n })\n .where(eq(memories.id, id))\n .run();\n\n recordAudit(db, id, \"rejected\", actor, null, beforeSnapshot);\n\n queueMemoryEmbeddingSync(db, id);\n return true;\n}\n\nexport function confirmMemory(db: RecallDb, id: string): boolean {\n return promoteMemory(db, id, \"explicit_confirm\", {\n type: \"session_correction\",\n session: \"cli\",\n timestamp: new Date().toISOString(),\n context: \"user explicitly confirmed\",\n });\n}\n\nexport function reactivateMemory(\n db: RecallDb,\n id: string,\n evidence: EvidenceEntry,\n): boolean {\n const mem = getMemory(db, id);\n if (!mem) return false;\n if (mem.status !== \"rejected\") return false;\n\n const now = new Date().toISOString();\n const dedupeKey = memoryDedupeKey(mem);\n const existing = db.select().from(memories)\n .where(and(eq(memories.dedupe_key, dedupeKey), sql`${memories.status} != 'rejected'`))\n .get();\n if (existing && existing.id !== id) return false;\n\n db.update(memories)\n .set({\n status: \"candidate\",\n confidence: CONFIDENCE.TRANSIENT_MAX + 0.05,\n dedupe_key: dedupeKey,\n evidence: [...mem.evidence, evidence] as any,\n updated_at: now,\n })\n .where(eq(memories.id, id))\n .run();\n\n queueMemoryEmbeddingSync(db, id);\n return true;\n}\n\nexport function appendEvidence(\n db: RecallDb,\n id: string,\n evidence: EvidenceEntry,\n): boolean {\n const mem = getMemory(db, id);\n if (!mem) return false;\n if (hasEquivalentEvidence(mem.evidence, evidence)) return true;\n\n const now = new Date().toISOString();\n db.update(memories)\n .set({\n evidence: [...mem.evidence, evidence] as any,\n updated_at: now,\n last_validated_at: now,\n })\n .where(eq(memories.id, id))\n .run();\n\n return true;\n}\n\n// An archived memory (auto_inject cleared by the stale-archiver) that the user\n// teaches again is, by definition, relevant again. Reinforcement puts it back\n// into automatic injection instead of leaving it retrievable-but-silent.\nexport function restoreAutoInject(db: RecallDb, id: string): boolean {\n const mem = getMemory(db, id);\n if (!mem || mem.auto_inject) return false;\n\n db.update(memories)\n .set({ auto_inject: true, updated_at: new Date().toISOString() })\n .where(eq(memories.id, id))\n .run();\n return true;\n}\n\nexport function updateMemoryCaptureContext(\n db: RecallDb,\n id: string,\n captureContext: CaptureContext,\n): boolean {\n const mem = getMemory(db, id);\n if (!mem) return false;\n\n db.update(memories)\n .set({\n capture_context: captureContext as any,\n updated_at: new Date().toISOString(),\n })\n .where(eq(memories.id, id))\n .run();\n\n return true;\n}\n\nexport function incrementMemoryRepetition(\n db: RecallDb,\n id: string,\n): boolean {\n const mem = getMemory(db, id);\n if (!mem) return false;\n\n db.update(memories)\n .set({\n repetition_count: sql`repetition_count + 1`,\n updated_at: new Date().toISOString(),\n })\n .where(eq(memories.id, id))\n .run();\n\n return true;\n}\n\nexport function countDistinctCorrectionSessions(mem: MemoryItem): number {\n const sessions = new Set<string>();\n\n for (const entry of mem.evidence) {\n if (entry.type === \"session_correction\") {\n sessions.add(entry.session);\n } else if (entry.type === \"repeated_correction\") {\n for (const session of entry.sessions) {\n sessions.add(session);\n }\n }\n }\n\n return sessions.size;\n}\n\n// --- Feedback ---\n\nexport function recordFeedback(\n db: RecallDb,\n memoryId: string,\n sessionId: string,\n injected: boolean,\n outcome: FeedbackOutcome,\n): string {\n const id = randomUUID();\n const now = new Date().toISOString();\n\n db.insert(feedbackEvents)\n .values({\n id,\n memory_id: memoryId,\n session_id: sessionId,\n injected,\n outcome,\n timestamp: now,\n })\n .run();\n\n const mem = getMemory(db, memoryId);\n if (!mem) return id;\n\n const delta = outcome === \"followed\"\n ? 0.05\n : outcome === \"overridden\"\n ? -0.15\n : outcome === \"ignored\"\n ? -0.02\n : -0.25;\n const nextConfidence = Math.max(0, Math.min(1, mem.confidence + delta));\n const nextStatus = statusFromConfidence(nextConfidence);\n\n // Update injection tracking\n if (injected) {\n db.update(memories)\n .set({\n confidence: nextConfidence,\n status: nextStatus === \"transient\" ? \"candidate\" : nextStatus,\n updated_at: now,\n last_injected_at: now,\n injection_count: sql`injection_count + 1`,\n ...(outcome === \"overridden\" || outcome === \"contradicted\"\n ? { override_count: sql`override_count + 1` }\n : {}),\n })\n .where(eq(memories.id, memoryId))\n .run();\n } else {\n db.update(memories)\n .set({\n confidence: nextConfidence,\n status: nextStatus === \"transient\" ? \"candidate\" : nextStatus,\n updated_at: now,\n })\n .where(eq(memories.id, memoryId))\n .run();\n }\n\n return id;\n}\n\nexport function getMemoryFeedback(\n db: RecallDb,\n memoryId: string,\n) {\n return db\n .select()\n .from(feedbackEvents)\n .where(eq(feedbackEvents.memory_id, memoryId))\n .all();\n}\n\nexport interface FeedbackSummary {\n followed: number;\n overridden: number;\n contradicted: number;\n ignored: number;\n resolved: number;\n}\n\n/**\n * Aggregate feedback outcomes for a batch of memories in a single query.\n * `resolved` excludes `ignored` because the post-Phase-2.3 detector only\n * writes meaningful outcomes.\n */\nexport function getMemoryFeedbackSummaries(\n db: RecallDb,\n memoryIds: readonly string[],\n): Map<string, FeedbackSummary> {\n const empty = (): FeedbackSummary => ({\n followed: 0,\n overridden: 0,\n contradicted: 0,\n ignored: 0,\n resolved: 0,\n });\n const result = new Map<string, FeedbackSummary>();\n if (memoryIds.length === 0) return result;\n for (const id of memoryIds) result.set(id, empty());\n\n const rows = db.select({\n memory_id: feedbackEvents.memory_id,\n outcome: feedbackEvents.outcome,\n count: sql<number>`count(*)`.as(\"count\"),\n })\n .from(feedbackEvents)\n .where(inArray(feedbackEvents.memory_id, [...memoryIds]))\n .groupBy(feedbackEvents.memory_id, feedbackEvents.outcome)\n .all();\n\n for (const row of rows) {\n const entry = result.get(row.memory_id) ?? empty();\n if (row.outcome === \"followed\") entry.followed += row.count;\n else if (row.outcome === \"overridden\") entry.overridden += row.count;\n else if (row.outcome === \"contradicted\") entry.contradicted += row.count;\n else if (row.outcome === \"ignored\") entry.ignored += row.count;\n if (row.outcome !== \"ignored\") entry.resolved += row.count;\n result.set(row.memory_id, entry);\n }\n return result;\n}\n\n/**\n * Smoothed feedback-driven score in [0, 1]. Cold-start memories return their\n * confidence directly; as resolved samples accumulate, the score blends in\n * the empirical followed rate (Bayesian beta(1,1) prior, weight ramps to 1\n * at FEEDBACK_MATURITY resolved samples).\n */\nexport const FEEDBACK_MATURITY = 5;\nexport function feedbackWeightedScore(\n confidence: number,\n summary: FeedbackSummary,\n): number {\n const total = summary.resolved;\n const maturity = Math.min(total, FEEDBACK_MATURITY) / FEEDBACK_MATURITY;\n if (maturity === 0) return confidence;\n // Penalize contradictions harder than overrides.\n const positive = summary.followed;\n const negative = summary.overridden + 2 * summary.contradicted;\n const numerator = Math.max(0, positive - negative + 1);\n const denominator = Math.max(1, total + 2);\n const empirical = Math.min(1, numerator / denominator);\n return (1 - maturity) * confidence + maturity * empirical;\n}\n\n// --- Helpers ---\n\nfunction rowToMemory(row: MemoryRow): MemoryItem {\n const evidence =\n typeof row.evidence === \"string\"\n ? JSON.parse(row.evidence as string)\n : Array.isArray(row.evidence)\n ? row.evidence\n : [];\n const captureContext =\n typeof row.capture_context === \"string\"\n ? JSON.parse(row.capture_context as string)\n : row.capture_context ?? null;\n return {\n id: row.id,\n type: row.type,\n text: row.text,\n scope: row.scope,\n path_scope: row.path_scope,\n repo: row.repo,\n status: row.status,\n confidence: row.confidence,\n source: row.source,\n evidence: evidence as EvidenceEntry[],\n capture_context: captureContext as MemoryItem[\"capture_context\"],\n supersedes: row.supersedes,\n created_at: row.created_at,\n updated_at: row.updated_at,\n last_validated_at: row.last_validated_at,\n last_injected_at: row.last_injected_at,\n injection_count: row.injection_count,\n override_count: row.override_count,\n repetition_count: row.repetition_count,\n auto_inject: row.auto_inject,\n };\n}\n\nfunction hasEquivalentEvidence(\n existing: EvidenceEntry[],\n next: EvidenceEntry,\n): boolean {\n return existing.some((entry) => {\n if (entry.type !== next.type) return false;\n\n if (entry.type === \"session_correction\" && next.type === \"session_correction\") {\n return entry.session === next.session;\n }\n\n if (entry.type === \"review_feedback\" && next.type === \"review_feedback\") {\n return entry.reviewer === next.reviewer && entry.context === next.context;\n }\n\n if (entry.type === \"repo_scan\" && next.type === \"repo_scan\") {\n return entry.file === next.file;\n }\n\n if (entry.type === \"repeated_correction\" && next.type === \"repeated_correction\") {\n return entry.sessions.join(\"|\") === next.sessions.join(\"|\");\n }\n\n return false;\n });\n}\n","export function defineOwn<T>(\n target: Record<string, T>,\n key: string,\n value: T,\n): void {\n Object.defineProperty(target, key, {\n configurable: true,\n enumerable: true,\n value,\n writable: true,\n });\n}\n\nexport function deleteOwn(\n target: Record<string, unknown>,\n key: string,\n): void {\n Reflect.deleteProperty(target, key);\n}\n","import { defineOwn } from \"../security/object.js\";\n\nexport function normalizeDedupeText(text: string): string {\n return text\n .toLowerCase()\n .replace(/\\s+/g, \" \")\n .replace(/[\\s.;:,!?`]+$/g, \"\")\n .trim();\n}\n\nexport function memoryDedupeKey(input: {\n type: string;\n scope: string;\n repo?: string | null;\n path_scope?: string | null;\n text: string;\n}): string {\n return [\n \"memory\",\n input.type,\n input.scope,\n input.repo ?? \"\",\n input.path_scope ?? \"\",\n normalizeDedupeText(input.text),\n ].join(\"\\u001f\");\n}\n\nexport function historySnippetDedupeKey(input: {\n repo?: string | null;\n session_id?: string | null;\n kind: string;\n text: string;\n}): string {\n return [\n \"history\",\n input.repo ?? \"\",\n input.session_id ?? \"\",\n input.kind,\n normalizeDedupeText(input.text),\n ].join(\"\\u001f\");\n}\n\nexport function activityEventDedupeKey(input: {\n session_id?: string | null;\n repo?: string | null;\n path?: string | null;\n source: string;\n event_type: string;\n request?: Record<string, unknown>;\n result?: Record<string, unknown>;\n}): string | null {\n if (!input.session_id) return null;\n return [\n \"activity\",\n input.session_id,\n input.repo ?? \"\",\n input.path ?? \"\",\n input.source,\n input.event_type,\n stableDedupeJson(stripVolatileFields(input.request ?? {})),\n stableDedupeJson(stripVolatileFields(input.result ?? {})),\n ].join(\"\\u001f\");\n}\n\nexport function hookCallDedupeKey(input: {\n session_id?: string | null;\n agent: string;\n event: string;\n ok: boolean;\n payload?: Record<string, unknown>;\n}): string | null {\n if (!input.session_id) return null;\n return [\n \"hook\",\n input.session_id,\n input.agent,\n input.event,\n input.ok ? \"ok\" : \"error\",\n stableDedupeJson(stripVolatileFields(input.payload ?? {})),\n ].join(\"\\u001f\");\n}\n\nexport function stripVolatileFields(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(stripVolatileFields);\n }\n if (!value || typeof value !== \"object\") {\n return value;\n }\n\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n if (/_at$/u.test(key) || key === \"timestamp\") continue;\n if (entry === undefined) continue;\n defineOwn(out, key, stripVolatileFields(entry));\n }\n return out;\n}\n\nexport function stableDedupeJson(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map(stableDedupeJson).join(\",\")}]`;\n }\n if (!value || typeof value !== \"object\") {\n return JSON.stringify(value);\n }\n\n const record = value as Record<string, unknown>;\n return `{${Object.keys(record).sort().map((key) => (\n `${JSON.stringify(key)}:${stableDedupeJson(record[key])}`\n )).join(\",\")}}`;\n}\n","/**\n * Audit trail — versioned history of every memory mutation.\n *\n * Records who changed what, when, why. Supports diff between versions\n * and rollback to a previous state.\n */\n\nimport { eq, desc } from \"drizzle-orm\";\nimport { randomUUID } from \"node:crypto\";\nimport type { RecallDb } from \"../db/client.js\";\nimport { auditTrail, memories } from \"../db/schema.js\";\nimport { queueMemoryEmbeddingSync } from \"../embeddings/embeddings.js\";\nimport { getMemory } from \"../models/memory.js\";\nimport type { AuditAction, AuditEntry, MemoryItem } from \"../types.js\";\n\n// --- Record an audit entry ---\n\nexport function recordAudit(\n db: RecallDb,\n memoryId: string,\n action: AuditAction,\n actor: string,\n reason: string | null,\n beforeSnapshot?: string | null,\n afterSnapshot?: string | null,\n): string {\n const id = randomUUID();\n\n // Auto-capture snapshots if not provided\n if (afterSnapshot === undefined) {\n const mem = getMemory(db, memoryId);\n if (mem) {\n afterSnapshot = JSON.stringify(mem);\n }\n }\n\n db.insert(auditTrail)\n .values({\n id,\n memory_id: memoryId,\n action,\n actor,\n before_snapshot: beforeSnapshot ?? null,\n after_snapshot: afterSnapshot ?? null,\n reason: reason ?? null,\n timestamp: new Date().toISOString(),\n })\n .run();\n\n return id;\n}\n\n/** Record with explicit before/after snapshots */\nexport function recordAuditWithSnapshot(\n db: RecallDb,\n memoryId: string,\n action: AuditAction,\n actor: string,\n reason: string | null,\n before: MemoryItem | null,\n after: MemoryItem | null,\n): string {\n return recordAudit(\n db,\n memoryId,\n action,\n actor,\n reason,\n before ? JSON.stringify(before) : null,\n after ? JSON.stringify(after) : null,\n );\n}\n\n// --- Query audit trail ---\n\nexport function getAuditTrail(\n db: RecallDb,\n memoryId: string,\n): AuditEntry[] {\n return db\n .select()\n .from(auditTrail)\n .where(eq(auditTrail.memory_id, memoryId))\n .orderBy(desc(auditTrail.timestamp))\n .all()\n .map(rowToAudit);\n}\n\nexport function getRecentAudit(\n db: RecallDb,\n limit: number = 50,\n): AuditEntry[] {\n return db\n .select()\n .from(auditTrail)\n .orderBy(desc(auditTrail.timestamp))\n .limit(limit)\n .all()\n .map(rowToAudit);\n}\n\n// --- Diff between versions ---\n\nexport interface MemoryDiff {\n field: string;\n before: unknown;\n after: unknown;\n}\n\nexport function diffSnapshots(\n before: string | null,\n after: string | null,\n): MemoryDiff[] {\n if (!before || !after) return [];\n\n const a = JSON.parse(before);\n const b = JSON.parse(after);\n const diffs: MemoryDiff[] = [];\n\n const keys = new Set([...Object.keys(a), ...Object.keys(b)]);\n for (const key of keys) {\n if (key === \"evidence\" || key === \"embedding\") continue; // skip large fields\n const va = JSON.stringify(a[key]);\n const vb = JSON.stringify(b[key]);\n if (va !== vb) {\n diffs.push({ field: key, before: a[key], after: b[key] });\n }\n }\n\n return diffs;\n}\n\n// --- Rollback ---\n\nexport function rollbackMemory(\n db: RecallDb,\n memoryId: string,\n auditEntryId: string,\n actor: string,\n): boolean {\n const entry = db\n .select()\n .from(auditTrail)\n .where(eq(auditTrail.id, auditEntryId))\n .get();\n\n if (!entry) return false;\n\n // Use the before_snapshot to restore state\n const snapshot = entry.before_snapshot;\n if (!snapshot) return false;\n\n const beforeRollback = getMemory(db, memoryId);\n const restored = JSON.parse(snapshot) as MemoryItem;\n\n db.update(memories)\n .set({\n text: restored.text,\n type: restored.type,\n scope: restored.scope,\n path_scope: restored.path_scope,\n status: restored.status,\n confidence: restored.confidence,\n source: restored.source,\n evidence: restored.evidence as any,\n capture_context: restored.capture_context as any,\n repetition_count: restored.repetition_count,\n updated_at: new Date().toISOString(),\n })\n .where(eq(memories.id, memoryId))\n .run();\n queueMemoryEmbeddingSync(db, memoryId);\n\n recordAuditWithSnapshot(\n db,\n memoryId,\n \"rolled_back\",\n actor,\n `Rolled back to state from ${entry.timestamp}`,\n beforeRollback ?? null,\n getMemory(db, memoryId) ?? null,\n );\n\n return true;\n}\n\n// --- Format audit trail ---\n\nexport function formatAuditTrail(entries: AuditEntry[]): string {\n if (entries.length === 0) return \"No audit entries.\";\n\n const lines = [\"# Audit Trail\", \"\"];\n for (const e of entries) {\n const diffs = diffSnapshots(e.before_snapshot, e.after_snapshot);\n const diffStr = diffs.length > 0\n ? ` [${diffs.map((d) => `${d.field}: ${JSON.stringify(d.before)} → ${JSON.stringify(d.after)}`).join(\", \")}]`\n : \"\";\n lines.push(\n `${e.timestamp.slice(0, 19)} ${e.action.padEnd(22)} by ${e.actor}${e.reason ? ` — ${e.reason}` : \"\"}${diffStr}`,\n );\n }\n\n return lines.join(\"\\n\");\n}\n\n// --- Helpers ---\n\nfunction rowToAudit(row: any): AuditEntry {\n return {\n id: row.id,\n memory_id: row.memory_id,\n action: row.action,\n actor: row.actor,\n before_snapshot: row.before_snapshot,\n after_snapshot: row.after_snapshot,\n reason: row.reason,\n timestamp: row.timestamp,\n };\n}\n","/**\n * Entity extractor. Pulls entities (files, functions, libraries, tools,\n * concepts, paths, commands, URLs) plus typed relations out of memory text.\n *\n * Two paths:\n * 1. heuristic() — always runs, cheap, regex-based, deterministic.\n * Catches paths, package-like names, identifier-shaped function calls,\n * common CLI tools, URLs. Used on every memory write.\n *\n * 2. llmEnrich() — opt-in; runs when an LLM provider is configured.\n * Reads the memory text + the heuristic seed and returns canonical\n * entity names + relations between them. Drives multi-hop graph walks.\n */\nimport type { RelationType } from \"./store.js\";\nimport type { EntityKind } from \"./normalize.js\";\nimport { isPlausibleEntityName } from \"./normalize.js\";\n\nexport interface ExtractedEntity {\n kind: EntityKind;\n name: string;\n /** 'heuristic' for regex output, 'llm' for model-extracted, 'manual' for user. */\n source: \"heuristic\" | \"llm\" | \"manual\";\n /** Where this mention came from in the source text, if known. */\n weight?: number;\n}\n\nexport interface ExtractedRelation {\n source: { kind: EntityKind; name: string };\n target: { kind: EntityKind; name: string };\n relation: RelationType;\n confidence: number;\n}\n\nexport interface ExtractionResult {\n entities: ExtractedEntity[];\n relations: ExtractedRelation[];\n}\n\n// ---- Heuristic extractor ----------------------------------------------------\n\n// File paths: src/foo/bar.ts, ./scripts/x.sh, docs/README.md\nconst PATH_RE = /(?:^|[\\s`'\"(])((?:\\.{0,2}\\/)?(?:[A-Za-z0-9_.-]+\\/){1,}[A-Za-z0-9_.-]+\\.[A-Za-z0-9]{1,8})/g;\n// Inline-coded short identifiers: `foo()`, `Bar.method()`\nconst FUNC_RE = /`([A-Za-z_][\\w.]{1,}\\(\\))`/g;\n// Package-like names in backticks: `react`, `@scope/pkg`, `drizzle-orm`.\n// Two flavours:\n// - SCOPED_PACKAGE_RE: @scope/name and hyphenated names — high-confidence\n// - SIMPLE_PACKAGE_RE: single lowercase words in backticks — gated by a stop-list\nconst SCOPED_PACKAGE_RE = /`(@[a-z0-9_-]+\\/[a-z0-9_.-]+|[a-z][a-z0-9_-]*(?:-[a-z0-9]+)+)`/g;\nconst SIMPLE_PACKAGE_RE = /`([a-z][a-z0-9_]{2,30})`/g;\n// Common English / generic words that look package-shaped but aren't.\nconst PACKAGE_STOPWORDS = new Set([\n \"the\", \"and\", \"but\", \"for\", \"use\", \"uses\", \"used\", \"with\", \"from\", \"this\",\n \"that\", \"have\", \"has\", \"true\", \"false\", \"null\", \"void\", \"data\", \"code\",\n \"test\", \"tests\", \"build\", \"run\", \"runs\", \"name\", \"type\", \"types\", \"main\",\n \"yes\", \"no\", \"ok\", \"all\", \"any\", \"new\", \"old\", \"more\", \"less\", \"always\",\n \"never\", \"todo\", \"fixme\", \"note\", \"warn\", \"info\", \"error\", \"ts\", \"js\",\n // Shell / language builtins that look package-shaped in backticks but are\n // not libraries (\"echo\", \"dict\", ...).\n \"echo\", \"dict\", \"list\", \"set\", \"map\", \"str\", \"int\", \"bool\", \"float\",\n \"print\", \"println\", \"log\", \"dir\", \"env\", \"tmp\", \"src\", \"lib\", \"bin\",\n \"out\", \"obj\", \"val\", \"var\", \"let\", \"const\", \"func\", \"def\", \"cls\", \"self\",\n \"args\", \"kwargs\", \"none\", \"cat\", \"grep\", \"sed\", \"awk\", \"cwd\", \"std\",\n]);\n// Bare CLI invocation lines: `npm test`, `pnpm i`, `cargo build`\nconst CLI_RE = /\\b(npm|pnpm|yarn|bun|cargo|go|uv|pip|node|deno|claude|codex|cursor|recall|brew|gh|git)\\s+([a-z][a-z-]{0,30})\\b/g;\n// Package managers + runtimes whose `<tool> <word>` pairs are almost always\n// generic build/script noise (\"pnpm build\", \"node dist\", \"npm run\") or English\n// filler grabbed from prose (\"Use pnpm as ...\", \"npm install\" → \"npm in\").\n// For these we record the tool itself but never a `command` entity.\nconst TOOL_ONLY_CLIS = new Set([\"npm\", \"pnpm\", \"yarn\", \"bun\", \"node\", \"deno\"]);\n// Second tokens that are English filler, not real subcommands — reject the\n// whole match so we don't mint entities like \"pnpm as\" or \"git it\".\nconst CLI_SUBCOMMAND_STOPWORDS = new Set([\n \"a\", \"an\", \"and\", \"are\", \"as\", \"at\", \"be\", \"by\", \"can\", \"do\", \"does\", \"for\",\n \"from\", \"has\", \"have\", \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"no\",\n \"not\", \"of\", \"on\", \"or\", \"so\", \"that\", \"the\", \"then\", \"this\", \"to\", \"up\",\n \"via\", \"was\", \"we\", \"will\", \"with\", \"you\",\n]);\n// URLs\nconst URL_RE = /\\bhttps?:\\/\\/[^\\s<>\"'`)]+/g;\n\n// Relation keyword cues. Order matters — first match wins for a sentence.\nconst RELATION_CUES: Array<{ rx: RegExp; relation: RelationType; flip?: boolean }> = [\n { rx: /\\b(?:replaces?|replaced|supersedes?|superseded|deprecates?|deprecated)\\b/i, relation: \"replaces\" },\n { rx: /\\b(?:conflicts? with|incompatible with|clashes? with)\\b/i, relation: \"conflicts_with\" },\n { rx: /\\b(?:tested by|covered by)\\b/i, relation: \"tested_by\" },\n { rx: /\\b(?:depends on|requires|required by)\\b/i, relation: \"depends_on\" },\n { rx: /\\b(?:uses?|used|relies on|via)\\b/i, relation: \"uses\" },\n { rx: /\\b(?:references?|see also|cf\\.)\\b/i, relation: \"references\" },\n { rx: /\\b(?:part of|inside|under)\\b/i, relation: \"part_of\" },\n];\n\nexport function heuristic(text: string): ExtractionResult {\n const entities = new Map<string, ExtractedEntity>(); // dedupe by (kind|name)\n const relations: ExtractedRelation[] = [];\n\n const push = (kind: EntityKind, name: string, weight = 1) => {\n if (!isPlausibleEntityName(kind, name)) return;\n const key = `${kind}|${name}`;\n const existing = entities.get(key);\n if (existing) {\n existing.weight = (existing.weight ?? 1) + weight;\n } else {\n entities.set(key, { kind, name, source: \"heuristic\", weight });\n }\n };\n\n // Files / paths\n for (const m of text.matchAll(PATH_RE)) {\n const raw = m[1];\n // Discriminate `repo_path` (no extension) vs `file` — both produce graph\n // nodes, but only `file` is treated as a file-system artifact.\n if (raw.includes(\".\") && !raw.endsWith(\"/\")) {\n push(\"file\", raw);\n } else {\n push(\"repo_path\", raw);\n }\n }\n\n // Functions in backticks\n for (const m of text.matchAll(FUNC_RE)) {\n push(\"function\", m[1]);\n }\n\n // Packages in backticks — scoped/hyphenated first (high confidence)\n for (const m of text.matchAll(SCOPED_PACKAGE_RE)) {\n push(\"library\", m[1]);\n }\n // Single-word backticked tokens, filtered by stop-list\n for (const m of text.matchAll(SIMPLE_PACKAGE_RE)) {\n const candidate = m[1];\n if (PACKAGE_STOPWORDS.has(candidate)) continue;\n push(\"library\", candidate, 0.7);\n }\n\n // CLI commands\n for (const m of text.matchAll(CLI_RE)) {\n const tool = m[1];\n const sub = m[2];\n // English filler after the tool (\"pnpm as\", \"npm in\") is not a command.\n if (CLI_SUBCOMMAND_STOPWORDS.has(sub)) {\n push(\"tool\", tool);\n continue;\n }\n push(\"tool\", tool);\n // Package managers / runtimes: the `<tool> <script>` pair is generic\n // tooling noise (\"pnpm build\", \"node dist\"). Keep only the tool node.\n if (TOOL_ONLY_CLIS.has(tool)) continue;\n push(\"command\", `${tool} ${sub}`);\n }\n\n // URLs\n for (const m of text.matchAll(URL_RE)) {\n push(\"url\", m[0]);\n }\n\n // Relations: split into sentences, look for a cue + two entity mentions.\n const sentences = text.split(/(?<=[.!?])\\s+|\\n+/);\n for (const sentence of sentences) {\n const cue = RELATION_CUES.find((c) => c.rx.test(sentence));\n if (!cue) continue;\n const mentioned: Array<{ kind: EntityKind; name: string; idx: number }> = [];\n for (const ent of entities.values()) {\n const idx = sentence.indexOf(ent.name);\n if (idx >= 0) mentioned.push({ kind: ent.kind, name: ent.name, idx });\n }\n if (mentioned.length < 2) continue;\n mentioned.sort((a, b) => a.idx - b.idx);\n relations.push({\n source: { kind: mentioned[0].kind, name: mentioned[0].name },\n target: { kind: mentioned[1].kind, name: mentioned[1].name },\n relation: cue.relation,\n confidence: 0.5,\n });\n }\n\n return { entities: Array.from(entities.values()), relations };\n}\n\n// ---- LLM enrichment --------------------------------------------------------\n\nexport const ENTITY_EXTRACTION_SYSTEM = `You extract code-graph entities and typed relations from short engineering notes (rules, decisions, gotchas).\n\nReturn STRICT JSON only — no prose, no fences. Shape:\n{\n \"entities\": [{\"kind\": \"<one of: file|function|library|tool|concept|repo_path|command|url>\", \"name\": \"<canonical surface form>\"}],\n \"relations\": [{\"source\": {\"kind\": \"...\", \"name\": \"...\"}, \"target\": {\"kind\": \"...\", \"name\": \"...\"}, \"relation\": \"<one of: uses|replaces|conflicts_with|tested_by|depends_on|references|part_of>\", \"confidence\": 0.0-1.0}]\n}\n\nRules:\n- Only include entities the text actually mentions. Do NOT invent.\n- Prefer the most specific kind: a file path is \"file\", a library name is \"library\", a CLI like \"npm install\" is \"command\".\n- \"concept\" is a last resort for domain words (\"authentication\", \"rate limiting\").\n- Skip generic English (pronouns, verbs, adjectives).\n- If the text is purely about user preferences or behaviour with no nameable artifact, return {\"entities\": [], \"relations\": []}.\n- Be conservative on relations — only include one when the text clearly states it.`;\n\nexport interface LlmExtractInput {\n memoryText: string;\n /** Optional seed list from the heuristic pass — saves the LLM a step. */\n seed?: ExtractedEntity[];\n}\n\nexport function buildExtractionPrompt(input: LlmExtractInput): string {\n const seedBlock = input.seed && input.seed.length > 0\n ? `\\n\\nHeuristic seed (use as hints, refine or override):\\n${input.seed\n .slice(0, 20)\n .map((e) => `- ${e.kind}: ${e.name}`)\n .join(\"\\n\")}`\n : \"\";\n return `Memory text:\\n\"\"\"\\n${input.memoryText}\\n\"\"\"${seedBlock}\\n\\nReturn STRICT JSON.`;\n}\n\n/**\n * Parse the LLM response into an ExtractionResult, tolerating fenced code\n * and surrounding prose. Returns null if no valid shape is recognised.\n */\nexport function parseLlmExtraction(raw: string): ExtractionResult | null {\n let text = raw.trim();\n // Strip code fences if present\n const fenceMatch = text.match(/```(?:json)?\\s*([\\s\\S]+?)\\s*```/);\n if (fenceMatch) text = fenceMatch[1].trim();\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n if (typeof parsed !== \"object\" || parsed === null) return null;\n const obj = parsed as Record<string, unknown>;\n const entities = sanitiseEntities(obj.entities);\n const relations = sanitiseRelations(obj.relations);\n return { entities, relations };\n}\n\nconst VALID_KINDS: ReadonlySet<EntityKind> = new Set<EntityKind>([\n \"file\", \"function\", \"library\", \"tool\", \"concept\", \"repo_path\", \"command\", \"url\",\n]);\nconst VALID_RELATIONS: ReadonlySet<RelationType> = new Set<RelationType>([\n \"uses\", \"replaces\", \"conflicts_with\", \"tested_by\", \"depends_on\", \"references\", \"part_of\",\n]);\n\nfunction sanitiseEntities(raw: unknown): ExtractedEntity[] {\n if (!Array.isArray(raw)) return [];\n const out: ExtractedEntity[] = [];\n for (const item of raw) {\n if (!item || typeof item !== \"object\") continue;\n const o = item as Record<string, unknown>;\n const kind = String(o.kind ?? \"\");\n const name = String(o.name ?? \"\").trim();\n if (!VALID_KINDS.has(kind as EntityKind)) continue;\n if (!isPlausibleEntityName(kind as EntityKind, name)) continue;\n out.push({ kind: kind as EntityKind, name, source: \"llm\" });\n }\n return out;\n}\n\nfunction sanitiseRelations(raw: unknown): ExtractedRelation[] {\n if (!Array.isArray(raw)) return [];\n const out: ExtractedRelation[] = [];\n for (const item of raw) {\n if (!item || typeof item !== \"object\") continue;\n const o = item as Record<string, unknown>;\n const rel = String(o.relation ?? \"\");\n if (!VALID_RELATIONS.has(rel as RelationType)) continue;\n const source = parseEndpoint(o.source);\n const target = parseEndpoint(o.target);\n if (!source || !target) continue;\n const confidence = typeof o.confidence === \"number\"\n ? Math.max(0, Math.min(1, o.confidence))\n : 0.6;\n out.push({ source, target, relation: rel as RelationType, confidence });\n }\n return out;\n}\n\nfunction parseEndpoint(raw: unknown): { kind: EntityKind; name: string } | null {\n if (!raw || typeof raw !== \"object\") return null;\n const o = raw as Record<string, unknown>;\n const kind = String(o.kind ?? \"\");\n const name = String(o.name ?? \"\").trim();\n if (!VALID_KINDS.has(kind as EntityKind)) return null;\n if (!isPlausibleEntityName(kind as EntityKind, name)) return null;\n return { kind: kind as EntityKind, name };\n}\n\n/**\n * Merge a heuristic pass with an LLM pass. LLM entries override heuristic\n * ones on the same (kind, name) — the model's source tag takes precedence\n * because it's the higher-quality signal.\n */\nexport function mergeExtractions(...passes: ExtractionResult[]): ExtractionResult {\n const entities = new Map<string, ExtractedEntity>();\n for (const pass of passes) {\n for (const ent of pass.entities) {\n const key = `${ent.kind}|${ent.name}`;\n const prev = entities.get(key);\n if (!prev || (prev.source === \"heuristic\" && ent.source === \"llm\")) {\n entities.set(key, ent);\n }\n }\n }\n // Deduplicate relations on (source, target, relation).\n const relations = new Map<string, ExtractedRelation>();\n for (const pass of passes) {\n for (const rel of pass.relations) {\n const key = `${rel.source.kind}|${rel.source.name}->${rel.relation}->${rel.target.kind}|${rel.target.name}`;\n const prev = relations.get(key);\n if (!prev || rel.confidence > prev.confidence) {\n relations.set(key, rel);\n }\n }\n }\n return {\n entities: Array.from(entities.values()),\n relations: Array.from(relations.values()),\n };\n}\n","/**\n * Glue: take a memory row, extract entities, persist them into the graph.\n *\n * The heuristic pass always runs (cheap, deterministic). The LLM enrichment\n * pass is left to the maintenance dispatcher — capture-path latency stays\n * regex-bounded, the graph fills in asynchronously.\n */\nimport type { RecallDb } from \"../db/client.js\";\nimport { getMemory } from \"../models/memory.js\";\nimport {\n heuristic,\n mergeExtractions,\n type ExtractionResult,\n} from \"./extractor.js\";\nimport {\n upsertEntity,\n linkMemoryToEntity,\n upsertRelation,\n type EntityRow,\n type EntityRelationRow,\n} from \"./store.js\";\n\nexport interface IngestSummary {\n memory_id: string;\n entities_created_or_updated: number;\n relations_created_or_updated: number;\n}\n\nexport interface MemoryLike {\n id: string;\n text: string;\n repo: string | null;\n}\n\n/**\n * Run the heuristic extractor on a memory and persist entities + relations.\n * Idempotent: calling twice for the same memory bumps mention counts but\n * does not duplicate rows. Safe to call from capture-path hot code.\n */\nexport function ingestMemoryHeuristic(db: RecallDb, memory: MemoryLike): IngestSummary {\n const extraction = heuristic(memory.text);\n return persistExtraction(db, memory, extraction);\n}\n\n/**\n * Apply a pre-computed ExtractionResult (e.g. from an LLM pass merged with\n * the heuristic pass) for a memory. Used by the maintenance dispatcher.\n */\nexport function ingestMemoryExtraction(\n db: RecallDb,\n memory: MemoryLike,\n extraction: ExtractionResult,\n): IngestSummary {\n return persistExtraction(db, memory, extraction);\n}\n\nexport function mergeAndIngest(\n db: RecallDb,\n memory: MemoryLike,\n passes: ExtractionResult[],\n): IngestSummary {\n return persistExtraction(db, memory, mergeExtractions(...passes));\n}\n\nfunction persistExtraction(\n db: RecallDb,\n memory: MemoryLike,\n extraction: ExtractionResult,\n): IngestSummary {\n const entityIndex = new Map<string, EntityRow>(); // dedupe by (kind|normalized) for relation lookup\n let entitiesTouched = 0;\n for (const ent of extraction.entities) {\n const row = upsertEntity(db, {\n kind: ent.kind,\n name: ent.name,\n repo: memory.repo,\n first_seen_memory_id: memory.id,\n });\n entityIndex.set(`${row.kind}|${row.normalized_name}`, row);\n linkMemoryToEntity(db, {\n memory_id: memory.id,\n entity_id: row.id,\n source: ent.source,\n weight: ent.weight,\n });\n entitiesTouched++;\n }\n\n let relationsTouched = 0;\n const lookupRow = (kind: string, name: string): EntityRow | undefined => {\n // upsertEntity normalizes internally, so we have to mirror that to look up\n // by the index key. Skip if the related entity wasn't in this batch.\n for (const row of entityIndex.values()) {\n if (row.kind === kind && row.name === name) return row;\n }\n return undefined;\n };\n\n for (const rel of extraction.relations) {\n const src = lookupRow(rel.source.kind, rel.source.name)\n ?? upsertEntity(db, { kind: rel.source.kind, name: rel.source.name, repo: memory.repo });\n const tgt = lookupRow(rel.target.kind, rel.target.name)\n ?? upsertEntity(db, { kind: rel.target.kind, name: rel.target.name, repo: memory.repo });\n if (src.id === tgt.id) continue;\n upsertRelation(db, {\n source_entity_id: src.id,\n target_entity_id: tgt.id,\n relation_type: rel.relation,\n source_memory_id: memory.id,\n confidence: rel.confidence,\n });\n relationsTouched++;\n }\n\n return {\n memory_id: memory.id,\n entities_created_or_updated: entitiesTouched,\n relations_created_or_updated: relationsTouched,\n };\n}\n\n/**\n * Best-effort heuristic ingest by memory id. Used by capture-path callers\n * (daemon /correct, /review, /scan) that want graph ingest to be a no-op on\n * failure rather than aborting the originating request.\n *\n * Only *active* (verified) memories enter the graph — candidate/transient\n * memories are skipped so the graph stays a projection of verified knowledge.\n * A candidate that is later promoted is ingested at promotion time.\n *\n * Returns the summary on success, `null` if the memory was not found, not\n * active, or if any error was swallowed.\n */\nexport function safeIngestMemoryById(db: RecallDb, memoryId: string): IngestSummary | null {\n try {\n const mem = getMemory(db, memoryId);\n if (!mem) return null;\n if (mem.status !== \"active\") return null;\n return ingestMemoryHeuristic(db, { id: mem.id, text: mem.text, repo: mem.repo });\n } catch (err) {\n console.error(\"[recall] graph ingest failed:\", { memory_id: memoryId, error: err });\n return null;\n }\n}\n\n// Re-export the row types so callers don't have to know about the\n// store layer's internal naming.\nexport type { EntityRow, EntityRelationRow };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,SAAS,cAAAA,mBAAkB;;;ACDpB,SAAS,UACd,QACA,KACA,OACM;AACN,SAAO,eAAe,QAAQ,KAAK;AAAA,IACjC,cAAc;AAAA,IACd,YAAY;AAAA,IACZ;AAAA,IACA,UAAU;AAAA,EACZ,CAAC;AACH;AAEO,SAAS,UACd,QACA,KACM;AACN,UAAQ,eAAe,QAAQ,GAAG;AACpC;;;AChBO,SAAS,oBAAoB,MAAsB;AACxD,SAAO,KACJ,YAAY,EACZ,QAAQ,QAAQ,GAAG,EACnB,QAAQ,kBAAkB,EAAE,EAC5B,KAAK;AACV;AAEO,SAAS,gBAAgB,OAMrB;AACT,SAAO;AAAA,IACL;AAAA,IACA,MAAM;AAAA,IACN,MAAM;AAAA,IACN,MAAM,QAAQ;AAAA,IACd,MAAM,cAAc;AAAA,IACpB,oBAAoB,MAAM,IAAI;AAAA,EAChC,EAAE,KAAK,GAAQ;AACjB;AAEO,SAAS,wBAAwB,OAK7B;AACT,SAAO;AAAA,IACL;AAAA,IACA,MAAM,QAAQ;AAAA,IACd,MAAM,cAAc;AAAA,IACpB,MAAM;AAAA,IACN,oBAAoB,MAAM,IAAI;AAAA,EAChC,EAAE,KAAK,GAAQ;AACjB;AAEO,SAAS,uBAAuB,OAQrB;AAChB,MAAI,CAAC,MAAM,WAAY,QAAO;AAC9B,SAAO;AAAA,IACL;AAAA,IACA,MAAM;AAAA,IACN,MAAM,QAAQ;AAAA,IACd,MAAM,QAAQ;AAAA,IACd,MAAM;AAAA,IACN,MAAM;AAAA,IACN,iBAAiB,oBAAoB,MAAM,WAAW,CAAC,C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