@edihasaj/recall 0.8.20 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/README.md +13 -0
  2. package/dist/{chunk-6I5U6KS3.js → chunk-5K2LTXNW.js} +17 -15
  3. package/dist/chunk-5K2LTXNW.js.map +1 -0
  4. package/dist/{chunk-O4KCMCJG.js → chunk-A27AP4NR.js} +21 -6
  5. package/dist/chunk-A27AP4NR.js.map +1 -0
  6. package/dist/{chunk-VT5VAEHY.js → chunk-CW3XJDH7.js} +2 -2
  7. package/dist/{chunk-K6AFGQWR.js → chunk-DRAOZ2RN.js} +4 -4
  8. package/dist/{chunk-M7OKBKKU.js → chunk-EAFRT7RX.js} +2 -2
  9. package/dist/{chunk-ZBIJDXA7.js → chunk-FPZ3GBXP.js} +5 -5
  10. package/dist/{chunk-4CV4JOE5.js → chunk-JYWURG5T.js} +8 -3
  11. package/dist/{chunk-55KCGAOX.js → chunk-LUIYWYOT.js} +2 -2
  12. package/dist/{chunk-S7FJMV5O.js → chunk-OADI5XD2.js} +8 -8
  13. package/dist/{chunk-KG7YFARS.js → chunk-PQJRYAVG.js} +92 -14
  14. package/dist/chunk-PQJRYAVG.js.map +1 -0
  15. package/dist/{chunk-QKN6IWJ3.js → chunk-SISLEKTR.js} +54 -68
  16. package/dist/chunk-SISLEKTR.js.map +1 -0
  17. package/dist/{chunk-DNFKAHS6.js → chunk-VYZSP23L.js} +95 -12
  18. package/dist/chunk-VYZSP23L.js.map +1 -0
  19. package/dist/{chunk-LGTD5A4A.js → chunk-XRWHIL74.js} +75 -15
  20. package/dist/chunk-XRWHIL74.js.map +1 -0
  21. package/dist/{chunk-NAYZL5XI.js → chunk-YDSCPOIJ.js} +4 -4
  22. package/dist/{cleanup-HWQCVPY4.js → cleanup-3JDS7MHX.js} +9 -9
  23. package/dist/cli.js +950 -161
  24. package/dist/cli.js.map +1 -1
  25. package/dist/daemon.js +112 -56
  26. package/dist/daemon.js.map +1 -1
  27. package/dist/dispatcher-LV6WGHR2.js +20 -0
  28. package/dist/{embeddings-LNMNKWB7.js → embeddings-E362AC3R.js} +5 -5
  29. package/dist/ingest-7FAOX7YV.js +18 -0
  30. package/dist/{keychain-5QG52ANO.js → keychain-PWFWKTZW.js} +3 -3
  31. package/dist/mcp.js +12 -12
  32. package/dist/{memory-value-GH67CBQP.js → memory-value-V4MH2DYO.js} +9 -9
  33. package/dist/quality-5SB4S5G2.js +23 -0
  34. package/dist/retrieval-YU2PLBUS.js +13 -0
  35. package/dist/{store-OPRTGS73.js → store-5C7ZKKZF.js} +4 -4
  36. package/dist/sync-server.js +1 -1
  37. package/dist/{tasks-LOZ7XWON.js → tasks-DT6QPIKV.js} +9 -9
  38. package/dist/{usage-CAAACLUR.js → usage-VQ5LJCNH.js} +4 -4
  39. package/dist/webui/assets/{index-BODg2A9d.js → index-DAoAhOb4.js} +244 -244
  40. package/dist/webui/assets/{index-BODg2A9d.js.map → index-DAoAhOb4.js.map} +1 -1
  41. package/dist/webui/index.html +1 -1
  42. package/package.json +34 -2
  43. package/dist/chunk-6I5U6KS3.js.map +0 -1
  44. package/dist/chunk-DNFKAHS6.js.map +0 -1
  45. package/dist/chunk-KG7YFARS.js.map +0 -1
  46. package/dist/chunk-LGTD5A4A.js.map +0 -1
  47. package/dist/chunk-O4KCMCJG.js.map +0 -1
  48. package/dist/chunk-QKN6IWJ3.js.map +0 -1
  49. package/dist/dispatcher-RU25CZK3.js +0 -20
  50. package/dist/ingest-QSOE5XJZ.js +0 -18
  51. package/dist/quality-PZ36JND4.js +0 -23
  52. package/dist/retrieval-HIE5MASN.js +0 -13
  53. /package/dist/{chunk-VT5VAEHY.js.map → chunk-CW3XJDH7.js.map} +0 -0
  54. /package/dist/{chunk-K6AFGQWR.js.map → chunk-DRAOZ2RN.js.map} +0 -0
  55. /package/dist/{chunk-M7OKBKKU.js.map → chunk-EAFRT7RX.js.map} +0 -0
  56. /package/dist/{chunk-ZBIJDXA7.js.map → chunk-FPZ3GBXP.js.map} +0 -0
  57. /package/dist/{chunk-4CV4JOE5.js.map → chunk-JYWURG5T.js.map} +0 -0
  58. /package/dist/{chunk-55KCGAOX.js.map → chunk-LUIYWYOT.js.map} +0 -0
  59. /package/dist/{chunk-S7FJMV5O.js.map → chunk-OADI5XD2.js.map} +0 -0
  60. /package/dist/{chunk-NAYZL5XI.js.map → chunk-YDSCPOIJ.js.map} +0 -0
  61. /package/dist/{cleanup-HWQCVPY4.js.map → cleanup-3JDS7MHX.js.map} +0 -0
  62. /package/dist/{dispatcher-RU25CZK3.js.map → dispatcher-LV6WGHR2.js.map} +0 -0
  63. /package/dist/{embeddings-LNMNKWB7.js.map → embeddings-E362AC3R.js.map} +0 -0
  64. /package/dist/{ingest-QSOE5XJZ.js.map → ingest-7FAOX7YV.js.map} +0 -0
  65. /package/dist/{keychain-5QG52ANO.js.map → keychain-PWFWKTZW.js.map} +0 -0
  66. /package/dist/{memory-value-GH67CBQP.js.map → memory-value-V4MH2DYO.js.map} +0 -0
  67. /package/dist/{quality-PZ36JND4.js.map → quality-5SB4S5G2.js.map} +0 -0
  68. /package/dist/{retrieval-HIE5MASN.js.map → retrieval-YU2PLBUS.js.map} +0 -0
  69. /package/dist/{store-OPRTGS73.js.map → store-5C7ZKKZF.js.map} +0 -0
  70. /package/dist/{tasks-LOZ7XWON.js.map → tasks-DT6QPIKV.js.map} +0 -0
  71. /package/dist/{usage-CAAACLUR.js.map → usage-VQ5LJCNH.js.map} +0 -0
@@ -2,13 +2,13 @@ import {
2
2
  CONFIDENCE,
3
3
  PROMOTION,
4
4
  queueMemoryEmbeddingSync
5
- } from "./chunk-KG7YFARS.js";
5
+ } from "./chunk-PQJRYAVG.js";
6
6
  import {
7
7
  isPlausibleEntityName,
8
8
  linkMemoryToEntity,
9
9
  upsertEntity,
10
10
  upsertRelation
11
- } from "./chunk-M7OKBKKU.js";
11
+ } from "./chunk-EAFRT7RX.js";
12
12
  import {
13
13
  and,
14
14
  eq,
@@ -18,11 +18,24 @@ import {
18
18
  like,
19
19
  memories,
20
20
  sql
21
- } from "./chunk-55KCGAOX.js";
21
+ } from "./chunk-LUIYWYOT.js";
22
22
 
23
23
  // src/models/memory.ts
24
24
  import { randomUUID } from "crypto";
25
25
 
26
+ // src/security/object.ts
27
+ function defineOwn(target, key, value) {
28
+ Object.defineProperty(target, key, {
29
+ configurable: true,
30
+ enumerable: true,
31
+ value,
32
+ writable: true
33
+ });
34
+ }
35
+ function deleteOwn(target, key) {
36
+ Reflect.deleteProperty(target, key);
37
+ }
38
+
26
39
  // src/models/dedupe.ts
27
40
  function normalizeDedupeText(text) {
28
41
  return text.toLowerCase().replace(/\s+/g, " ").replace(/[\s.;:,!?`]+$/g, "").trim();
@@ -81,7 +94,7 @@ function stripVolatileFields(value) {
81
94
  for (const [key, entry] of Object.entries(value)) {
82
95
  if (/_at$/u.test(key) || key === "timestamp") continue;
83
96
  if (entry === void 0) continue;
84
- out[key] = stripVolatileFields(entry);
97
+ defineOwn(out, key, stripVolatileFields(entry));
85
98
  }
86
99
  return out;
87
100
  }
@@ -751,12 +764,14 @@ function safeIngestMemoryById(db, memoryId) {
751
764
  if (mem.status !== "active") return null;
752
765
  return ingestMemoryHeuristic(db, { id: mem.id, text: mem.text, repo: mem.repo });
753
766
  } catch (err) {
754
- console.error(`[recall] graph ingest failed for ${memoryId}:`, err);
767
+ console.error("[recall] graph ingest failed:", { memory_id: memoryId, error: err });
755
768
  return null;
756
769
  }
757
770
  }
758
771
 
759
772
  export {
773
+ defineOwn,
774
+ deleteOwn,
760
775
  normalizeDedupeText,
761
776
  memoryDedupeKey,
762
777
  historySnippetDedupeKey,
@@ -786,4 +801,4 @@ export {
786
801
  getMemoryFeedbackSummaries,
787
802
  feedbackWeightedScore
788
803
  };
789
- //# sourceMappingURL=chunk-O4KCMCJG.js.map
804
+ //# sourceMappingURL=chunk-A27AP4NR.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/models/memory.ts","../src/security/object.ts","../src/models/dedupe.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 { 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 const dedupeKey = input.dedupe === false\n ? null\n : memoryDedupeKey({\n type: input.type,\n scope: input.scope,\n repo: input.repo ?? null,\n path_scope: input.path_scope ?? null,\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: input.scope,\n path_scope: input.path_scope ?? null,\n repo: input.repo ?? null,\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\nexport function rejectMemory(db: RecallDb, id: string): boolean {\n const mem = getMemory(db, id);\n if (!mem) return false;\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 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\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 * 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,kBAAkB;;;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,SAA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,WAAW,OAAO;AAAA,IAClB,6BAA6B;AAAA,IAC7B,8BAA8B;AAAA,EAChC;AACF;AAcO,SAAS,qBAAqB,IAAc,UAAwC;AACzF,MAAI;AACF,UAAM,MAAM,UAAU,IAAI,QAAQ;AAClC,QAAI,CAAC,IAAK,QAAO;AACjB,QAAI,IAAI,WAAW,SAAU,QAAO;AACpC,WAAO,sBAAsB,IAAI,EAAE,IAAI,IAAI,IAAI,MAAM,IAAI,MAAM,MAAM,IAAI,KAAK,CAAC;AAAA,EACjF,SAAS,KAAK;AACZ,YAAQ,MAAM,iCAAiC,EAAE,WAAW,UAAU,OAAO,IAAI,CAAC;AAClF,WAAO;AAAA,EACT;AACF;","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  sql
3
- } from "./chunk-55KCGAOX.js";
3
+ } from "./chunk-LUIYWYOT.js";
4
4
 
5
5
  // node_modules/drizzle-orm/sql/expressions/select.js
6
6
  function asc(column) {
@@ -14,4 +14,4 @@ export {
14
14
  asc,
15
15
  desc
16
16
  };
17
- //# sourceMappingURL=chunk-VT5VAEHY.js.map
17
+ //# sourceMappingURL=chunk-CW3XJDH7.js.map
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  computeMemoryValueReport
3
- } from "./chunk-ZBIJDXA7.js";
3
+ } from "./chunk-FPZ3GBXP.js";
4
4
  import {
5
5
  desc
6
- } from "./chunk-VT5VAEHY.js";
6
+ } from "./chunk-CW3XJDH7.js";
7
7
  import {
8
8
  and,
9
9
  eq,
@@ -14,7 +14,7 @@ import {
14
14
  memoryInjections,
15
15
  qualitySnapshots,
16
16
  sql
17
- } from "./chunk-55KCGAOX.js";
17
+ } from "./chunk-LUIYWYOT.js";
18
18
 
19
19
  // src/maintenance/quality.ts
20
20
  import { randomUUID } from "crypto";
@@ -180,4 +180,4 @@ export {
180
180
  diffQualitySnapshots,
181
181
  formatQualityReport
182
182
  };
183
- //# sourceMappingURL=chunk-K6AFGQWR.js.map
183
+ //# sourceMappingURL=chunk-DRAOZ2RN.js.map
@@ -8,7 +8,7 @@ import {
8
8
  memoryEntities,
9
9
  or,
10
10
  sql
11
- } from "./chunk-55KCGAOX.js";
11
+ } from "./chunk-LUIYWYOT.js";
12
12
 
13
13
  // src/graph/store.ts
14
14
  import { randomUUID } from "crypto";
@@ -285,4 +285,4 @@ export {
285
285
  countRelations,
286
286
  clearGraph
287
287
  };
288
- //# sourceMappingURL=chunk-M7OKBKKU.js.map
288
+ //# sourceMappingURL=chunk-EAFRT7RX.js.map
@@ -1,18 +1,18 @@
1
1
  import {
2
2
  asc,
3
3
  desc
4
- } from "./chunk-VT5VAEHY.js";
4
+ } from "./chunk-CW3XJDH7.js";
5
5
  import {
6
6
  getMemory,
7
7
  promoteMemory,
8
8
  queryMemories
9
- } from "./chunk-O4KCMCJG.js";
9
+ } from "./chunk-A27AP4NR.js";
10
10
  import {
11
11
  cosineSimilarity,
12
12
  generateEmbedding,
13
13
  loadEmbedding,
14
14
  loadEmbeddingConfigFromEnv
15
- } from "./chunk-KG7YFARS.js";
15
+ } from "./chunk-PQJRYAVG.js";
16
16
  import {
17
17
  and,
18
18
  eq,
@@ -23,7 +23,7 @@ import {
23
23
  memoryInjections,
24
24
  memoryValueEvents,
25
25
  sql
26
- } from "./chunk-55KCGAOX.js";
26
+ } from "./chunk-LUIYWYOT.js";
27
27
 
28
28
  // src/models/memory-value.ts
29
29
  import { randomUUID as randomUUID2 } from "crypto";
@@ -706,4 +706,4 @@ export {
706
706
  detectAndRecordRetrievalMissesSemantic,
707
707
  computeMemoryValueReport
708
708
  };
709
- //# sourceMappingURL=chunk-ZBIJDXA7.js.map
709
+ //# sourceMappingURL=chunk-FPZ3GBXP.js.map
@@ -2,8 +2,13 @@ var __defProp = Object.defineProperty;
2
2
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
3
  var __getOwnPropNames = Object.getOwnPropertyNames;
4
4
  var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __esm = (fn, res) => function __init() {
6
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ var __esm = (fn, res, err) => function __init() {
6
+ if (err) throw err[0];
7
+ try {
8
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
+ } catch (e) {
10
+ throw err = [e], e;
11
+ }
7
12
  };
8
13
  var __export = (target, all) => {
9
14
  for (var name in all)
@@ -24,4 +29,4 @@ export {
24
29
  __export,
25
30
  __toCommonJS
26
31
  };
27
- //# sourceMappingURL=chunk-4CV4JOE5.js.map
32
+ //# sourceMappingURL=chunk-JYWURG5T.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  __export
3
- } from "./chunk-4CV4JOE5.js";
3
+ } from "./chunk-JYWURG5T.js";
4
4
 
5
5
  // node_modules/drizzle-orm/entity.js
6
6
  var entityKind = /* @__PURE__ */ Symbol.for("drizzle:entityKind");
@@ -2647,4 +2647,4 @@ export {
2647
2647
  maintenanceCleanupLog,
2648
2648
  schema_exports
2649
2649
  };
2650
- //# sourceMappingURL=chunk-55KCGAOX.js.map
2650
+ //# sourceMappingURL=chunk-LUIYWYOT.js.map
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  graphQuery
3
- } from "./chunk-NAYZL5XI.js";
3
+ } from "./chunk-YDSCPOIJ.js";
4
4
  import {
5
5
  captureCorrectionFallback,
6
6
  compileContext,
@@ -26,7 +26,7 @@ import {
26
26
  scanAndStore,
27
27
  sessionEndFallback,
28
28
  signalOutcomeFallback
29
- } from "./chunk-QKN6IWJ3.js";
29
+ } from "./chunk-SISLEKTR.js";
30
30
  import {
31
31
  DEFAULT_LEASE_SECONDS,
32
32
  TaskClaimConflictError,
@@ -47,27 +47,27 @@ import {
47
47
  releaseTask,
48
48
  rollbackMemory,
49
49
  submitTask
50
- } from "./chunk-6I5U6KS3.js";
50
+ } from "./chunk-5K2LTXNW.js";
51
51
  import {
52
52
  recordCompletionUseValueEventsSemantic
53
- } from "./chunk-ZBIJDXA7.js";
53
+ } from "./chunk-FPZ3GBXP.js";
54
54
  import {
55
55
  confirmMemory,
56
56
  demoteGlobalMemory,
57
57
  getMemory,
58
58
  queryMemories,
59
59
  rejectMemory
60
- } from "./chunk-O4KCMCJG.js";
60
+ } from "./chunk-A27AP4NR.js";
61
61
  import {
62
62
  loadEmbeddingConfigFromEnv,
63
63
  tagActivitySource
64
- } from "./chunk-KG7YFARS.js";
64
+ } from "./chunk-PQJRYAVG.js";
65
65
  import {
66
66
  getEntity,
67
67
  listEntities,
68
68
  listMemoryIdsForEntity,
69
69
  neighborsOf
70
- } from "./chunk-M7OKBKKU.js";
70
+ } from "./chunk-EAFRT7RX.js";
71
71
 
72
72
  // src/mcp/factory.ts
73
73
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
@@ -1197,4 +1197,4 @@ function createRecallMcpServer(db = initDb()) {
1197
1197
  export {
1198
1198
  createRecallMcpServer
1199
1199
  };
1200
- //# sourceMappingURL=chunk-S7FJMV5O.js.map
1200
+ //# sourceMappingURL=chunk-OADI5XD2.js.map
@@ -2,13 +2,13 @@ import {
2
2
  getProviderConfig,
3
3
  hasProviderConfigured,
4
4
  init_keychain
5
- } from "./chunk-DNFKAHS6.js";
5
+ } from "./chunk-VYZSP23L.js";
6
6
  import {
7
7
  eq,
8
8
  llmUsage,
9
9
  memories,
10
10
  memoryEmbeddings
11
- } from "./chunk-55KCGAOX.js";
11
+ } from "./chunk-LUIYWYOT.js";
12
12
 
13
13
  // src/embeddings/embeddings.ts
14
14
  import { createHash as createHash2 } from "crypto";
@@ -1316,12 +1316,12 @@ function expandTokenWithSynonyms(token, prefixDisabled, synonymsDisabled) {
1316
1316
  function buildFtsQuery(query) {
1317
1317
  const tokens = query.match(/[A-Za-z0-9_.:/-]+/g)?.map((token) => token.replace(/"/g, '""')).filter(Boolean) ?? [];
1318
1318
  if (tokens.length === 0) return null;
1319
- const join3 = process.env.RECALL_FTS_MODE === "or" ? " OR " : " AND ";
1319
+ const join4 = process.env.RECALL_FTS_MODE === "or" ? " OR " : " AND ";
1320
1320
  const prefixDisabled = process.env.RECALL_FTS_PREFIX === "false";
1321
1321
  const synonymsDisabled = process.env.RECALL_SYNONYMS === "false";
1322
1322
  return tokens.map(
1323
1323
  (token) => expandTokenWithSynonyms(token, prefixDisabled, synonymsDisabled)
1324
- ).join(join3);
1324
+ ).join(join4);
1325
1325
  }
1326
1326
  function getFtsCreateSql(db, table) {
1327
1327
  const row = getSqlite2(db).prepare("select sql from sqlite_master where type = 'table' and name = ?").get(table);
@@ -1480,8 +1480,8 @@ function searchMemoryFtsIndex(db, query, options = {}) {
1480
1480
 
1481
1481
  // src/embeddings/hyde.ts
1482
1482
  import { createHash } from "crypto";
1483
- import { existsSync as existsSync3, readFileSync as readFileSync2, writeFileSync, mkdirSync as mkdirSync2 } from "fs";
1484
- import { dirname } from "path";
1483
+ import { mkdirSync as mkdirSync2 } from "fs";
1484
+ import { dirname as dirname2 } from "path";
1485
1485
 
1486
1486
  // src/llm/client.ts
1487
1487
  init_keychain();
@@ -1548,6 +1548,8 @@ async function callOpenAi(apiKey, model, input) {
1548
1548
  const started = Date.now();
1549
1549
  const response = await fetch("https://api.openai.com/v1/chat/completions", {
1550
1550
  method: "POST",
1551
+ redirect: "error",
1552
+ signal: AbortSignal.timeout(12e4),
1551
1553
  headers: {
1552
1554
  "Content-Type": "application/json",
1553
1555
  Authorization: `Bearer ${apiKey}`
@@ -1589,6 +1591,8 @@ async function callAzureOpenAi(config, deployment, input) {
1589
1591
  const url = `${config.endpoint}/openai/deployments/${encodeURIComponent(deployment)}/chat/completions?api-version=${encodeURIComponent(config.api_version)}`;
1590
1592
  const response = await fetch(url, {
1591
1593
  method: "POST",
1594
+ redirect: "error",
1595
+ signal: AbortSignal.timeout(12e4),
1592
1596
  headers: {
1593
1597
  "Content-Type": "application/json",
1594
1598
  "api-key": config.key
@@ -1628,6 +1632,8 @@ async function callAnthropic(apiKey, model, input) {
1628
1632
  const started = Date.now();
1629
1633
  const response = await fetch("https://api.anthropic.com/v1/messages", {
1630
1634
  method: "POST",
1635
+ redirect: "error",
1636
+ signal: AbortSignal.timeout(12e4),
1631
1637
  headers: {
1632
1638
  "Content-Type": "application/json",
1633
1639
  "x-api-key": apiKey,
@@ -1705,6 +1711,71 @@ async function safeText(response) {
1705
1711
 
1706
1712
  // src/embeddings/hyde.ts
1707
1713
  init_keychain();
1714
+
1715
+ // src/security/atomic-file.ts
1716
+ import {
1717
+ closeSync,
1718
+ constants,
1719
+ fstatSync,
1720
+ fsyncSync,
1721
+ openSync,
1722
+ readFileSync as readFileSync2,
1723
+ renameSync,
1724
+ unlinkSync,
1725
+ writeFileSync
1726
+ } from "fs";
1727
+ import { randomUUID as randomUUID2 } from "crypto";
1728
+ import { basename, dirname, join as join2 } from "path";
1729
+ function readUtf8FileIfExists(path) {
1730
+ let fd;
1731
+ try {
1732
+ const noFollow = process.platform === "win32" ? 0 : constants.O_NOFOLLOW;
1733
+ fd = openSync(path, constants.O_RDONLY | noFollow);
1734
+ } catch (error) {
1735
+ if (isErrorCode(error, "ENOENT")) return null;
1736
+ throw error;
1737
+ }
1738
+ try {
1739
+ if (!fstatSync(fd).isFile()) {
1740
+ throw new Error(`Refusing to read non-file path: ${path}`);
1741
+ }
1742
+ return readFileSync2(fd, "utf-8");
1743
+ } finally {
1744
+ closeSync(fd);
1745
+ }
1746
+ }
1747
+ function atomicWriteUtf8File(path, content, mode = 384) {
1748
+ const tempPath = join2(
1749
+ dirname(path),
1750
+ `.${basename(path)}.${process.pid}.${randomUUID2()}.tmp`
1751
+ );
1752
+ let fd = null;
1753
+ try {
1754
+ fd = openSync(
1755
+ tempPath,
1756
+ constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,
1757
+ mode
1758
+ );
1759
+ writeFileSync(fd, content, "utf-8");
1760
+ fsyncSync(fd);
1761
+ closeSync(fd);
1762
+ fd = null;
1763
+ renameSync(tempPath, path);
1764
+ } catch (error) {
1765
+ if (fd !== null) closeSync(fd);
1766
+ try {
1767
+ unlinkSync(tempPath);
1768
+ } catch (cleanupError) {
1769
+ if (!isErrorCode(cleanupError, "ENOENT")) throw cleanupError;
1770
+ }
1771
+ throw error;
1772
+ }
1773
+ }
1774
+ function isErrorCode(error, code) {
1775
+ return error instanceof Error && "code" in error && error.code === code;
1776
+ }
1777
+
1778
+ // src/embeddings/hyde.ts
1708
1779
  var HYDE_SYSTEM_PROMPT = "Generate a single short sentence that plausibly answers the user's question. Do not include preamble, qualifications, or follow-up questions. If the question is unanswerable without specific personal context, produce a sentence in the format of a likely answer using neutral placeholders. Output only the sentence.";
1709
1780
  var MEMORY_CACHE_MAX = 512;
1710
1781
  var memoryCache = /* @__PURE__ */ new Map();
@@ -1727,9 +1798,11 @@ function loadDiskCache() {
1727
1798
  if (diskCacheLoaded) return;
1728
1799
  diskCacheLoaded = true;
1729
1800
  const path = process.env.RECALL_HYDE_CACHE_PATH;
1730
- if (!path || !existsSync3(path)) return;
1801
+ if (!path) return;
1731
1802
  try {
1732
- diskCache = JSON.parse(readFileSync2(path, "utf-8"));
1803
+ const raw = readUtf8FileIfExists(path);
1804
+ if (raw === null) return;
1805
+ diskCache = JSON.parse(raw);
1733
1806
  } catch {
1734
1807
  diskCache = {};
1735
1808
  }
@@ -1738,8 +1811,8 @@ function persistDiskCache() {
1738
1811
  const path = process.env.RECALL_HYDE_CACHE_PATH;
1739
1812
  if (!path) return;
1740
1813
  try {
1741
- mkdirSync2(dirname(path), { recursive: true });
1742
- writeFileSync(path, JSON.stringify(diskCache, null, 2));
1814
+ mkdirSync2(dirname2(path), { recursive: true });
1815
+ atomicWriteUtf8File(path, JSON.stringify(diskCache, null, 2));
1743
1816
  } catch {
1744
1817
  }
1745
1818
  }
@@ -1788,7 +1861,7 @@ async function generateHydeText(db, query) {
1788
1861
 
1789
1862
  // src/embeddings/reranker.ts
1790
1863
  import { mkdirSync as mkdirSync3 } from "fs";
1791
- import { join as join2 } from "path";
1864
+ import { join as join3 } from "path";
1792
1865
  import {
1793
1866
  pipeline as pipeline5
1794
1867
  } from "@huggingface/transformers";
@@ -1800,7 +1873,7 @@ function getModel5() {
1800
1873
  }
1801
1874
  async function getReranker() {
1802
1875
  const model = getModel5();
1803
- const cacheDir = join2(getEmbeddingCacheRoot(), "rerank", ...model.split("/"));
1876
+ const cacheDir = join3(getEmbeddingCacheRoot(), "rerank", ...model.split("/"));
1804
1877
  mkdirSync3(cacheDir, { recursive: true });
1805
1878
  rerankerPromise ??= pipeline5("text-classification", model, {
1806
1879
  cache_dir: cacheDir,
@@ -2030,7 +2103,10 @@ function queueMemoryEmbeddingSync(db, memoryId, config = loadEmbeddingConfigFrom
2030
2103
  if (!config) return null;
2031
2104
  const job = syncMemoryEmbedding(db, memoryId, config).then(() => void 0).catch((error) => {
2032
2105
  const message = error instanceof Error ? error.message : String(error);
2033
- console.error(`[recall] embedding sync failed for ${memoryId.slice(0, 8)}: ${message}`);
2106
+ console.error("[recall] embedding sync failed:", {
2107
+ memory_id: memoryId.slice(0, 8),
2108
+ error: message
2109
+ });
2034
2110
  }).finally(() => {
2035
2111
  pendingEmbeddingJobs.delete(job);
2036
2112
  });
@@ -2323,6 +2399,8 @@ export {
2323
2399
  searchMemoryFtsIndex,
2324
2400
  LlmCredentialError,
2325
2401
  callLlm,
2402
+ readUtf8FileIfExists,
2403
+ atomicWriteUtf8File,
2326
2404
  loadEmbeddingConfigFromEnv,
2327
2405
  getEmbeddingModelInfo,
2328
2406
  ensureEmbeddingProviderReady,
@@ -2344,4 +2422,4 @@ export {
2344
2422
  findSemanticDuplicates,
2345
2423
  findSimilarRejectedExemplar
2346
2424
  };
2347
- //# sourceMappingURL=chunk-KG7YFARS.js.map
2425
+ //# sourceMappingURL=chunk-PQJRYAVG.js.map