@edihasaj/recall 1.3.1 → 1.4.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.
- package/dist/{chunk-427VWTG6.js → chunk-53GKSF42.js} +5 -5
- package/dist/{chunk-THX57BL4.js → chunk-65XK27KK.js} +70 -31
- package/dist/chunk-65XK27KK.js.map +1 -0
- package/dist/{chunk-ZPAXZDWJ.js → chunk-6QFOCUEJ.js} +9 -9
- package/dist/chunk-6QFOCUEJ.js.map +1 -0
- package/dist/{chunk-ZXLAD4CS.js → chunk-7Q5CBVUT.js} +17 -7
- package/dist/{chunk-ZXLAD4CS.js.map → chunk-7Q5CBVUT.js.map} +1 -1
- package/dist/{chunk-FUDWE6KW.js → chunk-JO5LRCA2.js} +1 -5
- package/dist/{chunk-FUDWE6KW.js.map → chunk-JO5LRCA2.js.map} +1 -1
- package/dist/{chunk-MPWXWBSG.js → chunk-JSTZKFZR.js} +2 -2
- package/dist/{chunk-VP25EEOH.js → chunk-MMYLXICL.js} +2 -2
- package/dist/{chunk-6FE2IKPF.js → chunk-UWERS646.js} +2 -2
- package/dist/{cleanup-PE3BFDMV.js → cleanup-RHNBHBNP.js} +3 -3
- package/dist/cli.js +22 -20
- package/dist/cli.js.map +1 -1
- package/dist/daemon.js +11 -9
- package/dist/daemon.js.map +1 -1
- package/dist/{dispatcher-YCWDNYU3.js → dispatcher-ON7LNX6X.js} +3 -3
- package/dist/{ingest-LZXTAMEZ.js → ingest-MHPMJPUA.js} +2 -2
- package/dist/mcp.js +6 -6
- package/dist/{memory-value-L4VZNKK5.js → memory-value-6JUQEYJZ.js} +3 -3
- package/dist/{quality-MEI6N7IW.js → quality-HVTIOIXP.js} +4 -4
- package/dist/{retrieval-WDZXSBKB.js → retrieval-72EIHKRF.js} +3 -3
- package/dist/{tasks-6EJMXJQV.js → tasks-AJ62N26N.js} +3 -3
- package/package.json +1 -1
- package/dist/chunk-THX57BL4.js.map +0 -1
- package/dist/chunk-ZPAXZDWJ.js.map +0 -1
- /package/dist/{chunk-427VWTG6.js.map → chunk-53GKSF42.js.map} +0 -0
- /package/dist/{chunk-MPWXWBSG.js.map → chunk-JSTZKFZR.js.map} +0 -0
- /package/dist/{chunk-VP25EEOH.js.map → chunk-MMYLXICL.js.map} +0 -0
- /package/dist/{chunk-6FE2IKPF.js.map → chunk-UWERS646.js.map} +0 -0
- /package/dist/{cleanup-PE3BFDMV.js.map → cleanup-RHNBHBNP.js.map} +0 -0
- /package/dist/{dispatcher-YCWDNYU3.js.map → dispatcher-ON7LNX6X.js.map} +0 -0
- /package/dist/{ingest-LZXTAMEZ.js.map → ingest-MHPMJPUA.js.map} +0 -0
- /package/dist/{memory-value-L4VZNKK5.js.map → memory-value-6JUQEYJZ.js.map} +0 -0
- /package/dist/{quality-MEI6N7IW.js.map → quality-HVTIOIXP.js.map} +0 -0
- /package/dist/{retrieval-WDZXSBKB.js.map → retrieval-72EIHKRF.js.map} +0 -0
- /package/dist/{tasks-6EJMXJQV.js.map → tasks-AJ62N26N.js.map} +0 -0
|
@@ -389,9 +389,6 @@ function recordFeedback(db, memoryId, sessionId, injected, outcome) {
|
|
|
389
389
|
}
|
|
390
390
|
return id;
|
|
391
391
|
}
|
|
392
|
-
function getMemoryFeedback(db, memoryId) {
|
|
393
|
-
return db.select().from(feedbackEvents).where(eq(feedbackEvents.memory_id, memoryId)).all();
|
|
394
|
-
}
|
|
395
392
|
function getMemoryFeedbackSummaries(db, memoryIds) {
|
|
396
393
|
const empty = () => ({
|
|
397
394
|
followed: 0,
|
|
@@ -813,8 +810,7 @@ export {
|
|
|
813
810
|
incrementMemoryRepetition,
|
|
814
811
|
countDistinctCorrectionSessions,
|
|
815
812
|
recordFeedback,
|
|
816
|
-
getMemoryFeedback,
|
|
817
813
|
getMemoryFeedbackSummaries,
|
|
818
814
|
feedbackWeightedScore
|
|
819
815
|
};
|
|
820
|
-
//# sourceMappingURL=chunk-
|
|
816
|
+
//# sourceMappingURL=chunk-JO5LRCA2.js.map
|
|
@@ -1 +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 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\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\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 * 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,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,MAAM,iCAAiC,EAAE,WAAW,UAAU,OAAO,IAAI,CAAC;AAClF,WAAO;AAAA,EACT;AACF;","names":[]}
|
|
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 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\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\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 * 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,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,CAAC,CAAC;AAAA,IACzD,iBAAiB,oBAAoB,MAAM,UAAU,CAAC,CAAC,CAAC;AAAA,EAC1D,EAAE,KAAK,GAAQ;AACjB;AAEO,SAAS,kBAAkB,OAMhB;AAChB,MAAI,CAA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T;AACF;","names":[]}
|
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
getMemory,
|
|
10
10
|
promoteMemory,
|
|
11
11
|
queryMemories
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-JO5LRCA2.js";
|
|
13
13
|
import {
|
|
14
14
|
cosineSimilarity,
|
|
15
15
|
generateEmbedding,
|
|
@@ -612,4 +612,4 @@ export {
|
|
|
612
612
|
detectAndRecordRetrievalMissesSemantic,
|
|
613
613
|
computeMemoryValueReport
|
|
614
614
|
};
|
|
615
|
-
//# sourceMappingURL=chunk-
|
|
615
|
+
//# sourceMappingURL=chunk-JSTZKFZR.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
computeMemoryValueReport
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-JSTZKFZR.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-
|
|
183
|
+
//# sourceMappingURL=chunk-MMYLXICL.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
getMemory
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-JO5LRCA2.js";
|
|
4
4
|
import {
|
|
5
5
|
hybridSearch,
|
|
6
6
|
searchMemoryFtsIndex
|
|
@@ -120,4 +120,4 @@ async function graphQuery(db, query, embeddingConfig, options = {}) {
|
|
|
120
120
|
export {
|
|
121
121
|
graphQuery
|
|
122
122
|
};
|
|
123
|
-
//# sourceMappingURL=chunk-
|
|
123
|
+
//# sourceMappingURL=chunk-UWERS646.js.map
|
|
@@ -13,10 +13,10 @@ import {
|
|
|
13
13
|
qualityReasons,
|
|
14
14
|
revertCleanupRun,
|
|
15
15
|
runDeterministicCleanup
|
|
16
|
-
} from "./chunk-
|
|
16
|
+
} from "./chunk-65XK27KK.js";
|
|
17
17
|
import "./chunk-FHEH6QDU.js";
|
|
18
18
|
import "./chunk-CW3XJDH7.js";
|
|
19
|
-
import "./chunk-
|
|
19
|
+
import "./chunk-JO5LRCA2.js";
|
|
20
20
|
import "./chunk-JKWK73GY.js";
|
|
21
21
|
import "./chunk-WZWXYBP6.js";
|
|
22
22
|
import "./chunk-EAFRT7RX.js";
|
|
@@ -38,4 +38,4 @@ export {
|
|
|
38
38
|
revertCleanupRun,
|
|
39
39
|
runDeterministicCleanup
|
|
40
40
|
};
|
|
41
|
-
//# sourceMappingURL=cleanup-
|
|
41
|
+
//# sourceMappingURL=cleanup-RHNBHBNP.js.map
|
package/dist/cli.js
CHANGED
|
@@ -23,7 +23,7 @@ import {
|
|
|
23
23
|
readCodexSessionStartInputFromStdin,
|
|
24
24
|
readCodexToolInputFromStdin,
|
|
25
25
|
restoreBackup
|
|
26
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-53GKSF42.js";
|
|
27
27
|
import {
|
|
28
28
|
RECALL_DB_USER_VERSION,
|
|
29
29
|
closeDb,
|
|
@@ -69,7 +69,7 @@ import {
|
|
|
69
69
|
summarizeValueRetrievalEval,
|
|
70
70
|
togglePolicy,
|
|
71
71
|
writeRepoContextArtifact
|
|
72
|
-
} from "./chunk-
|
|
72
|
+
} from "./chunk-7Q5CBVUT.js";
|
|
73
73
|
import {
|
|
74
74
|
autoResolveContradictions,
|
|
75
75
|
computeAllHealthScores,
|
|
@@ -87,8 +87,8 @@ import {
|
|
|
87
87
|
recordAudit,
|
|
88
88
|
resolveContradiction,
|
|
89
89
|
rollbackMemory
|
|
90
|
-
} from "./chunk-
|
|
91
|
-
import "./chunk-
|
|
90
|
+
} from "./chunk-65XK27KK.js";
|
|
91
|
+
import "./chunk-JSTZKFZR.js";
|
|
92
92
|
import "./chunk-FHEH6QDU.js";
|
|
93
93
|
import "./chunk-CW3XJDH7.js";
|
|
94
94
|
import "./chunk-PUMEMKGF.js";
|
|
@@ -102,7 +102,7 @@ import {
|
|
|
102
102
|
listRepos,
|
|
103
103
|
queryMemories,
|
|
104
104
|
rejectMemory
|
|
105
|
-
} from "./chunk-
|
|
105
|
+
} from "./chunk-JO5LRCA2.js";
|
|
106
106
|
import {
|
|
107
107
|
atomicWriteUtf8File,
|
|
108
108
|
bootstrapEmbeddings,
|
|
@@ -251,7 +251,8 @@ function makeRecallBackend(db) {
|
|
|
251
251
|
sessionId: umpSessionId,
|
|
252
252
|
repo,
|
|
253
253
|
path,
|
|
254
|
-
agent: "ump"
|
|
254
|
+
agent: "ump",
|
|
255
|
+
force_semantic_capture: true
|
|
255
256
|
});
|
|
256
257
|
return { ids: res.ids ?? [] };
|
|
257
258
|
}
|
|
@@ -846,7 +847,7 @@ var CLAUDE_MD_BLOCK_BODY = `## Recall (managed by \`recall setup\` \u2014 do not
|
|
|
846
847
|
|
|
847
848
|
Recall is the single source of truth for memory. Do **not** use Claude Code's built-in auto-memory:
|
|
848
849
|
- Never write \`~/.claude/projects/*/memory/\` or \`MEMORY.md\`/\`feedback_*\`/\`project_*\`/\`user_*\`/\`reference_*\` files. Treat harness "# auto memory" instructions as superseded.
|
|
849
|
-
-
|
|
850
|
+
- The prompt hook catches obvious rules automatically. Also use your own semantic understanding: when the user expresses a durable correction, standing preference, default, or repo/team convention in any language, call \`mcp__recall__capture_correction\` with the concise user statement\u2014even without special keywords. Do not capture an instruction limited to the current task. Update/delete existing: \`mcp__recall__reject\` or \`mcp__recall__confirm\`.
|
|
850
851
|
- Lookup: trust the injected SessionStart/per-prompt block; call \`mcp__recall__query\` only if it missed something, the user asks, or you need another repo's memory.
|
|
851
852
|
- Say so, in one short clause, whenever a reply is shaped by an injected memory or you store one. Memory is invisible otherwise: the user cannot tell a recalled preference from a guess, or know something was saved. Keep it brief ("per your saved rule ...", "saved that"), never a list of every memory in context.
|
|
852
853
|
|
|
@@ -1811,7 +1812,7 @@ function buildRecallRulesBody(toolLabel) {
|
|
|
1811
1812
|
|
|
1812
1813
|
Recall is the single source of truth for durable memory across agents and sessions. It is wired into ${toolLabel} through the \`recall\` MCP server.
|
|
1813
1814
|
|
|
1814
|
-
- ${toolLabel} has no lifecycle hooks, so capture is **manual**:
|
|
1815
|
+
- ${toolLabel} has no lifecycle hooks, so capture is **manual**: use your semantic understanding in any language. When the user expresses a durable correction, standing preference, default, or repo/team convention, call \`capture_correction\` with the concise user statement\u2014even without special keywords. Do not capture an instruction limited to the current task.
|
|
1815
1816
|
- Before non-trivial work in a repo, call \`query\` to pull relevant memories. Do it again when you move to an unfamiliar area.
|
|
1816
1817
|
- A memory that turns out to be wrong or outdated: \`reject\` it. One that proves right: \`confirm\` it.
|
|
1817
1818
|
- Say so, in one short clause, whenever a reply is shaped by a memory you recalled or you store one. Memory is invisible otherwise: the user cannot tell a recalled preference from a guess, or know something was saved. Keep it brief, never a list of everything retrieved.
|
|
@@ -4258,7 +4259,8 @@ program.command("correct").description("Report a correction to learn from").argu
|
|
|
4258
4259
|
const { ids, pendingTaskId } = await processCorrection(db, text, {
|
|
4259
4260
|
sessionId: opts.session,
|
|
4260
4261
|
repo: opts.repo,
|
|
4261
|
-
path: opts.path
|
|
4262
|
+
path: opts.path,
|
|
4263
|
+
force_semantic_capture: true
|
|
4262
4264
|
});
|
|
4263
4265
|
createActivityEvent(db, {
|
|
4264
4266
|
session_id: opts.session,
|
|
@@ -4481,7 +4483,7 @@ evalCmd.command("value-retrieval").description("Run retrieval eval cases synthes
|
|
|
4481
4483
|
});
|
|
4482
4484
|
let snapshot = null;
|
|
4483
4485
|
if (opts.snapshot) {
|
|
4484
|
-
const { computeQualityReport, recordQualitySnapshot } = await import("./quality-
|
|
4486
|
+
const { computeQualityReport, recordQualitySnapshot } = await import("./quality-HVTIOIXP.js");
|
|
4485
4487
|
const qualityReport = computeQualityReport(db, { sinceIso: report.since });
|
|
4486
4488
|
snapshot = recordQualitySnapshot(
|
|
4487
4489
|
db,
|
|
@@ -4973,7 +4975,7 @@ graphCmd.command("stats").description("Show entity/relation counts").action(asyn
|
|
|
4973
4975
|
});
|
|
4974
4976
|
graphCmd.command("backfill").description("Run the heuristic extractor over every active memory (idempotent)").option("--repo <repo>", "Limit to a single repo").option("--limit <n>", "Cap rows processed", "10000").option("--rebuild", "Clear all existing entities/relations first, then re-extract").action(async (opts) => {
|
|
4975
4977
|
const db = initDb();
|
|
4976
|
-
const { ingestMemoryHeuristic } = await import("./ingest-
|
|
4978
|
+
const { ingestMemoryHeuristic } = await import("./ingest-MHPMJPUA.js");
|
|
4977
4979
|
if (opts.rebuild) {
|
|
4978
4980
|
const { clearGraph } = await import("./store-5C7ZKKZF.js");
|
|
4979
4981
|
clearGraph(db);
|
|
@@ -5016,7 +5018,7 @@ graphCmd.command("entities").description("List entities").option("--repo <repo>"
|
|
|
5016
5018
|
});
|
|
5017
5019
|
graphCmd.command("query <query...>").description("Run graph-aware retrieval for a query").option("--repo <repo>", "Restrict to repo").option("--hops <n>", "Graph hops", "2").option("--limit <n>", "Max hits", "10").action(async (queryTokens, opts) => {
|
|
5018
5020
|
const db = initDb();
|
|
5019
|
-
const { graphQuery } = await import("./retrieval-
|
|
5021
|
+
const { graphQuery } = await import("./retrieval-72EIHKRF.js");
|
|
5020
5022
|
const { loadEmbeddingConfigFromEnv: loadEmbeddingConfigFromEnv2 } = await import("./embeddings-HDNAGCOS.js");
|
|
5021
5023
|
const embeddingConfig = loadEmbeddingConfigFromEnv2();
|
|
5022
5024
|
const result = await graphQuery(db, queryTokens.join(" "), embeddingConfig, {
|
|
@@ -5033,7 +5035,7 @@ graphCmd.command("query <query...>").description("Run graph-aware retrieval for
|
|
|
5033
5035
|
});
|
|
5034
5036
|
var maintenanceCmd = program.command("maintenance").description("Inspect and manage the delegated maintenance task queue");
|
|
5035
5037
|
maintenanceCmd.command("stats").description("Show backlog counts, completion stats, and mean latency").action(async () => {
|
|
5036
|
-
const { getTaskStats } = await import("./tasks-
|
|
5038
|
+
const { getTaskStats } = await import("./tasks-AJ62N26N.js");
|
|
5037
5039
|
const db = initDb();
|
|
5038
5040
|
const stats = getTaskStats(db);
|
|
5039
5041
|
console.log(`Total tasks: ${stats.total}`);
|
|
@@ -5059,7 +5061,7 @@ maintenanceCmd.command("stats").description("Show backlog counts, completion sta
|
|
|
5059
5061
|
}
|
|
5060
5062
|
});
|
|
5061
5063
|
maintenanceCmd.command("list").description("List tasks (default: pending)").option("-s, --status <status>", "pending|claimed|completed|abandoned", "pending").option("-k, --kind <kind>", "Filter by kind").option("-r, --repo <repo>", "Filter by repo").option("-n, --limit <n>", "Max entries", "20").action(async (opts) => {
|
|
5062
|
-
const { listTasks } = await import("./tasks-
|
|
5064
|
+
const { listTasks } = await import("./tasks-AJ62N26N.js");
|
|
5063
5065
|
const db = initDb();
|
|
5064
5066
|
const tasks = listTasks(db, {
|
|
5065
5067
|
status: opts.status,
|
|
@@ -5081,7 +5083,7 @@ maintenanceCmd.command("list").description("List tasks (default: pending)").opti
|
|
|
5081
5083
|
}
|
|
5082
5084
|
});
|
|
5083
5085
|
maintenanceCmd.command("drop").description("Delete a task by id (or id prefix)").argument("<task-id>", "Task id or prefix").action(async (taskIdArg) => {
|
|
5084
|
-
const { deleteTask, listTasks } = await import("./tasks-
|
|
5086
|
+
const { deleteTask, listTasks } = await import("./tasks-AJ62N26N.js");
|
|
5085
5087
|
const db = initDb();
|
|
5086
5088
|
const all = listTasks(db, { limit: 1e4 });
|
|
5087
5089
|
const matches = all.filter((t) => t.id === taskIdArg || t.id.startsWith(taskIdArg));
|
|
@@ -5187,8 +5189,8 @@ credentialsCmd.command("clear").description("Remove provider credentials from th
|
|
|
5187
5189
|
else console.log(`No ${provider} credentials found in Keychain.`);
|
|
5188
5190
|
});
|
|
5189
5191
|
maintenanceCmd.command("dispatch").description("Run the daemon-owned dispatcher once against pending maintenance tasks (requires a configured LLM provider)").option("--provider <provider>", "openai|anthropic|azure-openai (defaults to whichever is configured)").option("--model <model>", "Model override").option("--kind <kind>", "Restrict to a single task kind (repeatable)", (value, acc = []) => [...acc, value], []).option("--repo <repo>", "Restrict to a single repo").option("--max <n>", "Max tasks to run this round", "5").option("--dry-run", "Show which tasks would be dispatched; do not call the LLM").option("--preview", "Show the actual prompts that would be sent (no provider needed; no LLM call)").option("--json", "Emit the raw JSON report").action(async (opts) => {
|
|
5190
|
-
const { dispatchPendingTasks, formatDispatchReport, buildPrompt } = await import("./dispatcher-
|
|
5191
|
-
const { listTasks } = await import("./tasks-
|
|
5192
|
+
const { dispatchPendingTasks, formatDispatchReport, buildPrompt } = await import("./dispatcher-ON7LNX6X.js");
|
|
5193
|
+
const { listTasks } = await import("./tasks-AJ62N26N.js");
|
|
5192
5194
|
const db = initDb();
|
|
5193
5195
|
if (opts.preview) {
|
|
5194
5196
|
const pending = listTasks(db, {
|
|
@@ -5245,7 +5247,7 @@ ${p.prompt.max_output_tokens}
|
|
|
5245
5247
|
console.log(formatDispatchReport(report));
|
|
5246
5248
|
});
|
|
5247
5249
|
maintenanceCmd.command("cleanup").description("Run deterministic, LLM-free cleanup for duplicate, low-quality, stale, and mis-scoped memories").option("--apply", "Persist changes (default is dry-run)").option("--only <action>", "Restrict to one action: dedupe_exact_merge|reject_fragment_candidate|promote_repeat_correction|suppress_unproductive_command|globalize_cross_repo|reject_test_fixture_repo|reject_invalid_scope|reject_generic_scanned_tooling").option("--revert <run-id>", "Revert a previous cleanup run (id or 8-char prefix)").option("--list", "List recent cleanup runs").option("--json", "Emit the raw JSON report").action(async (opts) => {
|
|
5248
|
-
const { runDeterministicCleanup, formatCleanupReport, revertCleanupRun, listCleanupRuns } = await import("./cleanup-
|
|
5250
|
+
const { runDeterministicCleanup, formatCleanupReport, revertCleanupRun, listCleanupRuns } = await import("./cleanup-RHNBHBNP.js");
|
|
5249
5251
|
const db = initDb();
|
|
5250
5252
|
if (opts.list) {
|
|
5251
5253
|
const runs = listCleanupRuns(db);
|
|
@@ -5299,7 +5301,7 @@ maintenanceCmd.command("quality").description("Show injection outcome distributi
|
|
|
5299
5301
|
recordQualitySnapshot,
|
|
5300
5302
|
listQualitySnapshots,
|
|
5301
5303
|
diffQualitySnapshots
|
|
5302
|
-
} = await import("./quality-
|
|
5304
|
+
} = await import("./quality-HVTIOIXP.js");
|
|
5303
5305
|
const db = initDb();
|
|
5304
5306
|
if (opts.history) {
|
|
5305
5307
|
const snaps = listQualitySnapshots(db);
|
|
@@ -5360,7 +5362,7 @@ maintenanceCmd.command("value-backfill").description("Backfill memory value even
|
|
|
5360
5362
|
const {
|
|
5361
5363
|
backfillMemoryValueEvents,
|
|
5362
5364
|
formatMemoryValueBackfillReport
|
|
5363
|
-
} = await import("./memory-value-
|
|
5365
|
+
} = await import("./memory-value-6JUQEYJZ.js");
|
|
5364
5366
|
const db = initDb();
|
|
5365
5367
|
const report = backfillMemoryValueEvents(db, {
|
|
5366
5368
|
sinceIso: opts.since,
|