@edihasaj/recall 1.4.0 → 1.4.14
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/README.md +17 -7
- package/dist/{chunk-EAFRT7RX.js → chunk-22KM2YEO.js} +7 -2
- package/dist/{chunk-EAFRT7RX.js.map → chunk-22KM2YEO.js.map} +1 -1
- package/dist/{chunk-PUMEMKGF.js → chunk-47CB7PKL.js} +7 -1
- package/dist/{chunk-PUMEMKGF.js.map → chunk-47CB7PKL.js.map} +1 -1
- package/dist/{chunk-FHEH6QDU.js → chunk-7Z3CCCS2.js} +6 -1
- package/dist/{chunk-FHEH6QDU.js.map → chunk-7Z3CCCS2.js.map} +1 -1
- package/dist/chunk-AQOI4FCW.js +23 -0
- package/dist/chunk-AQOI4FCW.js.map +1 -0
- package/dist/{chunk-JKWK73GY.js → chunk-BWKFROGW.js} +101 -11
- package/dist/chunk-BWKFROGW.js.map +1 -0
- package/dist/{chunk-JYWURG5T.js → chunk-CYAODQOH.js} +12 -2
- package/dist/chunk-CYAODQOH.js.map +1 -0
- package/dist/{chunk-UWERS646.js → chunk-DJNJQA7L.js} +8 -4
- package/dist/{chunk-UWERS646.js.map → chunk-DJNJQA7L.js.map} +1 -1
- package/dist/{chunk-6QFOCUEJ.js → chunk-GGUWKT6I.js} +111 -21
- package/dist/chunk-GGUWKT6I.js.map +1 -0
- package/dist/{chunk-JO5LRCA2.js → chunk-HFHNPOBW.js} +207 -24
- package/dist/chunk-HFHNPOBW.js.map +1 -0
- package/dist/{chunk-JSTZKFZR.js → chunk-HRUNR5JJ.js} +14 -9
- package/dist/{chunk-JSTZKFZR.js.map → chunk-HRUNR5JJ.js.map} +1 -1
- package/dist/{chunk-65XK27KK.js → chunk-HUMJTWWT.js} +81 -161
- package/dist/chunk-HUMJTWWT.js.map +1 -0
- package/dist/{chunk-53GKSF42.js → chunk-JFUMA4WV.js} +308 -169
- package/dist/chunk-JFUMA4WV.js.map +1 -0
- package/dist/{chunk-MMYLXICL.js → chunk-KOBZIF2X.js} +8 -4
- package/dist/{chunk-MMYLXICL.js.map → chunk-KOBZIF2X.js.map} +1 -1
- package/dist/{chunk-7Q5CBVUT.js → chunk-M3ASNCVM.js} +234 -49
- package/dist/chunk-M3ASNCVM.js.map +1 -0
- package/dist/chunk-Q2KCBLJO.js +594 -0
- package/dist/chunk-Q2KCBLJO.js.map +1 -0
- package/dist/{chunk-CW3XJDH7.js → chunk-RWEX4VJE.js} +6 -2
- package/dist/{chunk-CW3XJDH7.js.map → chunk-RWEX4VJE.js.map} +1 -1
- package/dist/{chunk-LUIYWYOT.js → chunk-VSEAVK7X.js} +51 -3
- package/dist/chunk-VSEAVK7X.js.map +1 -0
- package/dist/{chunk-WZWXYBP6.js → chunk-XCFTE74H.js} +6 -3
- package/dist/{chunk-WZWXYBP6.js.map → chunk-XCFTE74H.js.map} +1 -1
- package/dist/{cleanup-RHNBHBNP.js → cleanup-YCYA6BJB.js} +11 -10
- package/dist/cli.js +648 -793
- package/dist/cli.js.map +1 -1
- package/dist/codex-trust-Z7LNNRVT.js +74 -0
- package/dist/codex-trust-Z7LNNRVT.js.map +1 -0
- package/dist/daemon.js +181 -61
- package/dist/daemon.js.map +1 -1
- package/dist/dispatcher-FP3WS74F.js +22 -0
- package/dist/{embeddings-HDNAGCOS.js → embeddings-VZPCFCEY.js} +7 -5
- package/dist/ingest-QEKMNVL7.js +20 -0
- package/dist/{keychain-5KXUHKMF.js → keychain-2PXI2EGF.js} +3 -3
- package/dist/mcp.js +18 -14
- package/dist/mcp.js.map +1 -1
- package/dist/{memory-value-6JUQEYJZ.js → memory-value-XSPRH6KY.js} +11 -10
- package/dist/provenance-GJR7S7VA.js +50 -0
- package/dist/provenance-GJR7S7VA.js.map +1 -0
- package/dist/quality-TWOC3UMF.js +25 -0
- package/dist/retrieval-RW6YBQ6P.js +15 -0
- package/dist/{store-5C7ZKKZF.js → store-HIM5US7B.js} +4 -4
- package/dist/sync-server.js +5 -2
- package/dist/sync-server.js.map +1 -1
- package/dist/{tasks-AJ62N26N.js → tasks-TAXJSUKB.js} +11 -10
- package/dist/{usage-VQ5LJCNH.js → usage-XMYRFJBJ.js} +7 -4
- package/dist/{usage-VQ5LJCNH.js.map → usage-XMYRFJBJ.js.map} +1 -1
- package/drizzle/0011_compact_telemetry_dedupe_keys.sql +25 -0
- package/drizzle/meta/_journal.json +7 -0
- package/package.json +15 -12
- package/dist/chunk-53GKSF42.js.map +0 -1
- package/dist/chunk-65XK27KK.js.map +0 -1
- package/dist/chunk-6QFOCUEJ.js.map +0 -1
- package/dist/chunk-7Q5CBVUT.js.map +0 -1
- package/dist/chunk-JKWK73GY.js.map +0 -1
- package/dist/chunk-JO5LRCA2.js.map +0 -1
- package/dist/chunk-LUIYWYOT.js.map +0 -1
- package/dist/dispatcher-ON7LNX6X.js +0 -21
- package/dist/ingest-MHPMJPUA.js +0 -18
- package/dist/quality-HVTIOIXP.js +0 -24
- package/dist/retrieval-72EIHKRF.js +0 -13
- package/dist/tasks-AJ62N26N.js.map +0 -1
- /package/dist/{chunk-JYWURG5T.js.map → cleanup-YCYA6BJB.js.map} +0 -0
- /package/dist/{cleanup-RHNBHBNP.js.map → dispatcher-FP3WS74F.js.map} +0 -0
- /package/dist/{dispatcher-ON7LNX6X.js.map → embeddings-VZPCFCEY.js.map} +0 -0
- /package/dist/{embeddings-HDNAGCOS.js.map → ingest-QEKMNVL7.js.map} +0 -0
- /package/dist/{ingest-MHPMJPUA.js.map → keychain-2PXI2EGF.js.map} +0 -0
- /package/dist/{keychain-5KXUHKMF.js.map → memory-value-XSPRH6KY.js.map} +0 -0
- /package/dist/{memory-value-6JUQEYJZ.js.map → quality-TWOC3UMF.js.map} +0 -0
- /package/dist/{quality-HVTIOIXP.js.map → retrieval-RW6YBQ6P.js.map} +0 -0
- /package/dist/{retrieval-72EIHKRF.js.map → store-HIM5US7B.js.map} +0 -0
- /package/dist/{store-5C7ZKKZF.js.map → tasks-TAXJSUKB.js.map} +0 -0
|
@@ -1,16 +1,23 @@
|
|
|
1
|
+
import {
|
|
2
|
+
desc
|
|
3
|
+
} from "./chunk-RWEX4VJE.js";
|
|
4
|
+
import {
|
|
5
|
+
defineOwn
|
|
6
|
+
} from "./chunk-AQOI4FCW.js";
|
|
1
7
|
import {
|
|
2
8
|
CONFIDENCE,
|
|
3
9
|
PROMOTION,
|
|
4
10
|
queueMemoryEmbeddingSync
|
|
5
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-BWKFROGW.js";
|
|
6
12
|
import {
|
|
7
13
|
isPlausibleEntityName,
|
|
8
14
|
linkMemoryToEntity,
|
|
9
15
|
upsertEntity,
|
|
10
16
|
upsertRelation
|
|
11
|
-
} from "./chunk-
|
|
17
|
+
} from "./chunk-22KM2YEO.js";
|
|
12
18
|
import {
|
|
13
19
|
and,
|
|
20
|
+
auditTrail,
|
|
14
21
|
eq,
|
|
15
22
|
feedbackEvents,
|
|
16
23
|
gte,
|
|
@@ -18,25 +25,53 @@ import {
|
|
|
18
25
|
like,
|
|
19
26
|
memories,
|
|
20
27
|
sql
|
|
21
|
-
} from "./chunk-
|
|
28
|
+
} from "./chunk-VSEAVK7X.js";
|
|
29
|
+
import {
|
|
30
|
+
init_define_RECALL_BUILD_INFO
|
|
31
|
+
} from "./chunk-CYAODQOH.js";
|
|
32
|
+
|
|
33
|
+
// src/graph/ingest.ts
|
|
34
|
+
init_define_RECALL_BUILD_INFO();
|
|
22
35
|
|
|
23
36
|
// src/models/memory.ts
|
|
24
|
-
|
|
37
|
+
init_define_RECALL_BUILD_INFO();
|
|
38
|
+
import { randomUUID as randomUUID2 } from "crypto";
|
|
25
39
|
|
|
26
|
-
// src/
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
enumerable: true,
|
|
31
|
-
value,
|
|
32
|
-
writable: true
|
|
33
|
-
});
|
|
40
|
+
// src/capture/provenance.ts
|
|
41
|
+
init_define_RECALL_BUILD_INFO();
|
|
42
|
+
function isGeneratedCaptureContext(text) {
|
|
43
|
+
return /^\s*<(?:system|developer|paseo-system|agent-response|task-notification|system-reminder)(?:\s|>)/i.test(text) || /^\s*\[(?:system|developer|tool result)\]/i.test(text) || /^\s*generate a title and a git branch name for a coding agent\b/i.test(text) || /^\s*(?:classify|analy[sz]e|extract|score|summari[sz]e|generate|you are)\b/i.test(text) && /\b(?:return|output|respond)[^\n]{0,45}\bJSON\b/i.test(text) && (/"(?:expected_schema_version|schema_version|source_text|raw_prompt)"\s*:/.test(text) || /(?:^|\n)Routes:\s*\n/.test(text));
|
|
34
44
|
}
|
|
35
|
-
function
|
|
36
|
-
|
|
45
|
+
function containsGeneratedHistory(text) {
|
|
46
|
+
return text.split("\n").some((line) => isGeneratedCaptureContext(
|
|
47
|
+
line.replace(/^\s*(?:[-*]\s*)?(?:\(\d+\)\s*)?/, "")
|
|
48
|
+
)) || isGeneratedCaptureContext(text);
|
|
49
|
+
}
|
|
50
|
+
function isTaskLimitedRule(text) {
|
|
51
|
+
return /^\s*(?:for|during) (?:this|the current) (?:repository )?(?:review|task|turn|session)\b/i.test(text);
|
|
52
|
+
}
|
|
53
|
+
function hasNonDurableProvenance(memory) {
|
|
54
|
+
return hasOnlyGeneratedEvidence(memory) || isTaskLimitedRule(memory.text);
|
|
55
|
+
}
|
|
56
|
+
function hasOnlyGeneratedEvidence(memory) {
|
|
57
|
+
const contexts = memory.evidence.filter((entry) => entry.type === "session_correction" || entry.type === "review_feedback").map((entry) => entry.context?.trim()).filter((context) => Boolean(context));
|
|
58
|
+
return contexts.length > 0 && contexts.every(isGeneratedCaptureContext);
|
|
59
|
+
}
|
|
60
|
+
function hasDirectCorrectionEvidence(memory) {
|
|
61
|
+
return memory.source === "user_correction" && memory.evidence.some(
|
|
62
|
+
(entry) => entry.type === "session_correction" && Boolean(entry.context?.trim()) && !isGeneratedCaptureContext(entry.context ?? "")
|
|
63
|
+
);
|
|
37
64
|
}
|
|
38
65
|
|
|
39
66
|
// src/models/dedupe.ts
|
|
67
|
+
init_define_RECALL_BUILD_INFO();
|
|
68
|
+
import { createHash } from "crypto";
|
|
69
|
+
var ACTIVITY_DEDUPE_PREFIX = "activitysha256:";
|
|
70
|
+
var HOOK_DEDUPE_PREFIX = "hooksha256:";
|
|
71
|
+
function compactDedupeKey(namespace, legacyKey) {
|
|
72
|
+
const prefix = namespace === "activity" ? ACTIVITY_DEDUPE_PREFIX : HOOK_DEDUPE_PREFIX;
|
|
73
|
+
return `${prefix}${createHash("sha256").update(legacyKey).digest("hex")}`;
|
|
74
|
+
}
|
|
40
75
|
function normalizeDedupeText(text) {
|
|
41
76
|
return text.toLowerCase().replace(/\s+/g, " ").replace(/[\s.;:,!?`]+$/g, "").trim();
|
|
42
77
|
}
|
|
@@ -61,7 +96,7 @@ function historySnippetDedupeKey(input) {
|
|
|
61
96
|
}
|
|
62
97
|
function activityEventDedupeKey(input) {
|
|
63
98
|
if (!input.session_id) return null;
|
|
64
|
-
|
|
99
|
+
const legacyKey = [
|
|
65
100
|
"activity",
|
|
66
101
|
input.session_id,
|
|
67
102
|
input.repo ?? "",
|
|
@@ -71,10 +106,11 @@ function activityEventDedupeKey(input) {
|
|
|
71
106
|
stableDedupeJson(stripVolatileFields(input.request ?? {})),
|
|
72
107
|
stableDedupeJson(stripVolatileFields(input.result ?? {}))
|
|
73
108
|
].join("");
|
|
109
|
+
return compactDedupeKey("activity", legacyKey);
|
|
74
110
|
}
|
|
75
111
|
function hookCallDedupeKey(input) {
|
|
76
112
|
if (!input.session_id) return null;
|
|
77
|
-
|
|
113
|
+
const legacyKey = [
|
|
78
114
|
"hook",
|
|
79
115
|
input.session_id,
|
|
80
116
|
input.agent,
|
|
@@ -82,6 +118,7 @@ function hookCallDedupeKey(input) {
|
|
|
82
118
|
input.ok ? "ok" : "error",
|
|
83
119
|
stableDedupeJson(stripVolatileFields(input.payload ?? {}))
|
|
84
120
|
].join("");
|
|
121
|
+
return compactDedupeKey("hook", legacyKey);
|
|
85
122
|
}
|
|
86
123
|
function stripVolatileFields(value) {
|
|
87
124
|
if (Array.isArray(value)) {
|
|
@@ -109,6 +146,119 @@ function stableDedupeJson(value) {
|
|
|
109
146
|
return `{${Object.keys(record).sort().map((key) => `${JSON.stringify(key)}:${stableDedupeJson(record[key])}`).join(",")}}`;
|
|
110
147
|
}
|
|
111
148
|
|
|
149
|
+
// src/audit/trail.ts
|
|
150
|
+
init_define_RECALL_BUILD_INFO();
|
|
151
|
+
import { randomUUID } from "crypto";
|
|
152
|
+
function recordAudit(db, memoryId, action, actor, reason, beforeSnapshot, afterSnapshot) {
|
|
153
|
+
const id = randomUUID();
|
|
154
|
+
if (afterSnapshot === void 0) {
|
|
155
|
+
const mem = getMemory(db, memoryId);
|
|
156
|
+
if (mem) {
|
|
157
|
+
afterSnapshot = JSON.stringify(mem);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
db.insert(auditTrail).values({
|
|
161
|
+
id,
|
|
162
|
+
memory_id: memoryId,
|
|
163
|
+
action,
|
|
164
|
+
actor,
|
|
165
|
+
before_snapshot: beforeSnapshot ?? null,
|
|
166
|
+
after_snapshot: afterSnapshot ?? null,
|
|
167
|
+
reason: reason ?? null,
|
|
168
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
169
|
+
}).run();
|
|
170
|
+
return id;
|
|
171
|
+
}
|
|
172
|
+
function recordAuditWithSnapshot(db, memoryId, action, actor, reason, before, after) {
|
|
173
|
+
return recordAudit(
|
|
174
|
+
db,
|
|
175
|
+
memoryId,
|
|
176
|
+
action,
|
|
177
|
+
actor,
|
|
178
|
+
reason,
|
|
179
|
+
before ? JSON.stringify(before) : null,
|
|
180
|
+
after ? JSON.stringify(after) : null
|
|
181
|
+
);
|
|
182
|
+
}
|
|
183
|
+
function getAuditTrail(db, memoryId) {
|
|
184
|
+
return db.select().from(auditTrail).where(eq(auditTrail.memory_id, memoryId)).orderBy(desc(auditTrail.timestamp)).all().map(rowToAudit);
|
|
185
|
+
}
|
|
186
|
+
function getRecentAudit(db, limit = 50) {
|
|
187
|
+
return db.select().from(auditTrail).orderBy(desc(auditTrail.timestamp)).limit(limit).all().map(rowToAudit);
|
|
188
|
+
}
|
|
189
|
+
function diffSnapshots(before, after) {
|
|
190
|
+
if (!before || !after) return [];
|
|
191
|
+
const a = JSON.parse(before);
|
|
192
|
+
const b = JSON.parse(after);
|
|
193
|
+
const diffs = [];
|
|
194
|
+
const keys = /* @__PURE__ */ new Set([...Object.keys(a), ...Object.keys(b)]);
|
|
195
|
+
for (const key of keys) {
|
|
196
|
+
if (key === "evidence" || key === "embedding") continue;
|
|
197
|
+
const va = JSON.stringify(a[key]);
|
|
198
|
+
const vb = JSON.stringify(b[key]);
|
|
199
|
+
if (va !== vb) {
|
|
200
|
+
diffs.push({ field: key, before: a[key], after: b[key] });
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
return diffs;
|
|
204
|
+
}
|
|
205
|
+
function rollbackMemory(db, memoryId, auditEntryId, actor) {
|
|
206
|
+
const entry = db.select().from(auditTrail).where(eq(auditTrail.id, auditEntryId)).get();
|
|
207
|
+
if (!entry) return false;
|
|
208
|
+
const snapshot = entry.before_snapshot;
|
|
209
|
+
if (!snapshot) return false;
|
|
210
|
+
const beforeRollback = getMemory(db, memoryId);
|
|
211
|
+
const restored = JSON.parse(snapshot);
|
|
212
|
+
db.update(memories).set({
|
|
213
|
+
text: restored.text,
|
|
214
|
+
type: restored.type,
|
|
215
|
+
scope: restored.scope,
|
|
216
|
+
path_scope: restored.path_scope,
|
|
217
|
+
status: restored.status,
|
|
218
|
+
confidence: restored.confidence,
|
|
219
|
+
source: restored.source,
|
|
220
|
+
evidence: restored.evidence,
|
|
221
|
+
capture_context: restored.capture_context,
|
|
222
|
+
repetition_count: restored.repetition_count,
|
|
223
|
+
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
224
|
+
}).where(eq(memories.id, memoryId)).run();
|
|
225
|
+
queueMemoryEmbeddingSync(db, memoryId);
|
|
226
|
+
recordAuditWithSnapshot(
|
|
227
|
+
db,
|
|
228
|
+
memoryId,
|
|
229
|
+
"rolled_back",
|
|
230
|
+
actor,
|
|
231
|
+
`Rolled back to state from ${entry.timestamp}`,
|
|
232
|
+
beforeRollback ?? null,
|
|
233
|
+
getMemory(db, memoryId) ?? null
|
|
234
|
+
);
|
|
235
|
+
return true;
|
|
236
|
+
}
|
|
237
|
+
function formatAuditTrail(entries) {
|
|
238
|
+
if (entries.length === 0) return "No audit entries.";
|
|
239
|
+
const lines = ["# Audit Trail", ""];
|
|
240
|
+
for (const e of entries) {
|
|
241
|
+
const diffs = diffSnapshots(e.before_snapshot, e.after_snapshot);
|
|
242
|
+
const diffStr = diffs.length > 0 ? ` [${diffs.map((d) => `${d.field}: ${JSON.stringify(d.before)} \u2192 ${JSON.stringify(d.after)}`).join(", ")}]` : "";
|
|
243
|
+
lines.push(
|
|
244
|
+
`${e.timestamp.slice(0, 19)} ${e.action.padEnd(22)} by ${e.actor}${e.reason ? ` \u2014 ${e.reason}` : ""}${diffStr}`
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
return lines.join("\n");
|
|
248
|
+
}
|
|
249
|
+
function rowToAudit(row) {
|
|
250
|
+
return {
|
|
251
|
+
id: row.id,
|
|
252
|
+
memory_id: row.memory_id,
|
|
253
|
+
action: row.action,
|
|
254
|
+
actor: row.actor,
|
|
255
|
+
before_snapshot: row.before_snapshot,
|
|
256
|
+
after_snapshot: row.after_snapshot,
|
|
257
|
+
reason: row.reason,
|
|
258
|
+
timestamp: row.timestamp
|
|
259
|
+
};
|
|
260
|
+
}
|
|
261
|
+
|
|
112
262
|
// src/models/memory.ts
|
|
113
263
|
function statusFromConfidence(confidence) {
|
|
114
264
|
if (confidence < CONFIDENCE.TRANSIENT_MAX) return "transient";
|
|
@@ -117,7 +267,7 @@ function statusFromConfidence(confidence) {
|
|
|
117
267
|
}
|
|
118
268
|
function createMemory(db, input) {
|
|
119
269
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
120
|
-
const id =
|
|
270
|
+
const id = randomUUID2();
|
|
121
271
|
const confidence = input.confidence ?? 0.35;
|
|
122
272
|
const status = statusFromConfidence(confidence);
|
|
123
273
|
let scope = input.scope;
|
|
@@ -213,6 +363,7 @@ function promoteMemory(db, id, reason, evidence) {
|
|
|
213
363
|
const mem = getMemory(db, id);
|
|
214
364
|
if (!mem) return false;
|
|
215
365
|
if (mem.status === "rejected") return false;
|
|
366
|
+
if (reason !== "explicit_confirm" && hasNonDurableProvenance(mem)) return false;
|
|
216
367
|
let newConfidence;
|
|
217
368
|
if (reason === "explicit_confirm") {
|
|
218
369
|
newConfidence = Math.max(mem.confidence, PROMOTION.EXPLICIT_CONFIRM);
|
|
@@ -230,6 +381,7 @@ function promoteMemory(db, id, reason, evidence) {
|
|
|
230
381
|
confidence: newConfidence,
|
|
231
382
|
status: newStatus,
|
|
232
383
|
evidence: newEvidence,
|
|
384
|
+
auto_inject: true,
|
|
233
385
|
updated_at: now,
|
|
234
386
|
last_validated_at: now
|
|
235
387
|
}).where(eq(memories.id, id)).run();
|
|
@@ -286,15 +438,17 @@ function demoteGlobalMemory(db, id, opts = {}) {
|
|
|
286
438
|
const updated = getMemory(db, id);
|
|
287
439
|
return { ok: true, outcome: targetRepo ? "rescoped" : "rejected", memory: updated };
|
|
288
440
|
}
|
|
289
|
-
function rejectMemory(db, id) {
|
|
441
|
+
function rejectMemory(db, id, actor = "system") {
|
|
290
442
|
const mem = getMemory(db, id);
|
|
291
443
|
if (!mem) return false;
|
|
444
|
+
const beforeSnapshot = JSON.stringify(mem);
|
|
292
445
|
db.update(memories).set({
|
|
293
446
|
status: "rejected",
|
|
294
447
|
confidence: 0,
|
|
295
448
|
dedupe_key: null,
|
|
296
449
|
updated_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
297
450
|
}).where(eq(memories.id, id)).run();
|
|
451
|
+
recordAudit(db, id, "rejected", actor, null, beforeSnapshot);
|
|
298
452
|
queueMemoryEmbeddingSync(db, id);
|
|
299
453
|
return true;
|
|
300
454
|
}
|
|
@@ -306,6 +460,24 @@ function confirmMemory(db, id) {
|
|
|
306
460
|
context: "user explicitly confirmed"
|
|
307
461
|
});
|
|
308
462
|
}
|
|
463
|
+
function reactivateMemory(db, id, evidence) {
|
|
464
|
+
const mem = getMemory(db, id);
|
|
465
|
+
if (!mem) return false;
|
|
466
|
+
if (mem.status !== "rejected") return false;
|
|
467
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
468
|
+
const dedupeKey = memoryDedupeKey(mem);
|
|
469
|
+
const existing = db.select().from(memories).where(and(eq(memories.dedupe_key, dedupeKey), sql`${memories.status} != 'rejected'`)).get();
|
|
470
|
+
if (existing && existing.id !== id) return false;
|
|
471
|
+
db.update(memories).set({
|
|
472
|
+
status: "candidate",
|
|
473
|
+
confidence: CONFIDENCE.TRANSIENT_MAX + 0.05,
|
|
474
|
+
dedupe_key: dedupeKey,
|
|
475
|
+
evidence: [...mem.evidence, evidence],
|
|
476
|
+
updated_at: now
|
|
477
|
+
}).where(eq(memories.id, id)).run();
|
|
478
|
+
queueMemoryEmbeddingSync(db, id);
|
|
479
|
+
return true;
|
|
480
|
+
}
|
|
309
481
|
function appendEvidence(db, id, evidence) {
|
|
310
482
|
const mem = getMemory(db, id);
|
|
311
483
|
if (!mem) return false;
|
|
@@ -320,7 +492,7 @@ function appendEvidence(db, id, evidence) {
|
|
|
320
492
|
}
|
|
321
493
|
function restoreAutoInject(db, id) {
|
|
322
494
|
const mem = getMemory(db, id);
|
|
323
|
-
if (!mem || mem.auto_inject) return false;
|
|
495
|
+
if (!mem || mem.auto_inject || hasNonDurableProvenance(mem)) return false;
|
|
324
496
|
db.update(memories).set({ auto_inject: true, updated_at: (/* @__PURE__ */ new Date()).toISOString() }).where(eq(memories.id, id)).run();
|
|
325
497
|
return true;
|
|
326
498
|
}
|
|
@@ -356,7 +528,7 @@ function countDistinctCorrectionSessions(mem) {
|
|
|
356
528
|
return sessions.size;
|
|
357
529
|
}
|
|
358
530
|
function recordFeedback(db, memoryId, sessionId, injected, outcome) {
|
|
359
|
-
const id =
|
|
531
|
+
const id = randomUUID2();
|
|
360
532
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
361
533
|
db.insert(feedbackEvents).values({
|
|
362
534
|
id,
|
|
@@ -367,7 +539,7 @@ function recordFeedback(db, memoryId, sessionId, injected, outcome) {
|
|
|
367
539
|
timestamp: now
|
|
368
540
|
}).run();
|
|
369
541
|
const mem = getMemory(db, memoryId);
|
|
370
|
-
if (!mem) return id;
|
|
542
|
+
if (!mem || mem.status === "rejected" || hasNonDurableProvenance(mem)) return id;
|
|
371
543
|
const delta = outcome === "followed" ? 0.05 : outcome === "overridden" ? -0.15 : outcome === "ignored" ? -0.02 : -0.25;
|
|
372
544
|
const nextConfidence = Math.max(0, Math.min(1, mem.confidence + delta));
|
|
373
545
|
const nextStatus = statusFromConfidence(nextConfidence);
|
|
@@ -474,6 +646,7 @@ function hasEquivalentEvidence(existing, next) {
|
|
|
474
646
|
}
|
|
475
647
|
|
|
476
648
|
// src/graph/extractor.ts
|
|
649
|
+
init_define_RECALL_BUILD_INFO();
|
|
477
650
|
var PATH_RE = /(?:^|[\s`'"(])((?:\.{0,2}\/)?(?:[A-Za-z0-9_.-]+\/){1,}[A-Za-z0-9_.-]+\.[A-Za-z0-9]{1,8})/g;
|
|
478
651
|
var FUNC_RE = /`([A-Za-z_][\w.]{1,}\(\))`/g;
|
|
479
652
|
var SCOPED_PACKAGE_RE = /`(@[a-z0-9_-]+\/[a-z0-9_.-]+|[a-z][a-z0-9_-]*(?:-[a-z0-9]+)+)`/g;
|
|
@@ -782,13 +955,22 @@ function safeIngestMemoryById(db, memoryId) {
|
|
|
782
955
|
}
|
|
783
956
|
|
|
784
957
|
export {
|
|
785
|
-
|
|
786
|
-
|
|
958
|
+
isGeneratedCaptureContext,
|
|
959
|
+
containsGeneratedHistory,
|
|
960
|
+
isTaskLimitedRule,
|
|
961
|
+
hasNonDurableProvenance,
|
|
962
|
+
hasDirectCorrectionEvidence,
|
|
787
963
|
normalizeDedupeText,
|
|
788
964
|
memoryDedupeKey,
|
|
789
965
|
historySnippetDedupeKey,
|
|
790
966
|
activityEventDedupeKey,
|
|
791
967
|
hookCallDedupeKey,
|
|
968
|
+
recordAudit,
|
|
969
|
+
recordAuditWithSnapshot,
|
|
970
|
+
getAuditTrail,
|
|
971
|
+
getRecentAudit,
|
|
972
|
+
rollbackMemory,
|
|
973
|
+
formatAuditTrail,
|
|
792
974
|
ingestMemoryHeuristic,
|
|
793
975
|
ingestMemoryExtraction,
|
|
794
976
|
mergeAndIngest,
|
|
@@ -804,6 +986,7 @@ export {
|
|
|
804
986
|
demoteGlobalMemory,
|
|
805
987
|
rejectMemory,
|
|
806
988
|
confirmMemory,
|
|
989
|
+
reactivateMemory,
|
|
807
990
|
appendEvidence,
|
|
808
991
|
restoreAutoInject,
|
|
809
992
|
updateMemoryCaptureContext,
|
|
@@ -813,4 +996,4 @@ export {
|
|
|
813
996
|
getMemoryFeedbackSummaries,
|
|
814
997
|
feedbackWeightedScore
|
|
815
998
|
};
|
|
816
|
-
//# sourceMappingURL=chunk-
|
|
999
|
+
//# sourceMappingURL=chunk-HFHNPOBW.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/graph/ingest.ts","../src/models/memory.ts","../src/capture/provenance.ts","../src/models/dedupe.ts","../src/audit/trail.ts","../src/graph/extractor.ts"],"sourcesContent":["/**\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","import { eq, and, gte, inArray, like, sql } from \"drizzle-orm\";\nimport { randomUUID } from \"node:crypto\";\nimport { hasNonDurableProvenance } from \"../capture/provenance.js\";\nimport type { RecallDb } from \"../db/client.js\";\nimport { memories, feedbackEvents } from \"../db/schema.js\";\nimport { memoryDedupeKey } from \"./dedupe.js\";\nimport { recordAudit } from \"../audit/trail.js\";\nimport { queueMemoryEmbeddingSync } from \"../embeddings/embeddings.js\";\nimport { safeIngestMemoryById } from \"../graph/ingest.js\";\nimport {\n CONFIDENCE,\n PROMOTION,\n type MemoryItem,\n type MemoryQuery,\n type MemoryStatus,\n type MemoryType,\n type MemoryScope,\n type MemorySource,\n type EvidenceEntry,\n type CaptureContext,\n type FeedbackOutcome,\n} from \"../types.js\";\n\ntype MemoryRow = typeof memories.$inferSelect;\n\n// --- Create ---\n\nexport interface CreateMemoryInput {\n type: MemoryType;\n text: string;\n scope: MemoryScope;\n path_scope?: string | null;\n repo?: string | null;\n source: MemorySource;\n confidence?: number;\n evidence?: EvidenceEntry[];\n capture_context?: CaptureContext | null;\n supersedes?: string | null;\n dedupe?: boolean;\n}\n\nexport function statusFromConfidence(confidence: number): MemoryStatus {\n if (confidence < CONFIDENCE.TRANSIENT_MAX) return \"transient\";\n if (confidence < CONFIDENCE.CANDIDATE_MAX) return \"candidate\";\n return \"active\";\n}\n\nexport function createMemory(db: RecallDb, input: CreateMemoryInput): string {\n const now = new Date().toISOString();\n const id = randomUUID();\n const confidence = input.confidence ?? 0.35; // default: low candidate\n const status = statusFromConfidence(confidence);\n let scope = input.scope;\n let repo = input.repo ?? null;\n let pathScope = input.path_scope ?? null;\n if (scope === \"path\" && !pathScope) scope = repo ? \"repo\" : \"global\";\n if (scope === \"repo\" && !repo) scope = \"global\";\n if (scope === \"global\") {\n repo = null;\n pathScope = null;\n }\n const dedupeKey = input.dedupe === false\n ? null\n : memoryDedupeKey({\n type: input.type,\n scope,\n repo,\n path_scope: pathScope,\n text: input.text,\n });\n\n if (dedupeKey) {\n const existing = db.select().from(memories)\n .where(and(eq(memories.dedupe_key, dedupeKey), sql`${memories.status} != 'rejected'`))\n .get();\n if (existing) return existing.id;\n }\n\n // onConflictDoNothing closes the TOCTOU window between the pre-check SELECT\n // and this INSERT: when two writers race (e.g. concurrent Claude + Codex\n // session-start scans bootstrapping the same repo), both pass the SELECT\n // above, then one INSERT wins and the other previously threw\n // \"UNIQUE constraint failed: memories.dedupe_key\", crashing the whole hook.\n const result = db.insert(memories)\n .values({\n id,\n type: input.type,\n text: input.text,\n scope,\n path_scope: pathScope,\n repo,\n status,\n confidence,\n source: input.source,\n evidence: (input.evidence ?? []) as any,\n capture_context: input.capture_context ? input.capture_context as any : null,\n supersedes: input.supersedes ?? null,\n dedupe_key: dedupeKey,\n created_at: now,\n updated_at: now,\n last_validated_at: null,\n last_injected_at: null,\n injection_count: 0,\n override_count: 0,\n repetition_count: 0,\n })\n .onConflictDoNothing({ target: memories.dedupe_key })\n .run();\n\n if (dedupeKey && result.changes === 0) {\n // Lost the race (or a stale rejected row still holds the key): return the\n // existing memory's id rather than the uninserted one, and don't queue an\n // embedding for a row that was never written.\n const winner = db.select().from(memories)\n .where(eq(memories.dedupe_key, dedupeKey))\n .get();\n if (winner) return winner.id;\n }\n\n queueMemoryEmbeddingSync(db, id);\n return id;\n}\n\n// --- Read ---\n\nexport function getMemory(\n db: RecallDb,\n id: string,\n): MemoryItem | undefined {\n const row = db.select().from(memories).where(eq(memories.id, id)).get();\n if (!row) return undefined;\n return rowToMemory(row);\n}\n\nexport function queryMemories(\n db: RecallDb,\n query: MemoryQuery,\n): MemoryItem[] {\n const conditions = [];\n\n if (query.repo) conditions.push(eq(memories.repo, query.repo));\n if (query.status) conditions.push(eq(memories.status, query.status));\n if (query.type) conditions.push(eq(memories.type, query.type));\n if (query.scope) conditions.push(eq(memories.scope, query.scope));\n if (query.min_confidence != null)\n conditions.push(gte(memories.confidence, query.min_confidence));\n if (query.path) conditions.push(like(memories.path_scope, `%${query.path}%`));\n if (query.auto_inject != null) conditions.push(eq(memories.auto_inject, query.auto_inject));\n\n let statement = db.select().from(memories).$dynamic();\n if (conditions.length > 0) {\n statement = statement.where(and(...conditions));\n }\n if (query.offset != null) {\n statement = statement.offset(query.offset);\n }\n if (query.limit != null) {\n statement = statement.limit(query.limit);\n }\n\n const rows = statement.all();\n\n return rows.map(rowToMemory);\n}\n\nexport function listMemories(\n db: RecallDb,\n repo?: string,\n options: Pick<MemoryQuery, \"limit\" | \"offset\"> = {},\n): MemoryItem[] {\n return queryMemories(db, {\n repo,\n limit: options.limit,\n offset: options.offset,\n });\n}\n\nexport function listRepos(db: RecallDb): string[] {\n return [...new Set(\n db.select({ repo: memories.repo }).from(memories)\n .where(sql`${memories.status} != 'rejected'`)\n .all()\n .map((row) => row.repo)\n .filter((repo): repo is string => Boolean(repo)),\n )].sort();\n}\n\n// --- State transitions ---\n\nexport function promoteMemory(\n db: RecallDb,\n id: string,\n reason: \"explicit_confirm\" | \"repeat_correction\" | \"review_feedback\" | \"passive_gain\",\n evidence?: EvidenceEntry,\n): boolean {\n const mem = getMemory(db, id);\n if (!mem) return false;\n if (mem.status === \"rejected\") return false; // must use reactivate\n if (reason !== \"explicit_confirm\" && hasNonDurableProvenance(mem)) return false;\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 auto_inject: true,\n updated_at: now,\n last_validated_at: now,\n })\n .where(eq(memories.id, id))\n .run();\n\n queueMemoryEmbeddingSync(db, id);\n\n // A memory only enters the (verified-only) knowledge graph once it becomes\n // active. Ingest on the candidate→active transition so promoted memories\n // appear without waiting for the next daemon restart / reconcile.\n if (newStatus === \"active\" && mem.status !== \"active\") {\n safeIngestMemoryById(db, id);\n }\n return true;\n}\n\nexport function demoteMemory(\n db: RecallDb,\n id: string,\n reason: string,\n): boolean {\n const mem = getMemory(db, id);\n if (!mem) return false;\n\n const newConfidence = Math.max(0, mem.confidence - 0.3);\n const newStatus = statusFromConfidence(newConfidence);\n const now = new Date().toISOString();\n\n db.update(memories)\n .set({\n confidence: newConfidence,\n status: newStatus === \"transient\" ? \"candidate\" : newStatus, // don't lose it completely\n updated_at: now,\n })\n .where(eq(memories.id, id))\n .run();\n\n queueMemoryEmbeddingSync(db, id);\n return true;\n}\n\nexport type DemoteGlobalResult =\n | { ok: true; outcome: \"rescoped\" | \"rejected\"; memory: MemoryItem }\n | { ok: false; reason: \"not_found\" | \"not_global\" };\n\nexport function demoteGlobalMemory(\n db: RecallDb,\n id: string,\n opts: { repo?: string | null } = {},\n): DemoteGlobalResult {\n const mem = getMemory(db, id);\n if (!mem) return { ok: false, reason: \"not_found\" };\n if (mem.scope !== \"global\") return { ok: false, reason: \"not_global\" };\n\n const targetRepo = opts.repo?.trim() || null;\n const now = new Date().toISOString();\n\n if (targetRepo) {\n const newDedupe = memoryDedupeKey({\n type: mem.type,\n scope: \"repo\",\n repo: targetRepo,\n path_scope: mem.path_scope,\n text: mem.text,\n });\n db.update(memories)\n .set({\n scope: \"repo\",\n repo: targetRepo,\n dedupe_key: newDedupe,\n updated_at: now,\n })\n .where(eq(memories.id, id))\n .run();\n } else {\n db.update(memories)\n .set({\n status: \"rejected\",\n confidence: 0,\n dedupe_key: null,\n updated_at: now,\n })\n .where(eq(memories.id, id))\n .run();\n }\n\n queueMemoryEmbeddingSync(db, id);\n const updated = getMemory(db, id)!;\n return { ok: true, outcome: targetRepo ? \"rescoped\" : \"rejected\", memory: updated };\n}\n\n/**\n * Reject a memory.\n *\n * `actor` records who decided. This matters beyond bookkeeping: a rejection a\n * human issued becomes a \"never capture this again\" exemplar for the capture\n * path, while a machine retirement (staleness, policy, pruning) must not. This\n * function previously wrote no audit row at all, so provenance was simply\n * absent for most rejections and the capture path had to guess — it guessed\n * \"human\", which turned routine cleanup into permanent capture blocks.\n *\n * Defaults to \"system\" so an unattributed caller is never mistaken for a\n * deliberate human verdict.\n */\nexport function rejectMemory(db: RecallDb, id: string, actor = \"system\"): boolean {\n const mem = getMemory(db, id);\n if (!mem) return false;\n\n const beforeSnapshot = JSON.stringify(mem);\n\n db.update(memories)\n .set({\n status: \"rejected\",\n confidence: 0,\n dedupe_key: null,\n updated_at: new Date().toISOString(),\n })\n .where(eq(memories.id, id))\n .run();\n\n recordAudit(db, id, \"rejected\", actor, null, beforeSnapshot);\n\n queueMemoryEmbeddingSync(db, id);\n return true;\n}\n\nexport function confirmMemory(db: RecallDb, id: string): boolean {\n return promoteMemory(db, id, \"explicit_confirm\", {\n type: \"session_correction\",\n session: \"cli\",\n timestamp: new Date().toISOString(),\n context: \"user explicitly confirmed\",\n });\n}\n\nexport function reactivateMemory(\n db: RecallDb,\n id: string,\n evidence: EvidenceEntry,\n): boolean {\n const mem = getMemory(db, id);\n if (!mem) return false;\n if (mem.status !== \"rejected\") return false;\n\n const now = new Date().toISOString();\n const dedupeKey = memoryDedupeKey(mem);\n const existing = db.select().from(memories)\n .where(and(eq(memories.dedupe_key, dedupeKey), sql`${memories.status} != 'rejected'`))\n .get();\n if (existing && existing.id !== id) return false;\n\n db.update(memories)\n .set({\n status: \"candidate\",\n confidence: CONFIDENCE.TRANSIENT_MAX + 0.05,\n dedupe_key: dedupeKey,\n evidence: [...mem.evidence, evidence] as any,\n updated_at: now,\n })\n .where(eq(memories.id, id))\n .run();\n\n queueMemoryEmbeddingSync(db, id);\n return true;\n}\n\nexport function appendEvidence(\n db: RecallDb,\n id: string,\n evidence: EvidenceEntry,\n): boolean {\n const mem = getMemory(db, id);\n if (!mem) return false;\n if (hasEquivalentEvidence(mem.evidence, evidence)) return true;\n\n const now = new Date().toISOString();\n db.update(memories)\n .set({\n evidence: [...mem.evidence, evidence] as any,\n updated_at: now,\n last_validated_at: now,\n })\n .where(eq(memories.id, id))\n .run();\n\n return true;\n}\n\n// An archived memory (auto_inject cleared by the stale-archiver) that the user\n// teaches again is, by definition, relevant again. Reinforcement puts it back\n// into automatic injection instead of leaving it retrievable-but-silent.\nexport function restoreAutoInject(db: RecallDb, id: string): boolean {\n const mem = getMemory(db, id);\n if (!mem || mem.auto_inject || hasNonDurableProvenance(mem)) 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 || mem.status === \"rejected\" || hasNonDurableProvenance(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","import type { MemoryItem } from \"../types.js\";\n\n// These are transport envelopes, not natural-language intent heuristics.\n// A generated message arriving on a user-prompt hook is still generated.\nexport function isGeneratedCaptureContext(text: string): boolean {\n return /^\\s*<(?:system|developer|paseo-system|agent-response|task-notification|system-reminder)(?:\\s|>)/i.test(text)\n || /^\\s*\\[(?:system|developer|tool result)\\]/i.test(text)\n || /^\\s*generate a title and a git branch name for a coding agent\\b/i.test(text)\n || (/^\\s*(?:classify|analy[sz]e|extract|score|summari[sz]e|generate|you are)\\b/i.test(text)\n && /\\b(?:return|output|respond)[^\\n]{0,45}\\bJSON\\b/i.test(text)\n && (/\"(?:expected_schema_version|schema_version|source_text|raw_prompt)\"\\s*:/.test(text)\n || /(?:^|\\n)Routes:\\s*\\n/.test(text)));\n}\n\nexport function containsGeneratedHistory(text: string): boolean {\n return text.split(\"\\n\").some((line) => isGeneratedCaptureContext(\n line.replace(/^\\s*(?:[-*]\\s*)?(?:\\(\\d+\\)\\s*)?/, \"\"),\n )) || isGeneratedCaptureContext(text);\n}\n\nexport function isTaskLimitedRule(text: string): boolean {\n return /^\\s*(?:for|during) (?:this|the current) (?:repository )?(?:review|task|turn|session)\\b/i.test(text);\n}\n\nexport function hasNonDurableProvenance(memory: MemoryItem): boolean {\n return hasOnlyGeneratedEvidence(memory) || isTaskLimitedRule(memory.text);\n}\n\nexport function hasOnlyGeneratedEvidence(memory: MemoryItem): boolean {\n const contexts = memory.evidence\n .filter((entry) => entry.type === \"session_correction\" || entry.type === \"review_feedback\")\n .map((entry) => entry.context?.trim())\n .filter((context): context is string => Boolean(context));\n return contexts.length > 0 && contexts.every(isGeneratedCaptureContext);\n}\n\nexport function hasDirectCorrectionEvidence(memory: MemoryItem): boolean {\n return memory.source === \"user_correction\" && memory.evidence.some((entry) =>\n entry.type === \"session_correction\"\n && Boolean(entry.context?.trim())\n && !isGeneratedCaptureContext(entry.context ?? \"\"),\n );\n}\n","import { createHash } from \"node:crypto\";\nimport { defineOwn } from \"../security/object.js\";\n\nexport const ACTIVITY_DEDUPE_PREFIX = \"activity\\u001fsha256:\";\nexport const HOOK_DEDUPE_PREFIX = \"hook\\u001fsha256:\";\n\nexport function compactDedupeKey(\n namespace: \"activity\" | \"hook\",\n legacyKey: string,\n): string {\n const prefix = namespace === \"activity\"\n ? ACTIVITY_DEDUPE_PREFIX\n : HOOK_DEDUPE_PREFIX;\n return `${prefix}${createHash(\"sha256\").update(legacyKey).digest(\"hex\")}`;\n}\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 const legacyKey = [\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 return compactDedupeKey(\"activity\", legacyKey);\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 const legacyKey = [\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 return compactDedupeKey(\"hook\", legacyKey);\n}\n\nexport function stripVolatileFields(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map(stripVolatileFields);\n }\n if (!value || typeof value !== \"object\") {\n return value;\n }\n\n const out: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n if (/_at$/u.test(key) || key === \"timestamp\") continue;\n if (entry === undefined) continue;\n defineOwn(out, key, stripVolatileFields(entry));\n }\n return out;\n}\n\nexport function stableDedupeJson(value: unknown): string {\n if (Array.isArray(value)) {\n return `[${value.map(stableDedupeJson).join(\",\")}]`;\n }\n if (!value || typeof value !== \"object\") {\n return JSON.stringify(value);\n }\n\n const record = value as Record<string, unknown>;\n return `{${Object.keys(record).sort().map((key) => (\n `${JSON.stringify(key)}:${stableDedupeJson(record[key])}`\n )).join(\",\")}}`;\n}\n","/**\n * Audit trail — versioned history of every memory mutation.\n *\n * Records who changed what, when, why. Supports diff between versions\n * and rollback to a previous state.\n */\n\nimport { eq, desc } from \"drizzle-orm\";\nimport { randomUUID } from \"node:crypto\";\nimport type { RecallDb } from \"../db/client.js\";\nimport { auditTrail, memories } from \"../db/schema.js\";\nimport { queueMemoryEmbeddingSync } from \"../embeddings/embeddings.js\";\nimport { getMemory } from \"../models/memory.js\";\nimport type { AuditAction, AuditEntry, MemoryItem } from \"../types.js\";\n\n// --- Record an audit entry ---\n\nexport function recordAudit(\n db: RecallDb,\n memoryId: string,\n action: AuditAction,\n actor: string,\n reason: string | null,\n beforeSnapshot?: string | null,\n afterSnapshot?: string | null,\n): string {\n const id = randomUUID();\n\n // Auto-capture snapshots if not provided\n if (afterSnapshot === undefined) {\n const mem = getMemory(db, memoryId);\n if (mem) {\n afterSnapshot = JSON.stringify(mem);\n }\n }\n\n db.insert(auditTrail)\n .values({\n id,\n memory_id: memoryId,\n action,\n actor,\n before_snapshot: beforeSnapshot ?? null,\n after_snapshot: afterSnapshot ?? null,\n reason: reason ?? null,\n timestamp: new Date().toISOString(),\n })\n .run();\n\n return id;\n}\n\n/** Record with explicit before/after snapshots */\nexport function recordAuditWithSnapshot(\n db: RecallDb,\n memoryId: string,\n action: AuditAction,\n actor: string,\n reason: string | null,\n before: MemoryItem | null,\n after: MemoryItem | null,\n): string {\n return recordAudit(\n db,\n memoryId,\n action,\n actor,\n reason,\n before ? JSON.stringify(before) : null,\n after ? JSON.stringify(after) : null,\n );\n}\n\n// --- Query audit trail ---\n\nexport function getAuditTrail(\n db: RecallDb,\n memoryId: string,\n): AuditEntry[] {\n return db\n .select()\n .from(auditTrail)\n .where(eq(auditTrail.memory_id, memoryId))\n .orderBy(desc(auditTrail.timestamp))\n .all()\n .map(rowToAudit);\n}\n\nexport function getRecentAudit(\n db: RecallDb,\n limit: number = 50,\n): AuditEntry[] {\n return db\n .select()\n .from(auditTrail)\n .orderBy(desc(auditTrail.timestamp))\n .limit(limit)\n .all()\n .map(rowToAudit);\n}\n\n// --- Diff between versions ---\n\nexport interface MemoryDiff {\n field: string;\n before: unknown;\n after: unknown;\n}\n\nexport function diffSnapshots(\n before: string | null,\n after: string | null,\n): MemoryDiff[] {\n if (!before || !after) return [];\n\n const a = JSON.parse(before);\n const b = JSON.parse(after);\n const diffs: MemoryDiff[] = [];\n\n const keys = new Set([...Object.keys(a), ...Object.keys(b)]);\n for (const key of keys) {\n if (key === \"evidence\" || key === \"embedding\") continue; // skip large fields\n const va = JSON.stringify(a[key]);\n const vb = JSON.stringify(b[key]);\n if (va !== vb) {\n diffs.push({ field: key, before: a[key], after: b[key] });\n }\n }\n\n return diffs;\n}\n\n// --- Rollback ---\n\nexport function rollbackMemory(\n db: RecallDb,\n memoryId: string,\n auditEntryId: string,\n actor: string,\n): boolean {\n const entry = db\n .select()\n .from(auditTrail)\n .where(eq(auditTrail.id, auditEntryId))\n .get();\n\n if (!entry) return false;\n\n // Use the before_snapshot to restore state\n const snapshot = entry.before_snapshot;\n if (!snapshot) return false;\n\n const beforeRollback = getMemory(db, memoryId);\n const restored = JSON.parse(snapshot) as MemoryItem;\n\n db.update(memories)\n .set({\n text: restored.text,\n type: restored.type,\n scope: restored.scope,\n path_scope: restored.path_scope,\n status: restored.status,\n confidence: restored.confidence,\n source: restored.source,\n evidence: restored.evidence as any,\n capture_context: restored.capture_context as any,\n repetition_count: restored.repetition_count,\n updated_at: new Date().toISOString(),\n })\n .where(eq(memories.id, memoryId))\n .run();\n queueMemoryEmbeddingSync(db, memoryId);\n\n recordAuditWithSnapshot(\n db,\n memoryId,\n \"rolled_back\",\n actor,\n `Rolled back to state from ${entry.timestamp}`,\n beforeRollback ?? null,\n getMemory(db, memoryId) ?? null,\n );\n\n return true;\n}\n\n// --- Format audit trail ---\n\nexport function formatAuditTrail(entries: AuditEntry[]): string {\n if (entries.length === 0) return \"No audit entries.\";\n\n const lines = [\"# Audit Trail\", \"\"];\n for (const e of entries) {\n const diffs = diffSnapshots(e.before_snapshot, e.after_snapshot);\n const diffStr = diffs.length > 0\n ? ` [${diffs.map((d) => `${d.field}: ${JSON.stringify(d.before)} → ${JSON.stringify(d.after)}`).join(\", \")}]`\n : \"\";\n lines.push(\n `${e.timestamp.slice(0, 19)} ${e.action.padEnd(22)} by ${e.actor}${e.reason ? ` — ${e.reason}` : \"\"}${diffStr}`,\n );\n }\n\n return lines.join(\"\\n\");\n}\n\n// --- Helpers ---\n\nfunction rowToAudit(row: any): AuditEntry {\n return {\n id: row.id,\n memory_id: row.memory_id,\n action: row.action,\n actor: row.actor,\n before_snapshot: row.before_snapshot,\n after_snapshot: row.after_snapshot,\n reason: row.reason,\n timestamp: row.timestamp,\n };\n}\n","/**\n * Entity extractor. Pulls entities (files, functions, libraries, tools,\n * concepts, paths, commands, URLs) plus typed relations out of memory text.\n *\n * Two paths:\n * 1. heuristic() — always runs, cheap, regex-based, deterministic.\n * Catches paths, package-like names, identifier-shaped function calls,\n * common CLI tools, URLs. Used on every memory write.\n *\n * 2. llmEnrich() — opt-in; runs when an LLM provider is configured.\n * Reads the memory text + the heuristic seed and returns canonical\n * entity names + relations between them. Drives multi-hop graph walks.\n */\nimport type { RelationType } from \"./store.js\";\nimport type { EntityKind } from \"./normalize.js\";\nimport { isPlausibleEntityName } from \"./normalize.js\";\n\nexport interface ExtractedEntity {\n kind: EntityKind;\n name: string;\n /** 'heuristic' for regex output, 'llm' for model-extracted, 'manual' for user. */\n source: \"heuristic\" | \"llm\" | \"manual\";\n /** Where this mention came from in the source text, if known. */\n weight?: number;\n}\n\nexport interface ExtractedRelation {\n source: { kind: EntityKind; name: string };\n target: { kind: EntityKind; name: string };\n relation: RelationType;\n confidence: number;\n}\n\nexport interface ExtractionResult {\n entities: ExtractedEntity[];\n relations: ExtractedRelation[];\n}\n\n// ---- Heuristic extractor ----------------------------------------------------\n\n// File paths: src/foo/bar.ts, ./scripts/x.sh, docs/README.md\nconst PATH_RE = /(?:^|[\\s`'\"(])((?:\\.{0,2}\\/)?(?:[A-Za-z0-9_.-]+\\/){1,}[A-Za-z0-9_.-]+\\.[A-Za-z0-9]{1,8})/g;\n// Inline-coded short identifiers: `foo()`, `Bar.method()`\nconst FUNC_RE = /`([A-Za-z_][\\w.]{1,}\\(\\))`/g;\n// Package-like names in backticks: `react`, `@scope/pkg`, `drizzle-orm`.\n// Two flavours:\n// - SCOPED_PACKAGE_RE: @scope/name and hyphenated names — high-confidence\n// - SIMPLE_PACKAGE_RE: single lowercase words in backticks — gated by a stop-list\nconst SCOPED_PACKAGE_RE = /`(@[a-z0-9_-]+\\/[a-z0-9_.-]+|[a-z][a-z0-9_-]*(?:-[a-z0-9]+)+)`/g;\nconst SIMPLE_PACKAGE_RE = /`([a-z][a-z0-9_]{2,30})`/g;\n// Common English / generic words that look package-shaped but aren't.\nconst PACKAGE_STOPWORDS = new Set([\n \"the\", \"and\", \"but\", \"for\", \"use\", \"uses\", \"used\", \"with\", \"from\", \"this\",\n \"that\", \"have\", \"has\", \"true\", \"false\", \"null\", \"void\", \"data\", \"code\",\n \"test\", \"tests\", \"build\", \"run\", \"runs\", \"name\", \"type\", \"types\", \"main\",\n \"yes\", \"no\", \"ok\", \"all\", \"any\", \"new\", \"old\", \"more\", \"less\", \"always\",\n \"never\", \"todo\", \"fixme\", \"note\", \"warn\", \"info\", \"error\", \"ts\", \"js\",\n // Shell / language builtins that look package-shaped in backticks but are\n // not libraries (\"echo\", \"dict\", ...).\n \"echo\", \"dict\", \"list\", \"set\", \"map\", \"str\", \"int\", \"bool\", \"float\",\n \"print\", \"println\", \"log\", \"dir\", \"env\", \"tmp\", \"src\", \"lib\", \"bin\",\n \"out\", \"obj\", \"val\", \"var\", \"let\", \"const\", \"func\", \"def\", \"cls\", \"self\",\n \"args\", \"kwargs\", \"none\", \"cat\", \"grep\", \"sed\", \"awk\", \"cwd\", \"std\",\n]);\n// Bare CLI invocation lines: `npm test`, `pnpm i`, `cargo build`\nconst CLI_RE = /\\b(npm|pnpm|yarn|bun|cargo|go|uv|pip|node|deno|claude|codex|cursor|recall|brew|gh|git)\\s+([a-z][a-z-]{0,30})\\b/g;\n// Package managers + runtimes whose `<tool> <word>` pairs are almost always\n// generic build/script noise (\"pnpm build\", \"node dist\", \"npm run\") or English\n// filler grabbed from prose (\"Use pnpm as ...\", \"npm install\" → \"npm in\").\n// For these we record the tool itself but never a `command` entity.\nconst TOOL_ONLY_CLIS = new Set([\"npm\", \"pnpm\", \"yarn\", \"bun\", \"node\", \"deno\"]);\n// Second tokens that are English filler, not real subcommands — reject the\n// whole match so we don't mint entities like \"pnpm as\" or \"git it\".\nconst CLI_SUBCOMMAND_STOPWORDS = new Set([\n \"a\", \"an\", \"and\", \"are\", \"as\", \"at\", \"be\", \"by\", \"can\", \"do\", \"does\", \"for\",\n \"from\", \"has\", \"have\", \"i\", \"if\", \"in\", \"into\", \"is\", \"it\", \"its\", \"no\",\n \"not\", \"of\", \"on\", \"or\", \"so\", \"that\", \"the\", \"then\", \"this\", \"to\", \"up\",\n \"via\", \"was\", \"we\", \"will\", \"with\", \"you\",\n]);\n// URLs\nconst URL_RE = /\\bhttps?:\\/\\/[^\\s<>\"'`)]+/g;\n\n// Relation keyword cues. Order matters — first match wins for a sentence.\nconst RELATION_CUES: Array<{ rx: RegExp; relation: RelationType; flip?: boolean }> = [\n { rx: /\\b(?:replaces?|replaced|supersedes?|superseded|deprecates?|deprecated)\\b/i, relation: \"replaces\" },\n { rx: /\\b(?:conflicts? with|incompatible with|clashes? with)\\b/i, relation: \"conflicts_with\" },\n { rx: /\\b(?:tested by|covered by)\\b/i, relation: \"tested_by\" },\n { rx: /\\b(?:depends on|requires|required by)\\b/i, relation: \"depends_on\" },\n { rx: /\\b(?:uses?|used|relies on|via)\\b/i, relation: \"uses\" },\n { rx: /\\b(?:references?|see also|cf\\.)\\b/i, relation: \"references\" },\n { rx: /\\b(?:part of|inside|under)\\b/i, relation: \"part_of\" },\n];\n\nexport function heuristic(text: string): ExtractionResult {\n const entities = new Map<string, ExtractedEntity>(); // dedupe by (kind|name)\n const relations: ExtractedRelation[] = [];\n\n const push = (kind: EntityKind, name: string, weight = 1) => {\n if (!isPlausibleEntityName(kind, name)) return;\n const key = `${kind}|${name}`;\n const existing = entities.get(key);\n if (existing) {\n existing.weight = (existing.weight ?? 1) + weight;\n } else {\n entities.set(key, { kind, name, source: \"heuristic\", weight });\n }\n };\n\n // Files / paths\n for (const m of text.matchAll(PATH_RE)) {\n const raw = m[1];\n // Discriminate `repo_path` (no extension) vs `file` — both produce graph\n // nodes, but only `file` is treated as a file-system artifact.\n if (raw.includes(\".\") && !raw.endsWith(\"/\")) {\n push(\"file\", raw);\n } else {\n push(\"repo_path\", raw);\n }\n }\n\n // Functions in backticks\n for (const m of text.matchAll(FUNC_RE)) {\n push(\"function\", m[1]);\n }\n\n // Packages in backticks — scoped/hyphenated first (high confidence)\n for (const m of text.matchAll(SCOPED_PACKAGE_RE)) {\n push(\"library\", m[1]);\n }\n // Single-word backticked tokens, filtered by stop-list\n for (const m of text.matchAll(SIMPLE_PACKAGE_RE)) {\n const candidate = m[1];\n if (PACKAGE_STOPWORDS.has(candidate)) continue;\n push(\"library\", candidate, 0.7);\n }\n\n // CLI commands\n for (const m of text.matchAll(CLI_RE)) {\n const tool = m[1];\n const sub = m[2];\n // English filler after the tool (\"pnpm as\", \"npm in\") is not a command.\n if (CLI_SUBCOMMAND_STOPWORDS.has(sub)) {\n push(\"tool\", tool);\n continue;\n }\n push(\"tool\", tool);\n // Package managers / runtimes: the `<tool> <script>` pair is generic\n // tooling noise (\"pnpm build\", \"node dist\"). Keep only the tool node.\n if (TOOL_ONLY_CLIS.has(tool)) continue;\n push(\"command\", `${tool} ${sub}`);\n }\n\n // URLs\n for (const m of text.matchAll(URL_RE)) {\n push(\"url\", m[0]);\n }\n\n // Relations: split into sentences, look for a cue + two entity mentions.\n const sentences = text.split(/(?<=[.!?])\\s+|\\n+/);\n for (const sentence of sentences) {\n const cue = RELATION_CUES.find((c) => c.rx.test(sentence));\n if (!cue) continue;\n const mentioned: Array<{ kind: EntityKind; name: string; idx: number }> = [];\n for (const ent of entities.values()) {\n const idx = sentence.indexOf(ent.name);\n if (idx >= 0) mentioned.push({ kind: ent.kind, name: ent.name, idx });\n }\n if (mentioned.length < 2) continue;\n mentioned.sort((a, b) => a.idx - b.idx);\n relations.push({\n source: { kind: mentioned[0].kind, name: mentioned[0].name },\n target: { kind: mentioned[1].kind, name: mentioned[1].name },\n relation: cue.relation,\n confidence: 0.5,\n });\n }\n\n return { entities: Array.from(entities.values()), relations };\n}\n\n// ---- LLM enrichment --------------------------------------------------------\n\nexport const ENTITY_EXTRACTION_SYSTEM = `You extract code-graph entities and typed relations from short engineering notes (rules, decisions, gotchas).\n\nReturn STRICT JSON only — no prose, no fences. Shape:\n{\n \"entities\": [{\"kind\": \"<one of: file|function|library|tool|concept|repo_path|command|url>\", \"name\": \"<canonical surface form>\"}],\n \"relations\": [{\"source\": {\"kind\": \"...\", \"name\": \"...\"}, \"target\": {\"kind\": \"...\", \"name\": \"...\"}, \"relation\": \"<one of: uses|replaces|conflicts_with|tested_by|depends_on|references|part_of>\", \"confidence\": 0.0-1.0}]\n}\n\nRules:\n- Only include entities the text actually mentions. Do NOT invent.\n- Prefer the most specific kind: a file path is \"file\", a library name is \"library\", a CLI like \"npm install\" is \"command\".\n- \"concept\" is a last resort for domain words (\"authentication\", \"rate limiting\").\n- Skip generic English (pronouns, verbs, adjectives).\n- If the text is purely about user preferences or behaviour with no nameable artifact, return {\"entities\": [], \"relations\": []}.\n- Be conservative on relations — only include one when the text clearly states it.`;\n\nexport interface LlmExtractInput {\n memoryText: string;\n /** Optional seed list from the heuristic pass — saves the LLM a step. */\n seed?: ExtractedEntity[];\n}\n\nexport function buildExtractionPrompt(input: LlmExtractInput): string {\n const seedBlock = input.seed && input.seed.length > 0\n ? `\\n\\nHeuristic seed (use as hints, refine or override):\\n${input.seed\n .slice(0, 20)\n .map((e) => `- ${e.kind}: ${e.name}`)\n .join(\"\\n\")}`\n : \"\";\n return `Memory text:\\n\"\"\"\\n${input.memoryText}\\n\"\"\"${seedBlock}\\n\\nReturn STRICT JSON.`;\n}\n\n/**\n * Parse the LLM response into an ExtractionResult, tolerating fenced code\n * and surrounding prose. Returns null if no valid shape is recognised.\n */\nexport function parseLlmExtraction(raw: string): ExtractionResult | null {\n let text = raw.trim();\n // Strip code fences if present\n const fenceMatch = text.match(/```(?:json)?\\s*([\\s\\S]+?)\\s*```/);\n if (fenceMatch) text = fenceMatch[1].trim();\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return null;\n }\n if (typeof parsed !== \"object\" || parsed === null) return null;\n const obj = parsed as Record<string, unknown>;\n const entities = sanitiseEntities(obj.entities);\n const relations = sanitiseRelations(obj.relations);\n return { entities, relations };\n}\n\nconst VALID_KINDS: ReadonlySet<EntityKind> = new Set<EntityKind>([\n \"file\", \"function\", \"library\", \"tool\", \"concept\", \"repo_path\", \"command\", \"url\",\n]);\nconst VALID_RELATIONS: ReadonlySet<RelationType> = new Set<RelationType>([\n \"uses\", \"replaces\", \"conflicts_with\", \"tested_by\", \"depends_on\", \"references\", \"part_of\",\n]);\n\nfunction sanitiseEntities(raw: unknown): ExtractedEntity[] {\n if (!Array.isArray(raw)) return [];\n const out: ExtractedEntity[] = [];\n for (const item of raw) {\n if (!item || typeof item !== \"object\") continue;\n const o = item as Record<string, unknown>;\n const kind = String(o.kind ?? \"\");\n const name = String(o.name ?? \"\").trim();\n if (!VALID_KINDS.has(kind as EntityKind)) continue;\n if (!isPlausibleEntityName(kind as EntityKind, name)) continue;\n out.push({ kind: kind as EntityKind, name, source: \"llm\" });\n }\n return out;\n}\n\nfunction sanitiseRelations(raw: unknown): ExtractedRelation[] {\n if (!Array.isArray(raw)) return [];\n const out: ExtractedRelation[] = [];\n for (const item of raw) {\n if (!item || typeof item !== \"object\") continue;\n const o = item as Record<string, unknown>;\n const rel = String(o.relation ?? \"\");\n if (!VALID_RELATIONS.has(rel as RelationType)) continue;\n const source = parseEndpoint(o.source);\n const target = parseEndpoint(o.target);\n if (!source || !target) continue;\n const confidence = typeof o.confidence === \"number\"\n ? Math.max(0, Math.min(1, o.confidence))\n : 0.6;\n out.push({ source, target, relation: rel as RelationType, confidence });\n }\n return out;\n}\n\nfunction parseEndpoint(raw: unknown): { kind: EntityKind; name: string } | null {\n if (!raw || typeof raw !== \"object\") return null;\n const o = raw as Record<string, unknown>;\n const kind = String(o.kind ?? \"\");\n const name = String(o.name ?? \"\").trim();\n if (!VALID_KINDS.has(kind as EntityKind)) return null;\n if (!isPlausibleEntityName(kind as EntityKind, name)) return null;\n return { kind: kind as EntityKind, name };\n}\n\n/**\n * Merge a heuristic pass with an LLM pass. LLM entries override heuristic\n * ones on the same (kind, name) — the model's source tag takes precedence\n * because it's the higher-quality signal.\n */\nexport function mergeExtractions(...passes: ExtractionResult[]): ExtractionResult {\n const entities = new Map<string, ExtractedEntity>();\n for (const pass of passes) {\n for (const ent of pass.entities) {\n const key = `${ent.kind}|${ent.name}`;\n const prev = entities.get(key);\n if (!prev || (prev.source === \"heuristic\" && ent.source === \"llm\")) {\n entities.set(key, ent);\n }\n }\n }\n // Deduplicate relations on (source, target, relation).\n const relations = new Map<string, ExtractedRelation>();\n for (const pass of passes) {\n for (const rel of pass.relations) {\n const key = `${rel.source.kind}|${rel.source.name}->${rel.relation}->${rel.target.kind}|${rel.target.name}`;\n const prev = relations.get(key);\n if (!prev || rel.confidence > prev.confidence) {\n relations.set(key, rel);\n }\n }\n }\n return {\n entities: Array.from(entities.values()),\n relations: Array.from(relations.values()),\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;;;ACAA;AACA,SAAS,cAAAA,mBAAkB;;;ACD3B;AAIO,SAAS,0BAA0B,MAAuB;AAC/D,SAAO,mGAAmG,KAAK,IAAI,KAC9G,4CAA4C,KAAK,IAAI,KACrD,mEAAmE,KAAK,IAAI,KAC3E,6EAA6E,KAAK,IAAI,KACrF,kDAAkD,KAAK,IAAI,MAC1D,0EAA0E,KAAK,IAAI,KAClF,uBAAuB,KAAK,IAAI;AAC3C;AAEO,SAAS,yBAAyB,MAAuB;AAC9D,SAAO,KAAK,MAAM,IAAI,EAAE,KAAK,CAAC,SAAS;AAAA,IACrC,KAAK,QAAQ,mCAAmC,EAAE;AAAA,EACpD,CAAC,KAAK,0BAA0B,IAAI;AACtC;AAEO,SAAS,kBAAkB,MAAuB;AACvD,SAAO,0FAA0F,KAAK,I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21 @@
|
|
|
1
1
|
import {
|
|
2
2
|
textMatchScore
|
|
3
|
-
} from "./chunk-
|
|
4
|
-
import {
|
|
5
|
-
asc,
|
|
6
|
-
desc
|
|
7
|
-
} from "./chunk-CW3XJDH7.js";
|
|
3
|
+
} from "./chunk-7Z3CCCS2.js";
|
|
8
4
|
import {
|
|
9
5
|
getMemory,
|
|
10
6
|
promoteMemory,
|
|
11
7
|
queryMemories
|
|
12
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-HFHNPOBW.js";
|
|
9
|
+
import {
|
|
10
|
+
asc,
|
|
11
|
+
desc
|
|
12
|
+
} from "./chunk-RWEX4VJE.js";
|
|
13
13
|
import {
|
|
14
14
|
cosineSimilarity,
|
|
15
15
|
generateEmbedding,
|
|
16
16
|
loadEmbedding,
|
|
17
17
|
loadEmbeddingConfigFromEnv
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-BWKFROGW.js";
|
|
19
19
|
import {
|
|
20
20
|
and,
|
|
21
21
|
eq,
|
|
@@ -26,12 +26,17 @@ import {
|
|
|
26
26
|
memoryInjections,
|
|
27
27
|
memoryValueEvents,
|
|
28
28
|
sql
|
|
29
|
-
} from "./chunk-
|
|
29
|
+
} from "./chunk-VSEAVK7X.js";
|
|
30
|
+
import {
|
|
31
|
+
init_define_RECALL_BUILD_INFO
|
|
32
|
+
} from "./chunk-CYAODQOH.js";
|
|
30
33
|
|
|
31
34
|
// src/models/memory-value.ts
|
|
35
|
+
init_define_RECALL_BUILD_INFO();
|
|
32
36
|
import { randomUUID as randomUUID2 } from "crypto";
|
|
33
37
|
|
|
34
38
|
// src/models/memory-injections.ts
|
|
39
|
+
init_define_RECALL_BUILD_INFO();
|
|
35
40
|
import { randomUUID } from "crypto";
|
|
36
41
|
function recordMemoryInjections(db, input) {
|
|
37
42
|
if (!input.session_id || input.memory_ids.length === 0) return 0;
|
|
@@ -612,4 +617,4 @@ export {
|
|
|
612
617
|
detectAndRecordRetrievalMissesSemantic,
|
|
613
618
|
computeMemoryValueReport
|
|
614
619
|
};
|
|
615
|
-
//# sourceMappingURL=chunk-
|
|
620
|
+
//# sourceMappingURL=chunk-HRUNR5JJ.js.map
|