@edihasaj/recall 0.6.7 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +57 -1
  2. package/dist/chunk-37K4DPRI.js +17 -0
  3. package/dist/chunk-37K4DPRI.js.map +1 -0
  4. package/dist/chunk-AKODTKWM.js +123 -0
  5. package/dist/chunk-AKODTKWM.js.map +1 -0
  6. package/dist/{chunk-4P3NKEIJ.js → chunk-CPOANMKD.js} +18 -9
  7. package/dist/{chunk-4P3NKEIJ.js.map → chunk-CPOANMKD.js.map} +1 -1
  8. package/dist/{chunk-AJAAK4FK.js → chunk-GNXTOM5K.js} +159 -9
  9. package/dist/chunk-GNXTOM5K.js.map +1 -0
  10. package/dist/chunk-JRIM7VBY.js +2346 -0
  11. package/dist/chunk-JRIM7VBY.js.map +1 -0
  12. package/dist/chunk-PG2ZVVAT.js +6525 -0
  13. package/dist/chunk-PG2ZVVAT.js.map +1 -0
  14. package/dist/{chunk-LFWG3CBM.js → chunk-PH6YNVHR.js} +206 -2381
  15. package/dist/chunk-PH6YNVHR.js.map +1 -0
  16. package/dist/chunk-QDA5M3AJ.js +2617 -0
  17. package/dist/chunk-QDA5M3AJ.js.map +1 -0
  18. package/dist/chunk-QSJKGEID.js +235 -0
  19. package/dist/chunk-QSJKGEID.js.map +1 -0
  20. package/dist/chunk-UBPGOOAN.js +462 -0
  21. package/dist/chunk-UBPGOOAN.js.map +1 -0
  22. package/dist/{chunk-XUM7JEJU.js → chunk-YL23MKB3.js} +10 -4
  23. package/dist/{chunk-XUM7JEJU.js.map → chunk-YL23MKB3.js.map} +1 -1
  24. package/dist/chunk-Z6RT5BUO.js +282 -0
  25. package/dist/chunk-Z6RT5BUO.js.map +1 -0
  26. package/dist/{cleanup-JM3CGHUV.js → cleanup-YGHZIYLJ.js} +6 -3
  27. package/dist/cli.js +160 -26
  28. package/dist/cli.js.map +1 -1
  29. package/dist/daemon.js +662 -42
  30. package/dist/daemon.js.map +1 -1
  31. package/dist/{dispatcher-C5S7SYY6.js → dispatcher-5MDL3QQT.js} +6 -3
  32. package/dist/embeddings-GKNH2E3N.js +48 -0
  33. package/dist/ingest-JWXX22QX.js +19 -0
  34. package/dist/mcp.js +9 -4
  35. package/dist/mcp.js.map +1 -1
  36. package/dist/{quality-YTQKAEY6.js → quality-2JOLSIC3.js} +4 -3
  37. package/dist/quality-2JOLSIC3.js.map +1 -0
  38. package/dist/retrieval-GLAEYWGA.js +13 -0
  39. package/dist/retrieval-GLAEYWGA.js.map +1 -0
  40. package/dist/store-2BPQPOOZ.js +31 -0
  41. package/dist/store-2BPQPOOZ.js.map +1 -0
  42. package/dist/{tasks-KHLJT7MP.js → tasks-6J3LULYO.js} +6 -3
  43. package/dist/tasks-6J3LULYO.js.map +1 -0
  44. package/dist/{usage-DU4TKVJH.js → usage-YBS74UEU.js} +8 -4
  45. package/dist/{usage-DU4TKVJH.js.map → usage-YBS74UEU.js.map} +1 -1
  46. package/dist/webui/assets/index-BJt1Lf-q.css +1 -0
  47. package/dist/webui/assets/index-Bfhwll2B.js +5224 -0
  48. package/dist/webui/assets/index-Bfhwll2B.js.map +1 -0
  49. package/dist/webui/index.html +15 -0
  50. package/dist/webui/recall-icon.png +0 -0
  51. package/drizzle/0008_premium_red_hulk.sql +44 -0
  52. package/drizzle/meta/0008_snapshot.json +2491 -0
  53. package/drizzle/meta/_journal.json +7 -0
  54. package/package.json +8 -3
  55. package/dist/chunk-A6XEULA4.js +0 -470
  56. package/dist/chunk-A6XEULA4.js.map +0 -1
  57. package/dist/chunk-AJAAK4FK.js.map +0 -1
  58. package/dist/chunk-DSNYEUZW.js +0 -2993
  59. package/dist/chunk-DSNYEUZW.js.map +0 -1
  60. package/dist/chunk-LFWG3CBM.js.map +0 -1
  61. /package/dist/{cleanup-JM3CGHUV.js.map → cleanup-YGHZIYLJ.js.map} +0 -0
  62. /package/dist/{dispatcher-C5S7SYY6.js.map → dispatcher-5MDL3QQT.js.map} +0 -0
  63. /package/dist/{quality-YTQKAEY6.js.map → embeddings-GKNH2E3N.js.map} +0 -0
  64. /package/dist/{tasks-KHLJT7MP.js.map → ingest-JWXX22QX.js.map} +0 -0
@@ -1,2993 +0,0 @@
1
- import {
2
- CONFIDENCE,
3
- RetrievalEvalCase,
4
- RetrievalEvalFile,
5
- activityEventDedupeKey,
6
- bootstrapEmbeddings,
7
- computeHealthScore,
8
- confirmMemory,
9
- createMemory,
10
- demoteMemory,
11
- feedbackWeightedScore,
12
- generateEmbedding,
13
- generateEmbeddings,
14
- getEmbeddingCacheRoot,
15
- getMemory,
16
- getMemoryFeedbackSummaries,
17
- getRepoQualityProfile,
18
- historySnippetDedupeKey,
19
- hybridSearch,
20
- loadEmbeddingConfigFromEnv,
21
- processCorrection,
22
- projectEmbeddingToIndex,
23
- promoteMemory,
24
- queryMemories,
25
- queueMemoryEmbeddingSync,
26
- recordAudit,
27
- recordFeedback,
28
- redactSensitiveValue,
29
- rejectMemory,
30
- resolveProvider,
31
- seedScannedConfidence,
32
- statusFromConfidence,
33
- tagActivitySource
34
- } from "./chunk-LFWG3CBM.js";
35
- import {
36
- activityEvents,
37
- approvalRequests,
38
- auditTrail,
39
- evalSessions,
40
- feedbackEvents,
41
- historyInjections,
42
- historySnippetEmbeddings,
43
- historySnippets,
44
- implicitSignals,
45
- memories,
46
- memoryInjections,
47
- memoryMaintenanceTasks,
48
- policyRules,
49
- schema_exports
50
- } from "./chunk-A6XEULA4.js";
51
-
52
- // src/db/client.ts
53
- import Database from "better-sqlite3";
54
- import { drizzle } from "drizzle-orm/better-sqlite3";
55
- import { migrate } from "drizzle-orm/better-sqlite3/migrator";
56
- import { join, dirname } from "path";
57
- import { mkdirSync, existsSync, rmSync, statSync } from "fs";
58
- import { fileURLToPath } from "url";
59
- var __dirname = dirname(fileURLToPath(import.meta.url));
60
- var RECALL_DB_USER_VERSION = 9;
61
- function getDbPath() {
62
- const dataDir = process.env.RECALL_DATA_DIR ?? join(
63
- process.env.HOME ?? process.env.USERPROFILE ?? ".",
64
- ".recall"
65
- );
66
- mkdirSync(dataDir, { recursive: true });
67
- return join(dataDir, "recall.db");
68
- }
69
- function getMigrationsPath() {
70
- let dir = __dirname;
71
- for (let i = 0; i < 5; i++) {
72
- const candidate = join(dir, "drizzle");
73
- if (existsSync(join(candidate, "meta", "_journal.json"))) {
74
- return candidate;
75
- }
76
- dir = dirname(dir);
77
- }
78
- return join(__dirname, "..", "drizzle");
79
- }
80
- var _sqlite = null;
81
- var _db = null;
82
- var _dbPath = null;
83
- function makeDb(sqlite) {
84
- return drizzle(sqlite, { schema: schema_exports });
85
- }
86
- var STARTUP_WAL_TRUNCATE_BYTES = (() => {
87
- const raw = process.env.RECALL_SQLITE_STARTUP_WAL_TRUNCATE_BYTES;
88
- const parsed = raw ? parseInt(raw, 10) : 32 * 1024 * 1024;
89
- return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
90
- })();
91
- function applyPragmas(sqlite) {
92
- sqlite.pragma("journal_mode = WAL");
93
- sqlite.pragma("foreign_keys = ON");
94
- truncateWalIfLarge(sqlite);
95
- }
96
- function truncateWalIfLarge(sqlite) {
97
- if (STARTUP_WAL_TRUNCATE_BYTES <= 0) return;
98
- try {
99
- const walPath = `${sqlite.name}-wal`;
100
- if (!existsSync(walPath)) return;
101
- if (statSync(walPath).size < STARTUP_WAL_TRUNCATE_BYTES) return;
102
- sqlite.pragma("wal_checkpoint(TRUNCATE)");
103
- } catch {
104
- }
105
- }
106
- function setDbUserVersion(sqlite, version2 = RECALL_DB_USER_VERSION) {
107
- sqlite.pragma(`user_version = ${version2}`);
108
- }
109
- function getDb(dbPath) {
110
- if (!_db) {
111
- const path = dbPath ?? getDbPath();
112
- _sqlite = new Database(path);
113
- applyPragmas(_sqlite);
114
- _db = makeDb(_sqlite);
115
- _dbPath = path;
116
- }
117
- return _db;
118
- }
119
- function initDb(dbPath) {
120
- const db = getDb(dbPath);
121
- migrate(db, { migrationsFolder: getMigrationsPath() });
122
- setDbUserVersion(db.$client);
123
- return db;
124
- }
125
- function closeDb() {
126
- if (_sqlite) {
127
- _sqlite.close();
128
- }
129
- _sqlite = null;
130
- _db = null;
131
- _dbPath = null;
132
- }
133
- function getDbUserVersion(dbPath) {
134
- const path = dbPath ?? getDbPath();
135
- if (!existsSync(path)) return 0;
136
- const sqlite = new Database(path, { readonly: true, fileMustExist: true });
137
- try {
138
- return Number(sqlite.pragma("user_version", { simple: true }) ?? 0);
139
- } finally {
140
- sqlite.close();
141
- }
142
- }
143
- function resetDb(dbPath, options = {}) {
144
- const path = dbPath ?? getDbPath();
145
- if (_dbPath === path) {
146
- closeDb();
147
- }
148
- for (const suffix of ["", "-shm", "-wal"]) {
149
- const candidate = `${path}${suffix}`;
150
- if (existsSync(candidate)) {
151
- rmSync(candidate, { force: true });
152
- }
153
- }
154
- if (options.purgeModels) {
155
- rmSync(getEmbeddingCacheRoot(), { recursive: true, force: true });
156
- }
157
- }
158
-
159
- // src/scanner/repo.ts
160
- import { readFileSync, existsSync as existsSync2 } from "fs";
161
- import { join as join2, basename } from "path";
162
- import { execSync } from "child_process";
163
- import { eq } from "drizzle-orm";
164
-
165
- // src/scanner/signal.ts
166
- var ACTIVE_COMMAND_PATTERNS = [
167
- /^use\b/i,
168
- /^(test|build|lint|dev|start|typecheck|check):\s*`.+`$/i,
169
- /^makefile targets:/i
170
- ];
171
- var CANDIDATE_GOTCHA_PATTERNS = [
172
- /^next\.js project$/i,
173
- /^react project\b/i,
174
- /^vue\.js project$/i,
175
- /^svelte project$/i,
176
- /^server framework:/i,
177
- /^uses alembic\b/i
178
- ];
179
- var ACTIONABLE_RULE_PATTERN = /\b(always|never|must|don't|do not|required|prefer|avoid|use|keep|run|update|add|remove|check|only)\b/i;
180
- function evaluateScannedMemory(input) {
181
- const normalized = normalizeScannedText(input.text);
182
- const lower = normalized.toLowerCase();
183
- if (!normalized || normalized.length < 12) {
184
- return reject(normalized, "too_short");
185
- }
186
- if (lower.startsWith("setup commands from readme:")) {
187
- return reject(normalized, "readme_setup_noise");
188
- }
189
- if (lower === "what we do not build") {
190
- return reject(normalized, "section_heading");
191
- }
192
- if (/^ci:\s*(github actions|gitlab ci)\b/i.test(normalized)) {
193
- return reject(normalized, "generic_ci");
194
- }
195
- if (/^req-[a-z0-9-]+:/i.test(lower)) {
196
- return reject(normalized, "spec_requirement");
197
- }
198
- if (/^[A-Z][A-Za-z0-9 /_-]{1,80}:$/.test(normalized)) {
199
- return reject(normalized, "heading");
200
- }
201
- if (input.source === "config_parse" && lower.startsWith("linting/formatting: python project")) {
202
- return reject(normalized, "generic_tooling");
203
- }
204
- if (input.source === "config_parse" && lower.startsWith("linting/formatting:")) {
205
- return keep(normalized, toCandidateConfidence(input.confidence));
206
- }
207
- if (ACTIVE_COMMAND_PATTERNS.some((pattern) => pattern.test(normalized))) {
208
- return keep(normalized, Math.max(input.confidence, 0.62));
209
- }
210
- if (input.type === "command") {
211
- return keep(normalized, toCandidateConfidence(input.confidence));
212
- }
213
- if (input.type === "gotcha") {
214
- if (CANDIDATE_GOTCHA_PATTERNS.some((pattern) => pattern.test(normalized))) {
215
- return keep(normalized, toCandidateConfidence(input.confidence));
216
- }
217
- return reject(normalized, "generic_gotcha");
218
- }
219
- if (input.type === "rule") {
220
- if (!ACTIONABLE_RULE_PATTERN.test(normalized)) {
221
- return reject(normalized, "non_actionable_rule");
222
- }
223
- return keep(normalized, toCandidateConfidence(input.confidence));
224
- }
225
- return keep(normalized, toCandidateConfidence(input.confidence));
226
- }
227
- function normalizeScannedText(text) {
228
- return text.replace(/\*\*/g, "").split("\n").map((line) => line.replace(/^[-*#>\s]+/, "").replace(/^\d+\.\s+/, "").trim()).filter(Boolean).join("\n").replace(/[ \t]+/g, " ").trim();
229
- }
230
- function toCandidateConfidence(confidence) {
231
- return clamp(confidence, CONFIDENCE.TRANSIENT_MAX + 0.05, CONFIDENCE.ACTIVE_MIN - 0.01);
232
- }
233
- function keep(text, confidence) {
234
- return { action: "keep", text, confidence: clamp(confidence) };
235
- }
236
- function reject(text, reason) {
237
- return { action: "reject", text, confidence: 0, reason };
238
- }
239
- function clamp(n, min = 0, max = 1) {
240
- return Math.max(min, Math.min(max, n));
241
- }
242
-
243
- // src/scanner/repo.ts
244
- function scanRepo(repoPath) {
245
- const repoName = inferRepoName(repoPath);
246
- const candidates = [];
247
- candidates.push(...scanPackageJson(repoPath, repoName));
248
- candidates.push(...scanMakefile(repoPath, repoName));
249
- candidates.push(...scanCIConfig(repoPath, repoName));
250
- candidates.push(...scanInstructionFiles(repoPath, repoName));
251
- candidates.push(...scanLinterConfigs(repoPath, repoName));
252
- candidates.push(...scanReadme(repoPath, repoName));
253
- candidates.push(...scanPythonProject(repoPath, repoName));
254
- return { candidates, repo: repoName };
255
- }
256
- function scanAndStore(db, repoPath) {
257
- const { candidates, repo } = scanRepo(repoPath);
258
- const profile = getRepoQualityProfile(db, repo);
259
- const existing = queryMemories(db, { repo }).filter((mem) => mem.status !== "rejected");
260
- const ids = [];
261
- for (const candidate of candidates) {
262
- const evaluated = evaluateScannedMemory({
263
- text: candidate.text,
264
- type: candidate.type,
265
- source: candidate.source,
266
- confidence: seedScannedConfidence(
267
- candidate.confidence ?? 0.5,
268
- profile
269
- )
270
- });
271
- if (evaluated.action === "reject") {
272
- continue;
273
- }
274
- const seededConfidence = evaluated.confidence;
275
- const normalizedCandidate = {
276
- ...candidate,
277
- text: evaluated.text
278
- };
279
- const duplicate = existing.find(
280
- (mem) => mem.type === normalizedCandidate.type && mem.source === normalizedCandidate.source && mem.text === normalizedCandidate.text
281
- );
282
- if (duplicate) {
283
- if (duplicate.confidence < seededConfidence) {
284
- db.update(memories).set({
285
- confidence: seededConfidence,
286
- status: statusFromConfidence(seededConfidence),
287
- text: normalizedCandidate.text,
288
- updated_at: (/* @__PURE__ */ new Date()).toISOString()
289
- }).where(eq(memories.id, duplicate.id)).run();
290
- queueMemoryEmbeddingSync(db, duplicate.id);
291
- }
292
- ids.push(duplicate.id);
293
- continue;
294
- }
295
- normalizedCandidate.confidence = seededConfidence;
296
- const id = createMemory(db, normalizedCandidate);
297
- ids.push(id);
298
- existing.push({
299
- ...queryMemories(db, { repo }).find((mem) => mem.id === id),
300
- confidence: seededConfidence,
301
- status: statusFromConfidence(seededConfidence)
302
- });
303
- }
304
- return ids;
305
- }
306
- function scanPackageJson(repoPath, repo) {
307
- const pkgPath = join2(repoPath, "package.json");
308
- if (!existsSync2(pkgPath)) return [];
309
- const results = [];
310
- try {
311
- const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
312
- if (pkg.packageManager) {
313
- const pm = pkg.packageManager.split("@")[0];
314
- results.push(makeCommand(
315
- `Use ${pm} as the package manager (lockfile: ${pm === "pnpm" ? "pnpm-lock.yaml" : pm === "yarn" ? "yarn.lock" : "package-lock.json"})`,
316
- repo,
317
- "package.json"
318
- ));
319
- } else if (existsSync2(join2(repoPath, "pnpm-lock.yaml"))) {
320
- results.push(makeCommand("Use pnpm as the package manager", repo, "package.json"));
321
- } else if (existsSync2(join2(repoPath, "yarn.lock"))) {
322
- results.push(makeCommand("Use yarn as the package manager", repo, "package.json"));
323
- } else if (existsSync2(join2(repoPath, "bun.lockb")) || existsSync2(join2(repoPath, "bun.lock"))) {
324
- results.push(makeCommand("Use bun as the package manager", repo, "package.json"));
325
- }
326
- const scripts = pkg.scripts ?? {};
327
- const importantScripts = ["test", "build", "lint", "dev", "start", "typecheck", "check"];
328
- for (const name of importantScripts) {
329
- if (scripts[name]) {
330
- results.push({
331
- type: "command",
332
- text: `${name}: \`${scripts[name]}\``,
333
- scope: "repo",
334
- repo,
335
- source: "config_parse",
336
- confidence: 0.65,
337
- evidence: [
338
- { type: "repo_scan", file: "package.json", timestamp: now() }
339
- ]
340
- });
341
- }
342
- }
343
- const allDeps = {
344
- ...pkg.dependencies,
345
- ...pkg.devDependencies
346
- };
347
- if (allDeps.next) results.push(makeGotcha("Next.js project", repo, "package.json"));
348
- if (allDeps.react && !allDeps.next) results.push(makeGotcha("React project (no Next.js)", repo, "package.json"));
349
- if (allDeps.vue) results.push(makeGotcha("Vue.js project", repo, "package.json"));
350
- if (allDeps.svelte) results.push(makeGotcha("Svelte project", repo, "package.json"));
351
- if (allDeps.express || allDeps.fastify || allDeps.hono)
352
- results.push(makeGotcha(`Server framework: ${allDeps.express ? "Express" : allDeps.fastify ? "Fastify" : "Hono"}`, repo, "package.json"));
353
- } catch {
354
- }
355
- return results;
356
- }
357
- function scanMakefile(repoPath, repo) {
358
- const mkPath = join2(repoPath, "Makefile");
359
- if (!existsSync2(mkPath)) return [];
360
- const results = [];
361
- try {
362
- const content = readFileSync(mkPath, "utf-8");
363
- const targets = content.match(/^([a-zA-Z_-]+):/gm);
364
- if (targets) {
365
- const key = targets.map((t) => t.replace(":", "")).filter(
366
- (t) => ["test", "build", "lint", "dev", "run", "deploy", "install", "setup", "clean"].includes(t)
367
- );
368
- if (key.length > 0) {
369
- results.push({
370
- type: "command",
371
- text: `Makefile targets: ${key.map((t) => `\`make ${t}\``).join(", ")}`,
372
- scope: "repo",
373
- repo,
374
- source: "config_parse",
375
- confidence: 0.65,
376
- evidence: [{ type: "repo_scan", file: "Makefile", timestamp: now() }]
377
- });
378
- }
379
- }
380
- } catch {
381
- }
382
- return results;
383
- }
384
- function scanCIConfig(repoPath, repo) {
385
- const results = [];
386
- const ghDir = join2(repoPath, ".github", "workflows");
387
- if (existsSync2(ghDir)) {
388
- results.push({
389
- type: "gotcha",
390
- text: "CI: GitHub Actions (check .github/workflows/ for pipeline config)",
391
- scope: "repo",
392
- repo,
393
- source: "repo_scan",
394
- confidence: 0.6,
395
- evidence: [{ type: "repo_scan", file: ".github/workflows/", timestamp: now() }]
396
- });
397
- }
398
- if (existsSync2(join2(repoPath, ".gitlab-ci.yml"))) {
399
- results.push(makeGotcha("CI: GitLab CI", repo, ".gitlab-ci.yml"));
400
- }
401
- return results;
402
- }
403
- function scanInstructionFiles(repoPath, repo) {
404
- const results = [];
405
- const instructionFiles = [
406
- "CLAUDE.md",
407
- "AGENTS.md",
408
- ".github/copilot-instructions.md",
409
- ".cursorrules"
410
- ];
411
- for (const file of instructionFiles) {
412
- const fPath = join2(repoPath, file);
413
- if (!existsSync2(fPath)) continue;
414
- try {
415
- const content = readFileSync(fPath, "utf-8");
416
- const rules = content.split("\n").filter(
417
- (line) => /\b(always|never|must|don't|do not|required|forbidden)\b/i.test(line)
418
- ).map((l) => l.replace(/^[-*#>\s]+/, "").trim()).filter((l) => l.length > 10 && l.length < 200);
419
- for (const rule of rules.slice(0, 5)) {
420
- results.push({
421
- type: "rule",
422
- text: rule,
423
- scope: "repo",
424
- repo,
425
- source: "repo_scan",
426
- confidence: 0.7,
427
- // high — explicit instruction files
428
- evidence: [{ type: "repo_scan", file, timestamp: now() }]
429
- });
430
- }
431
- } catch {
432
- }
433
- }
434
- return results;
435
- }
436
- function scanLinterConfigs(repoPath, repo) {
437
- const results = [];
438
- const configs = [
439
- [".eslintrc.json", "ESLint"],
440
- [".eslintrc.js", "ESLint"],
441
- [".eslintrc.cjs", "ESLint"],
442
- ["eslint.config.js", "ESLint (flat config)"],
443
- ["eslint.config.mjs", "ESLint (flat config)"],
444
- [".prettierrc", "Prettier"],
445
- ["prettier.config.js", "Prettier"],
446
- ["biome.json", "Biome"],
447
- ["biome.jsonc", "Biome"],
448
- [".rustfmt.toml", "rustfmt"],
449
- ["ruff.toml", "Ruff"],
450
- ["pyproject.toml", "Python project (pyproject.toml)"]
451
- ];
452
- const found = [];
453
- for (const [file, name] of configs) {
454
- if (existsSync2(join2(repoPath, file))) {
455
- found.push(name);
456
- }
457
- }
458
- if (found.length > 0) {
459
- results.push({
460
- type: "rule",
461
- text: `Linting/formatting: ${[...new Set(found)].join(", ")}`,
462
- scope: "repo",
463
- repo,
464
- source: "config_parse",
465
- confidence: 0.65,
466
- evidence: [{ type: "repo_scan", file: "config files", timestamp: now() }]
467
- });
468
- }
469
- return results;
470
- }
471
- function scanReadme(repoPath, repo) {
472
- const results = [];
473
- const readmePath = join2(repoPath, "README.md");
474
- if (!existsSync2(readmePath)) return [];
475
- try {
476
- const content = readFileSync(readmePath, "utf-8");
477
- const setupMatch = content.match(
478
- /^##\s*(setup|install|getting.started|quick.start|development)\s*\n([\s\S]*?)(?=^##\s|\z)/im
479
- );
480
- if (setupMatch) {
481
- const codeBlocks = setupMatch[2].match(/```(?:sh|bash|shell|zsh)?\n([\s\S]*?)```/g);
482
- if (codeBlocks && codeBlocks.length > 0) {
483
- const commands = codeBlocks.map((b) => b.replace(/```(?:sh|bash|shell|zsh)?\n?/, "").replace(/```$/, "").trim()).join("\n");
484
- if (commands.length < 500) {
485
- results.push({
486
- type: "command",
487
- text: `Setup commands from README:
488
- ${commands}`,
489
- scope: "repo",
490
- repo,
491
- source: "repo_scan",
492
- confidence: 0.5,
493
- evidence: [{ type: "repo_scan", file: "README.md", timestamp: now() }]
494
- });
495
- }
496
- }
497
- }
498
- } catch {
499
- }
500
- return results;
501
- }
502
- function scanPythonProject(repoPath, repo) {
503
- const results = [];
504
- if (existsSync2(join2(repoPath, "pyproject.toml"))) {
505
- if (existsSync2(join2(repoPath, "uv.lock"))) {
506
- results.push(makeCommand("Use `uv` for Python dependency management", repo, "uv.lock"));
507
- } else if (existsSync2(join2(repoPath, "poetry.lock"))) {
508
- results.push(makeCommand("Use `poetry` for Python dependency management", repo, "poetry.lock"));
509
- }
510
- if (existsSync2(join2(repoPath, "alembic.ini")) || existsSync2(join2(repoPath, "alembic"))) {
511
- results.push(makeGotcha("Uses Alembic for database migrations", repo, "alembic.ini"));
512
- }
513
- }
514
- return results;
515
- }
516
- function now() {
517
- return (/* @__PURE__ */ new Date()).toISOString();
518
- }
519
- function inferRepoName(repoPath) {
520
- try {
521
- const remote = execSync("git remote get-url origin", {
522
- cwd: repoPath,
523
- encoding: "utf-8",
524
- stdio: ["pipe", "pipe", "pipe"]
525
- }).trim();
526
- const repo = extractRepoSlugFromRemote(remote);
527
- if (repo) return repo;
528
- } catch {
529
- }
530
- return basename(repoPath);
531
- }
532
- function extractRepoSlugFromRemote(remote) {
533
- const trimmed = remote.trim().replace(/\.git$/, "");
534
- const parts = trimmed.split(/[:/]/).filter(Boolean);
535
- if (parts.length < 2) return null;
536
- return `${parts.at(-2)}/${parts.at(-1)}`;
537
- }
538
- function makeCommand(text, repo, file) {
539
- return {
540
- type: "command",
541
- text,
542
- scope: "repo",
543
- repo,
544
- source: "config_parse",
545
- confidence: 0.65,
546
- evidence: [{ type: "repo_scan", file, timestamp: now() }]
547
- };
548
- }
549
- function makeGotcha(text, repo, file) {
550
- return {
551
- type: "gotcha",
552
- text,
553
- scope: "repo",
554
- repo,
555
- source: "repo_scan",
556
- confidence: 0.6,
557
- evidence: [{ type: "repo_scan", file, timestamp: now() }]
558
- };
559
- }
560
-
561
- // src/history/snippets.ts
562
- import { desc, eq as eq2, and } from "drizzle-orm";
563
- import { randomUUID } from "crypto";
564
- function createHistorySnippet(db, input) {
565
- const dedupeKey = historySnippetDedupeKey(input);
566
- const existing = db.select().from(historySnippets).where(eq2(historySnippets.dedupe_key, dedupeKey)).get();
567
- if (existing) return existing.id;
568
- const id = randomUUID();
569
- const now2 = (/* @__PURE__ */ new Date()).toISOString();
570
- db.insert(historySnippets).values({
571
- id,
572
- repo: input.repo ?? null,
573
- session_id: input.session_id ?? null,
574
- kind: input.kind,
575
- text: input.text,
576
- dedupe_key: dedupeKey,
577
- source_activity_ids: input.source_activity_ids ?? [],
578
- created_at: now2,
579
- updated_at: now2
580
- }).run();
581
- return id;
582
- }
583
- function getHistorySnippet(db, id) {
584
- const row = db.select().from(historySnippets).where(eq2(historySnippets.id, id)).get();
585
- return row ? rowToHistorySnippet(row) : void 0;
586
- }
587
- function listHistorySnippets(db, query = {}) {
588
- const conditions = [];
589
- if (query.repo) conditions.push(eq2(historySnippets.repo, query.repo));
590
- if (query.session_id) conditions.push(eq2(historySnippets.session_id, query.session_id));
591
- if (query.kind) conditions.push(eq2(historySnippets.kind, query.kind));
592
- let stmt = db.select().from(historySnippets).$dynamic();
593
- if (conditions.length > 0) {
594
- stmt = stmt.where(and(...conditions));
595
- }
596
- stmt = stmt.orderBy(desc(historySnippets.updated_at));
597
- if (query.limit != null) {
598
- stmt = stmt.limit(query.limit);
599
- }
600
- return stmt.all().map(rowToHistorySnippet);
601
- }
602
- function findHistorySnippetBySession(db, sessionId, kind = "session_summary") {
603
- const row = db.select().from(historySnippets).where(and(
604
- eq2(historySnippets.session_id, sessionId),
605
- eq2(historySnippets.kind, kind)
606
- )).get();
607
- return row ? rowToHistorySnippet(row) : void 0;
608
- }
609
- function findHistorySnippetByRepoKind(db, repo, kind) {
610
- const row = db.select().from(historySnippets).where(and(
611
- eq2(historySnippets.repo, repo),
612
- eq2(historySnippets.kind, kind)
613
- )).get();
614
- return row ? rowToHistorySnippet(row) : void 0;
615
- }
616
- function updateHistorySnippet(db, id, updates) {
617
- const current = getHistorySnippet(db, id);
618
- if (!current) return;
619
- const nextText = updates.text ?? current.text;
620
- const dedupeKey = historySnippetDedupeKey({
621
- repo: current.repo,
622
- session_id: current.session_id,
623
- kind: current.kind,
624
- text: nextText
625
- });
626
- const collision = db.select().from(historySnippets).where(eq2(historySnippets.dedupe_key, dedupeKey)).get();
627
- if (collision && collision.id !== id) return;
628
- db.update(historySnippets).set({
629
- ...updates.text != null ? { text: updates.text } : {},
630
- dedupe_key: dedupeKey,
631
- ...updates.source_activity_ids ? { source_activity_ids: updates.source_activity_ids } : {},
632
- updated_at: (/* @__PURE__ */ new Date()).toISOString()
633
- }).where(eq2(historySnippets.id, id)).run();
634
- }
635
- function rowToHistorySnippet(row) {
636
- const sourceActivityIds = typeof row.source_activity_ids === "string" ? JSON.parse(row.source_activity_ids) : Array.isArray(row.source_activity_ids) ? row.source_activity_ids : [];
637
- return {
638
- id: row.id,
639
- repo: row.repo,
640
- session_id: row.session_id,
641
- kind: row.kind,
642
- text: row.text,
643
- source_activity_ids: sourceActivityIds,
644
- created_at: row.created_at,
645
- updated_at: row.updated_at
646
- };
647
- }
648
-
649
- // src/history/retrieval.ts
650
- import { createHash } from "crypto";
651
- import { eq as eq5 } from "drizzle-orm";
652
-
653
- // src/vector/sqlite-vec-history.ts
654
- import * as sqliteVec from "sqlite-vec";
655
- import { eq as eq3 } from "drizzle-orm";
656
- var VEC_HISTORY_INDEX = "vec_history_index";
657
- var loadedClients = /* @__PURE__ */ new WeakSet();
658
- function getSqlite(db) {
659
- return db.$client;
660
- }
661
- function hasHistoryVecIndex(db) {
662
- return Boolean(
663
- getSqlite(db).prepare("select 1 from sqlite_master where type = 'table' and name = ?").get(VEC_HISTORY_INDEX)
664
- );
665
- }
666
- function ensureLoaded(db) {
667
- const sqlite = getSqlite(db);
668
- if (loadedClients.has(sqlite)) return;
669
- sqliteVec.load(sqlite);
670
- loadedClients.add(sqlite);
671
- }
672
- function getHistoryVecDimension(rows) {
673
- const dimensions = [...new Set(rows.map((row) => row.index_dimensions))];
674
- if (dimensions.length === 0) return null;
675
- if (dimensions.length > 1) {
676
- throw new Error(
677
- `sqlite-vec history index rebuild refused mixed history embedding dimensions: ${dimensions.join(", ")}.`
678
- );
679
- }
680
- return dimensions[0];
681
- }
682
- function ensureHistoryVecIndex(db, dimensions) {
683
- ensureLoaded(db);
684
- const sqlite = getSqlite(db);
685
- const existing = sqlite.prepare("select sql from sqlite_master where type = 'table' and name = ?").get(VEC_HISTORY_INDEX);
686
- const expectedDimension = `float[${dimensions}]`;
687
- if (existing?.sql && !existing.sql.includes(expectedDimension)) {
688
- throw new Error(
689
- `sqlite-vec history index dimension mismatch. Expected ${expectedDimension}. Run history index rebuild.`
690
- );
691
- }
692
- sqlite.exec(`
693
- create virtual table if not exists ${VEC_HISTORY_INDEX} using vec0(
694
- embedding float[${dimensions}] distance_metric=cosine,
695
- snippet_id text,
696
- repo text,
697
- kind text
698
- );
699
- `);
700
- }
701
- function removeHistoryVecRow(db, snippetId) {
702
- ensureLoaded(db);
703
- if (!hasHistoryVecIndex(db)) return;
704
- getSqlite(db).prepare(`delete from ${VEC_HISTORY_INDEX} where snippet_id = ?`).run(snippetId);
705
- }
706
- function rebuildHistoryVecIndex(db, config, options = {}) {
707
- const rows = db.select({
708
- id: historySnippets.id,
709
- repo: historySnippets.repo,
710
- kind: historySnippets.kind,
711
- index_dimensions: historySnippetEmbeddings.index_dimensions,
712
- embedding: historySnippetEmbeddings.embedding
713
- }).from(historySnippets).innerJoin(historySnippetEmbeddings, eq3(historySnippetEmbeddings.snippet_id, historySnippets.id)).all().filter((row) => !options.repo || row.repo === options.repo);
714
- const storedDimension = getHistoryVecDimension(rows);
715
- const targetDimension = storedDimension ?? config.dimensions;
716
- const sqlite = getSqlite(db);
717
- if (options.repo) {
718
- if (rows.length > 0) {
719
- ensureHistoryVecIndex(db, targetDimension);
720
- }
721
- if (!hasHistoryVecIndex(db)) return 0;
722
- sqlite.prepare(`delete from ${VEC_HISTORY_INDEX} where repo = ?`).run(options.repo);
723
- if (rows.length === 0) return 0;
724
- } else {
725
- sqlite.exec(`drop table if exists ${VEC_HISTORY_INDEX};`);
726
- ensureHistoryVecIndex(db, targetDimension);
727
- }
728
- const stmt = getSqlite(db).prepare(`
729
- insert into ${VEC_HISTORY_INDEX} (
730
- embedding,
731
- snippet_id,
732
- repo,
733
- kind
734
- ) values (?, ?, ?, ?)
735
- `);
736
- const insertMany = getSqlite(db).transaction((batch) => {
737
- for (const row of batch) {
738
- stmt.run(projectIndexBuffer(row.embedding, row.index_dimensions), row.id, row.repo ?? "", row.kind);
739
- }
740
- });
741
- insertMany(rows);
742
- return rows.length;
743
- }
744
- function projectIndexBuffer(buffer, indexDimensions) {
745
- const embedding = new Float32Array(
746
- buffer.buffer,
747
- buffer.byteOffset,
748
- buffer.byteLength / Float32Array.BYTES_PER_ELEMENT
749
- );
750
- if (embedding.length === indexDimensions) {
751
- return buffer;
752
- }
753
- if (embedding.length < indexDimensions) {
754
- throw new Error(`Canonical history embedding width ${embedding.length} is smaller than index width ${indexDimensions}.`);
755
- }
756
- const sliced = embedding.slice(0, indexDimensions);
757
- let norm = 0;
758
- for (const value of sliced) norm += value * value;
759
- const scale = Math.sqrt(norm) || 1;
760
- for (let i = 0; i < sliced.length; i++) {
761
- sliced[i] /= scale;
762
- }
763
- return Buffer.from(sliced.buffer, sliced.byteOffset, sliced.byteLength);
764
- }
765
- function verifyHistoryVecIndex(db, options = {}) {
766
- ensureLoaded(db);
767
- const sqlite = getSqlite(db);
768
- const exists = sqlite.prepare("select 1 from sqlite_master where type = 'table' and name = ?").get(VEC_HISTORY_INDEX);
769
- const expected = db.select({
770
- snippet_id: historySnippetEmbeddings.snippet_id,
771
- repo: historySnippets.repo
772
- }).from(historySnippetEmbeddings).innerJoin(historySnippets, eq3(historySnippets.id, historySnippetEmbeddings.snippet_id)).all().filter((row) => !options.repo || row.repo === options.repo).length;
773
- let indexed = 0;
774
- if (exists) {
775
- if (options.repo) {
776
- indexed = sqlite.prepare(`select count(*) as count from ${VEC_HISTORY_INDEX} where repo = ?`).get(options.repo).count;
777
- } else {
778
- indexed = sqlite.prepare(`select count(*) as count from ${VEC_HISTORY_INDEX}`).get().count;
779
- }
780
- }
781
- return { expected, indexed, drift: expected - indexed };
782
- }
783
- function searchHistoryVecIndex(db, queryEmbedding, options = {}) {
784
- ensureLoaded(db);
785
- const sqlite = getSqlite(db);
786
- const exists = sqlite.prepare("select 1 from sqlite_master where type = 'table' and name = ?").get(VEC_HISTORY_INDEX);
787
- if (!exists) return [];
788
- const limit = options.limit ?? 10;
789
- if (options.repo) {
790
- return sqlite.prepare(`
791
- select snippet_id, distance
792
- from ${VEC_HISTORY_INDEX}
793
- where embedding match ?
794
- and k = ?
795
- and repo = ?
796
- order by distance
797
- `).all(queryEmbedding, limit, options.repo);
798
- }
799
- return sqlite.prepare(`
800
- select snippet_id, distance
801
- from ${VEC_HISTORY_INDEX}
802
- where embedding match ?
803
- and k = ?
804
- order by distance
805
- `).all(queryEmbedding, limit);
806
- }
807
-
808
- // src/vector/sqlite-fts-history.ts
809
- import { eq as eq4 } from "drizzle-orm";
810
- var FTS_HISTORY_INDEX = "fts_history_index";
811
- function getSqlite2(db) {
812
- return db.$client;
813
- }
814
- function ensureHistoryFtsIndex(db) {
815
- getSqlite2(db).exec(`
816
- create virtual table if not exists ${FTS_HISTORY_INDEX} using fts5(
817
- snippet_id UNINDEXED,
818
- text,
819
- repo UNINDEXED,
820
- kind UNINDEXED
821
- );
822
- `);
823
- }
824
- function removeHistoryFtsRow(db, snippetId) {
825
- const sqlite = getSqlite2(db);
826
- const exists = sqlite.prepare("select 1 from sqlite_master where type = 'table' and name = ?").get(FTS_HISTORY_INDEX);
827
- if (!exists) return;
828
- sqlite.prepare(`delete from ${FTS_HISTORY_INDEX} where snippet_id = ?`).run(snippetId);
829
- }
830
- function upsertHistoryFtsRow(db, snippet) {
831
- ensureHistoryFtsIndex(db);
832
- const sqlite = getSqlite2(db);
833
- sqlite.prepare(`delete from ${FTS_HISTORY_INDEX} where snippet_id = ?`).run(snippet.id);
834
- sqlite.prepare(`
835
- insert into ${FTS_HISTORY_INDEX} (
836
- snippet_id,
837
- text,
838
- repo,
839
- kind
840
- ) values (?, ?, ?, ?)
841
- `).run(snippet.id, snippet.text, snippet.repo ?? "", snippet.kind);
842
- }
843
- function syncHistoryFtsIndex(db, snippetId) {
844
- const snippet = db.select().from(historySnippets).where(eq4(historySnippets.id, snippetId)).get();
845
- if (!snippet) {
846
- removeHistoryFtsRow(db, snippetId);
847
- return "removed";
848
- }
849
- upsertHistoryFtsRow(db, snippet);
850
- return "stored";
851
- }
852
- function rebuildHistoryFtsIndex(db, options = {}) {
853
- const sqlite = getSqlite2(db);
854
- if (options.repo) {
855
- ensureHistoryFtsIndex(db);
856
- sqlite.prepare(`delete from ${FTS_HISTORY_INDEX} where repo = ?`).run(options.repo);
857
- } else {
858
- sqlite.exec(`drop table if exists ${FTS_HISTORY_INDEX};`);
859
- ensureHistoryFtsIndex(db);
860
- }
861
- const rows = db.select().from(historySnippets).all().filter((row) => !options.repo || row.repo === options.repo);
862
- const stmt = sqlite.prepare(`
863
- insert into ${FTS_HISTORY_INDEX} (
864
- snippet_id,
865
- text,
866
- repo,
867
- kind
868
- ) values (?, ?, ?, ?)
869
- `);
870
- const insertMany = sqlite.transaction((batch) => {
871
- for (const row of batch) {
872
- stmt.run(row.id, row.text, row.repo ?? "", row.kind);
873
- }
874
- });
875
- insertMany(rows);
876
- return rows.length;
877
- }
878
- function verifyHistoryFtsIndex(db, options = {}) {
879
- const sqlite = getSqlite2(db);
880
- const exists = sqlite.prepare("select 1 from sqlite_master where type = 'table' and name = ?").get(FTS_HISTORY_INDEX);
881
- const expected = db.select().from(historySnippets).all().filter((row) => !options.repo || row.repo === options.repo).length;
882
- let indexed = 0;
883
- if (exists) {
884
- if (options.repo) {
885
- indexed = sqlite.prepare(`select count(*) as count from ${FTS_HISTORY_INDEX} where repo = ?`).get(options.repo).count;
886
- } else {
887
- indexed = sqlite.prepare(`select count(*) as count from ${FTS_HISTORY_INDEX}`).get().count;
888
- }
889
- }
890
- return { expected, indexed, drift: expected - indexed };
891
- }
892
- function buildFtsQuery(query) {
893
- const tokens = query.match(/[A-Za-z0-9_.:/-]+/g)?.map((token) => token.replace(/"/g, '""')).filter(Boolean) ?? [];
894
- if (tokens.length === 0) return null;
895
- return tokens.map((token) => `"${token}"`).join(" ");
896
- }
897
- function searchHistoryFtsIndex(db, query, options = {}) {
898
- ensureHistoryFtsIndex(db);
899
- const ftsQuery = buildFtsQuery(query);
900
- if (!ftsQuery) return [];
901
- const sqlite = getSqlite2(db);
902
- const limit = options.limit ?? 10;
903
- if (options.repo) {
904
- return sqlite.prepare(`
905
- select snippet_id, bm25(${FTS_HISTORY_INDEX}) as lexical_rank
906
- from ${FTS_HISTORY_INDEX}
907
- where ${FTS_HISTORY_INDEX} match ?
908
- and repo = ?
909
- order by lexical_rank
910
- limit ?
911
- `).all(ftsQuery, options.repo, limit);
912
- }
913
- return sqlite.prepare(`
914
- select snippet_id, bm25(${FTS_HISTORY_INDEX}) as lexical_rank
915
- from ${FTS_HISTORY_INDEX}
916
- where ${FTS_HISTORY_INDEX} match ?
917
- order by lexical_rank
918
- limit ?
919
- `).all(ftsQuery, limit);
920
- }
921
-
922
- // src/history/retrieval.ts
923
- function hashText(text) {
924
- return createHash("sha256").update(text).digest("hex");
925
- }
926
- function version(config) {
927
- return config.version || `${config.provider}:${config.model}:${config.dimensions}`;
928
- }
929
- function rowNeedsRefresh(row, existing, config) {
930
- const metadata = resolveProvider(config).metadata();
931
- if (!existing) return true;
932
- return existing.model !== config.model || existing.embedding_dimensions !== metadata.canonical_dimensions || existing.index_dimensions !== metadata.index_dimensions || existing.version !== version(config) || existing.content_hash !== hashText(row.text);
933
- }
934
- function rowToHistorySnippet2(row) {
935
- const sourceActivityIds = typeof row.source_activity_ids === "string" ? JSON.parse(row.source_activity_ids) : Array.isArray(row.source_activity_ids) ? row.source_activity_ids : [];
936
- return {
937
- id: row.id,
938
- repo: row.repo,
939
- session_id: row.session_id,
940
- kind: row.kind,
941
- text: row.text,
942
- source_activity_ids: sourceActivityIds,
943
- created_at: row.created_at,
944
- updated_at: row.updated_at
945
- };
946
- }
947
- function storeHistoryEmbedding(db, snippetId, text, embedding, config) {
948
- const now2 = (/* @__PURE__ */ new Date()).toISOString();
949
- const metadata = resolveProvider(config).metadata();
950
- const payload = {
951
- snippet_id: snippetId,
952
- model: config.model,
953
- embedding_dimensions: metadata.canonical_dimensions,
954
- index_dimensions: metadata.index_dimensions,
955
- version: version(config),
956
- content_hash: hashText(text),
957
- updated_at: now2,
958
- embedding: Buffer.from(embedding.buffer, embedding.byteOffset, embedding.byteLength)
959
- };
960
- db.insert(historySnippetEmbeddings).values(payload).onConflictDoUpdate({
961
- target: historySnippetEmbeddings.snippet_id,
962
- set: {
963
- model: payload.model,
964
- embedding_dimensions: payload.embedding_dimensions,
965
- index_dimensions: payload.index_dimensions,
966
- version: payload.version,
967
- content_hash: payload.content_hash,
968
- updated_at: payload.updated_at,
969
- embedding: payload.embedding
970
- }
971
- }).run();
972
- }
973
- async function bootstrapHistoryEmbeddings(db, config, options = {}) {
974
- const rows = db.select().from(historySnippets).all().filter((row) => !options.repo || row.repo === options.repo);
975
- const existing = new Map(
976
- db.select().from(historySnippetEmbeddings).all().map((row) => [row.snippet_id, row])
977
- );
978
- const pending = rows.filter((row) => rowNeedsRefresh(row, existing.get(row.id), config));
979
- for (const row of rows) {
980
- syncHistoryFtsIndex(db, row.id);
981
- }
982
- const BATCH_SIZE = 100;
983
- let total = 0;
984
- for (let i = 0; i < pending.length; i += BATCH_SIZE) {
985
- const batch = pending.slice(i, i + BATCH_SIZE);
986
- const embeddings = await generateEmbeddings(batch.map((row) => row.text), config, "document");
987
- for (let j = 0; j < batch.length; j++) {
988
- storeHistoryEmbedding(db, batch[j].id, batch[j].text, embeddings[j], config);
989
- total++;
990
- }
991
- }
992
- rebuildHistoryFtsIndex(db, options);
993
- rebuildHistoryVecIndex(db, config, options);
994
- return total;
995
- }
996
- function verifyHistoryEmbeddings(db, config, options = {}) {
997
- const rows = db.select().from(historySnippets).all().filter((row) => !options.repo || row.repo === options.repo);
998
- const embeddings = db.select().from(historySnippetEmbeddings).all();
999
- const byId = new Map(embeddings.map((row) => [row.snippet_id, row]));
1000
- let eligible = 0;
1001
- let stale = 0;
1002
- for (const row of rows) {
1003
- eligible++;
1004
- if (rowNeedsRefresh(row, byId.get(row.id), config)) stale++;
1005
- }
1006
- const vec = verifyHistoryVecIndex(db, options);
1007
- const fts = verifyHistoryFtsIndex(db, options);
1008
- return {
1009
- eligible,
1010
- stored: embeddings.filter((row) => {
1011
- if (!options.repo) return true;
1012
- const snippet = rows.find((item) => item.id === row.snippet_id);
1013
- return snippet?.repo === options.repo;
1014
- }).length,
1015
- stale,
1016
- indexed: vec.indexed,
1017
- index_drift: vec.drift,
1018
- lexical_indexed: fts.indexed,
1019
- lexical_drift: fts.drift
1020
- };
1021
- }
1022
- function lexicalRankToScore(rank, position) {
1023
- const safeRank = Number.isFinite(rank) ? Math.abs(rank) : position + 1;
1024
- return 1 / (1 + safeRank + position);
1025
- }
1026
- async function searchHistorySnippets(db, query, options = {}) {
1027
- const limit = options.limit ?? 10;
1028
- const lexicalMatches = searchHistoryFtsIndex(db, query, {
1029
- repo: options.repo,
1030
- limit: Math.max(limit * 2, 20)
1031
- });
1032
- const config = loadEmbeddingConfigFromEnv();
1033
- const vectorMatches = config ? searchHistoryVecIndex(db, projectEmbeddingToIndex(
1034
- await generateEmbedding(query, config, "query"),
1035
- resolveProvider(config).metadata().index_dimensions
1036
- ), {
1037
- repo: options.repo,
1038
- limit: Math.max(limit * 2, 20)
1039
- }) : [];
1040
- const rowsById = new Map(
1041
- db.select().from(historySnippets).all().map((row) => [row.id, row])
1042
- );
1043
- const merged = /* @__PURE__ */ new Map();
1044
- for (let i = 0; i < lexicalMatches.length; i++) {
1045
- const match = lexicalMatches[i];
1046
- const row = rowsById.get(match.snippet_id);
1047
- if (!row) continue;
1048
- const lexicalScore = lexicalRankToScore(match.lexical_rank, i);
1049
- merged.set(match.snippet_id, {
1050
- snippet: rowToHistorySnippet2(row),
1051
- score: lexicalScore * 0.35,
1052
- similarity: 0,
1053
- lexical_score: lexicalScore
1054
- });
1055
- }
1056
- for (const match of vectorMatches) {
1057
- const row = rowsById.get(match.snippet_id);
1058
- if (!row) continue;
1059
- const similarity = Math.max(0, 1 - match.distance);
1060
- const existing = merged.get(match.snippet_id);
1061
- if (existing) {
1062
- existing.similarity = similarity;
1063
- existing.score = similarity * 0.65 + existing.lexical_score * 0.35;
1064
- } else {
1065
- merged.set(match.snippet_id, {
1066
- snippet: rowToHistorySnippet2(row),
1067
- score: similarity * 0.65,
1068
- similarity,
1069
- lexical_score: 0
1070
- });
1071
- }
1072
- }
1073
- return [...merged.values()].sort((a, b) => b.score - a.score).slice(0, limit);
1074
- }
1075
-
1076
- // src/models/memory-injections.ts
1077
- import { and as and2, asc, eq as eq6, gt, isNull } from "drizzle-orm";
1078
- import { randomUUID as randomUUID2 } from "crypto";
1079
- function recordMemoryInjections(db, input) {
1080
- if (!input.session_id || input.memory_ids.length === 0) return 0;
1081
- const injectedAt = (/* @__PURE__ */ new Date()).toISOString();
1082
- let inserted = 0;
1083
- for (const memoryId of input.memory_ids) {
1084
- const result = db.insert(memoryInjections).values({
1085
- id: randomUUID2(),
1086
- memory_id: memoryId,
1087
- session_id: input.session_id,
1088
- repo: input.repo ?? null,
1089
- injected_at: injectedAt,
1090
- outcome: null,
1091
- outcome_at: null
1092
- }).onConflictDoNothing({
1093
- target: [memoryInjections.memory_id, memoryInjections.session_id]
1094
- }).run();
1095
- inserted += Number(result.changes ?? 0);
1096
- }
1097
- return inserted;
1098
- }
1099
- function listInjectedMemoryIdsForSession(db, sessionId) {
1100
- const rows = db.select({ memory_id: memoryInjections.memory_id }).from(memoryInjections).where(eq6(memoryInjections.session_id, sessionId)).all();
1101
- return new Set(rows.map((row) => row.memory_id));
1102
- }
1103
- function listPendingMemoryInjections(db, sessionId) {
1104
- const rows = db.select().from(memoryInjections).where(and2(
1105
- eq6(memoryInjections.session_id, sessionId),
1106
- isNull(memoryInjections.outcome)
1107
- )).orderBy(asc(memoryInjections.injected_at)).all();
1108
- return rows.map((row) => ({
1109
- ...rowToMemoryInjection(row),
1110
- memory: getMemory(db, row.memory_id) ?? null
1111
- }));
1112
- }
1113
- function resolveMemoryInjectionOutcome(db, memoryId, sessionId, outcome) {
1114
- const outcomeAt = (/* @__PURE__ */ new Date()).toISOString();
1115
- const result = db.update(memoryInjections).set({
1116
- outcome,
1117
- outcome_at: outcomeAt
1118
- }).where(and2(
1119
- eq6(memoryInjections.memory_id, memoryId),
1120
- eq6(memoryInjections.session_id, sessionId),
1121
- isNull(memoryInjections.outcome)
1122
- )).run();
1123
- return Number(result.changes ?? 0) > 0;
1124
- }
1125
- function pathMatchesMemory(mem, targetPath) {
1126
- if (!targetPath) return mem.scope === "repo" || mem.scope === "team";
1127
- if (mem.scope === "repo" || mem.scope === "team") return true;
1128
- if (!mem.path_scope) return true;
1129
- const pattern = mem.path_scope;
1130
- if (pattern.endsWith("**")) {
1131
- return targetPath.startsWith(pattern.slice(0, -2));
1132
- }
1133
- if (pattern.includes("*")) {
1134
- const regex = new RegExp(
1135
- "^" + pattern.replace(/\*/g, "[^/]*").replace(/\*\*/g, ".*") + "$"
1136
- );
1137
- return regex.test(targetPath);
1138
- }
1139
- return targetPath.startsWith(pattern);
1140
- }
1141
- function toolCallTouchesMemory(mem, toolCall) {
1142
- if (toolCall.path && pathMatchesMemory(mem, toolCall.path)) return true;
1143
- if (toolCall.input_summary) {
1144
- const inferredPath = extractPath(toolCall.input_summary);
1145
- if (inferredPath && pathMatchesMemory(mem, inferredPath)) return true;
1146
- }
1147
- return mem.scope === "repo" || mem.scope === "team";
1148
- }
1149
- function rowToMemoryInjection(row) {
1150
- return {
1151
- id: row.id,
1152
- memory_id: row.memory_id,
1153
- session_id: row.session_id,
1154
- repo: row.repo,
1155
- injected_at: row.injected_at,
1156
- outcome: row.outcome,
1157
- outcome_at: row.outcome_at
1158
- };
1159
- }
1160
- function extractPath(text) {
1161
- const match = text.match(
1162
- /\b((?:src|lib|app|components|utils|test|spec)\/[\w./-]+|[\w./-]+\.(?:ts|tsx|js|jsx|py|rs|go|swift|java|rb|json|toml|ya?ml))\b/
1163
- );
1164
- return match?.[1];
1165
- }
1166
-
1167
- // src/models/history-injections.ts
1168
- import { eq as eq7 } from "drizzle-orm";
1169
- import { randomUUID as randomUUID3 } from "crypto";
1170
- function recordHistoryInjections(db, input) {
1171
- if (!input.session_id || input.snippet_ids.length === 0) return 0;
1172
- const injectedAt = (/* @__PURE__ */ new Date()).toISOString();
1173
- let inserted = 0;
1174
- for (const snippetId of input.snippet_ids) {
1175
- const result = db.insert(historyInjections).values({
1176
- id: randomUUID3(),
1177
- snippet_id: snippetId,
1178
- session_id: input.session_id,
1179
- repo: input.repo ?? null,
1180
- injected_at: injectedAt
1181
- }).onConflictDoNothing({
1182
- target: [historyInjections.snippet_id, historyInjections.session_id]
1183
- }).run();
1184
- inserted += Number(result.changes ?? 0);
1185
- }
1186
- return inserted;
1187
- }
1188
- function listInjectedHistoryIdsForSession(db, sessionId) {
1189
- const rows = db.select({ snippet_id: historyInjections.snippet_id }).from(historyInjections).where(eq7(historyInjections.session_id, sessionId)).all();
1190
- return new Set(rows.map((row) => row.snippet_id));
1191
- }
1192
-
1193
- // src/compiler/context.ts
1194
- var DEFAULT_CONFIG = {
1195
- confidence_threshold: CONFIDENCE.ACTIVE_MIN,
1196
- max_lines: 15,
1197
- max_commands: 3,
1198
- max_gotchas: 3,
1199
- max_history_snippets: 2,
1200
- token_budget: 2e3,
1201
- include_candidates: false
1202
- };
1203
- var QUERY_RESULT_LIMIT = 2;
1204
- var QUERY_VECTOR_RELEVANCE_FLOOR = 0.7;
1205
- var HISTORY_VECTOR_RELEVANCE_FLOOR = 0.7;
1206
- var HISTORY_LEXICAL_RELEVANCE_FLOOR = 0.01;
1207
- function compileContext(db, req) {
1208
- const profile = getRepoQualityProfile(db, req.repo);
1209
- const config = {
1210
- ...DEFAULT_CONFIG,
1211
- ...req.config,
1212
- confidence_threshold: req.config?.confidence_threshold ?? profile.compile_confidence_threshold
1213
- };
1214
- const selectedHistory = selectRepoHistory(db, req.repo, config.max_history_snippets);
1215
- const repoActive = queryMemories(db, {
1216
- repo: req.repo,
1217
- status: "active",
1218
- auto_inject: true
1219
- });
1220
- const globalActive = queryMemories(db, {
1221
- scope: "global",
1222
- status: "active",
1223
- auto_inject: true
1224
- });
1225
- const allActive = dedupeById([...repoActive, ...globalActive]);
1226
- const scoped = req.path ? allActive.filter((m) => pathMatches(m, req.path)) : allActive;
1227
- const passing = scoped.filter(
1228
- (m) => m.confidence >= config.confidence_threshold
1229
- );
1230
- const dropped = scoped.filter(
1231
- (m) => m.confidence < config.confidence_threshold
1232
- );
1233
- if (passing.length === 0 && selectedHistory.length === 0) {
1234
- return {
1235
- text: "",
1236
- memories_included: [],
1237
- memories_dropped: dropped.map((m) => m.id),
1238
- history_included: [],
1239
- token_estimate: 0
1240
- };
1241
- }
1242
- const summaries = getMemoryFeedbackSummaries(db, passing.map((m) => m.id));
1243
- const scored = passing.map((m) => ({
1244
- mem: m,
1245
- score: feedbackWeightedScore(m.confidence, summaries.get(m.id) ?? {
1246
- followed: 0,
1247
- overridden: 0,
1248
- contradicted: 0,
1249
- ignored: 0,
1250
- resolved: 0
1251
- })
1252
- }));
1253
- const sorted = scored.sort((a, b) => {
1254
- const typePrio = typePriority(a.mem.type) - typePriority(b.mem.type);
1255
- if (typePrio !== 0) return typePrio;
1256
- return b.score - a.score;
1257
- }).map((s) => s.mem);
1258
- const deduped = dedupeMemoriesForInjection(sorted);
1259
- const selected = [];
1260
- let commandCount = 0;
1261
- let gotchaCount = 0;
1262
- let lineCount = 0;
1263
- for (const mem of deduped) {
1264
- const memLines = renderMemoryText(mem).split("\n").length;
1265
- if (lineCount + memLines > config.max_lines) continue;
1266
- if (mem.type === "command" && commandCount >= config.max_commands) continue;
1267
- if (mem.type === "gotcha" && gotchaCount >= config.max_gotchas) continue;
1268
- selected.push(mem);
1269
- lineCount += memLines;
1270
- if (mem.type === "command") commandCount++;
1271
- if (mem.type === "gotcha") gotchaCount++;
1272
- }
1273
- const text = renderPack(selected, req.repo, selectedHistory);
1274
- const tokenEstimate = Math.ceil(text.length / 4);
1275
- if (tokenEstimate > config.token_budget) {
1276
- while (selected.length > 1 && Math.ceil(renderPack(selected, req.repo, selectedHistory).length / 4) > config.token_budget) {
1277
- selected.pop();
1278
- }
1279
- }
1280
- const finalText = renderPack(selected, req.repo, selectedHistory);
1281
- recordMemoryInjections(db, {
1282
- memory_ids: selected.map((memory) => memory.id),
1283
- session_id: req.session_id,
1284
- repo: req.repo
1285
- });
1286
- recordHistoryInjections(db, {
1287
- snippet_ids: selectedHistory.map((snippet) => snippet.id),
1288
- session_id: req.session_id,
1289
- repo: req.repo
1290
- });
1291
- return {
1292
- text: finalText,
1293
- memories_included: selected.map((m) => m.id),
1294
- memories_dropped: [
1295
- ...dropped.map((m) => m.id),
1296
- ...sorted.filter((m) => !selected.includes(m)).map((m) => m.id)
1297
- ],
1298
- history_included: selectedHistory.map((snippet) => snippet.id),
1299
- token_estimate: Math.ceil(finalText.length / 4)
1300
- };
1301
- }
1302
- async function compileContextHybrid(db, req) {
1303
- const embeddingConfig = req.embedding_config ?? loadEmbeddingConfigFromEnv();
1304
- const profile = getRepoQualityProfile(db, req.repo);
1305
- const config = {
1306
- ...DEFAULT_CONFIG,
1307
- ...req.config,
1308
- confidence_threshold: req.config?.confidence_threshold ?? profile.compile_confidence_threshold
1309
- };
1310
- const selectedHistory = req.query_text ? await selectRelevantHistory(db, req.repo, req.query_text, config.max_history_snippets) : selectRepoHistory(db, req.repo, config.max_history_snippets);
1311
- const repoMemories = queryMemories(db, { repo: req.repo });
1312
- const globalMemories = queryMemories(db, { scope: "global" });
1313
- const allMemories = dedupeById([...repoMemories, ...globalMemories]).filter(
1314
- (memory) => memory.auto_inject && (memory.status === "active" || config.include_candidates && memory.status === "candidate")
1315
- );
1316
- const scoped = req.path ? allMemories.filter((memory) => pathMatches(memory, req.path)) : allMemories;
1317
- const candidateConfidenceFloor = Math.min(config.confidence_threshold, 0.45);
1318
- const passing = scoped.filter((memory) => {
1319
- if (memory.status === "active") {
1320
- return memory.confidence >= config.confidence_threshold;
1321
- }
1322
- if (memory.status === "candidate" && config.include_candidates) {
1323
- return memory.confidence >= candidateConfidenceFloor;
1324
- }
1325
- return false;
1326
- });
1327
- const dropped = scoped.filter((memory) => !passing.includes(memory));
1328
- if (passing.length === 0 && selectedHistory.length === 0) {
1329
- return {
1330
- text: "",
1331
- memories_included: [],
1332
- memories_dropped: dropped.map((m) => m.id),
1333
- history_included: [],
1334
- token_estimate: 0
1335
- };
1336
- }
1337
- const retrieval = req.query_text ? await hybridSearch(db, req.query_text, embeddingConfig, {
1338
- repo: req.repo,
1339
- limit: QUERY_RESULT_LIMIT
1340
- }) : [];
1341
- const retrievalById = new Map(
1342
- retrieval.map((item) => [item.memory.id, item])
1343
- );
1344
- const summaries = getMemoryFeedbackSummaries(db, passing.map((m) => m.id));
1345
- const emptySummary = { followed: 0, overridden: 0, contradicted: 0, ignored: 0, resolved: 0 };
1346
- const ranked = passing.filter((memory) => {
1347
- const retrievalItem = retrievalById.get(memory.id);
1348
- if (req.query_text) {
1349
- if (!retrievalItem) return false;
1350
- if (embeddingConfig && retrievalItem.similarity < QUERY_VECTOR_RELEVANCE_FLOOR) {
1351
- return false;
1352
- }
1353
- return true;
1354
- }
1355
- if (memory.status !== "candidate") return true;
1356
- const retrievalScore = retrievalItem?.score ?? 0;
1357
- return retrievalScore >= 0.2;
1358
- }).map((memory) => {
1359
- const retrievalScore = retrievalById.get(memory.id)?.score ?? 0;
1360
- const weighted = feedbackWeightedScore(memory.confidence, summaries.get(memory.id) ?? emptySummary);
1361
- const score = req.query_text ? retrievalScore * 0.45 + weighted * 0.25 + scopeScore(memory, req.path) * 0.15 + freshnessScore(memory) * 0.05 + typeScore(memory.type) * 0.1 : weighted * 0.55 + scopeScore(memory, req.path) * 0.2 + freshnessScore(memory) * 0.1 + typeScore(memory.type) * 0.15;
1362
- return { memory, score };
1363
- }).sort((a, b) => b.score - a.score);
1364
- const dedupedRanked = dedupeRankedMemoriesForInjection(ranked);
1365
- const selected = [];
1366
- let commandCount = 0;
1367
- let gotchaCount = 0;
1368
- let lineCount = 0;
1369
- for (const item of dedupedRanked) {
1370
- const memory = item.memory;
1371
- const memLines = renderMemoryText(memory).split("\n").length;
1372
- if (lineCount + memLines > config.max_lines) continue;
1373
- if (memory.type === "command" && commandCount >= config.max_commands) continue;
1374
- if (memory.type === "gotcha" && gotchaCount >= config.max_gotchas) continue;
1375
- selected.push(memory);
1376
- lineCount += memLines;
1377
- if (memory.type === "command") commandCount++;
1378
- if (memory.type === "gotcha") gotchaCount++;
1379
- }
1380
- if (selected.length === 0) {
1381
- const historyOnlyText = renderPack([], req.repo, selectedHistory);
1382
- if (historyOnlyText) {
1383
- recordHistoryInjections(db, {
1384
- snippet_ids: selectedHistory.map((snippet) => snippet.id),
1385
- session_id: req.session_id,
1386
- repo: req.repo
1387
- });
1388
- return {
1389
- text: historyOnlyText,
1390
- memories_included: [],
1391
- memories_dropped: [...dropped, ...passing].map((m) => m.id),
1392
- history_included: selectedHistory.map((snippet) => snippet.id),
1393
- token_estimate: Math.ceil(historyOnlyText.length / 4)
1394
- };
1395
- }
1396
- return {
1397
- text: "",
1398
- memories_included: [],
1399
- memories_dropped: [...dropped, ...passing].map((m) => m.id),
1400
- history_included: [],
1401
- token_estimate: 0
1402
- };
1403
- }
1404
- while (selected.length > 1 && Math.ceil(renderPack(selected, req.repo, selectedHistory).length / 4) > config.token_budget) {
1405
- selected.pop();
1406
- }
1407
- const finalText = renderPack(selected, req.repo, selectedHistory);
1408
- recordMemoryInjections(db, {
1409
- memory_ids: selected.map((memory) => memory.id),
1410
- session_id: req.session_id,
1411
- repo: req.repo
1412
- });
1413
- recordHistoryInjections(db, {
1414
- snippet_ids: selectedHistory.map((snippet) => snippet.id),
1415
- session_id: req.session_id,
1416
- repo: req.repo
1417
- });
1418
- return {
1419
- text: finalText,
1420
- memories_included: selected.map((m) => m.id),
1421
- memories_dropped: [
1422
- ...dropped.map((m) => m.id),
1423
- ...ranked.map((item) => item.memory).filter((memory) => !selected.includes(memory)).map((memory) => memory.id)
1424
- ],
1425
- history_included: selectedHistory.map((snippet) => snippet.id),
1426
- token_estimate: Math.ceil(finalText.length / 4)
1427
- };
1428
- }
1429
- function renderPack(items, repo, history = []) {
1430
- if (items.length === 0 && history.length === 0) return "";
1431
- const rules = items.filter((m) => m.type === "rule" || m.type === "decision");
1432
- const commands = items.filter((m) => m.type === "command");
1433
- const gotchas = items.filter(
1434
- (m) => m.type === "gotcha" || m.type === "review_pattern"
1435
- );
1436
- const sections = [];
1437
- if (rules.length > 0) {
1438
- sections.push(
1439
- "## Rules\n" + rules.map(renderMemoryBullet).join("\n")
1440
- );
1441
- }
1442
- if (commands.length > 0) {
1443
- sections.push(
1444
- "## Commands\n" + commands.map(renderMemoryBullet).join("\n")
1445
- );
1446
- }
1447
- if (gotchas.length > 0) {
1448
- sections.push(
1449
- "## Gotchas\n" + gotchas.map(renderMemoryBullet).join("\n")
1450
- );
1451
- }
1452
- if (history.length > 0) {
1453
- sections.push(
1454
- "## History\n" + history.map(renderHistorySnippet).join("\n")
1455
- );
1456
- }
1457
- return `# Recall: ${repo}
1458
-
1459
- ${sections.join("\n\n")}
1460
- `;
1461
- }
1462
- function renderMemoryBullet(memory) {
1463
- const prefix = memory.scope === "global" ? "[global] " : "";
1464
- return `- ${prefix}${renderMemoryText(memory)}`;
1465
- }
1466
- function renderMemoryText(memory) {
1467
- const text = memory.text.replace(/\r\n/g, "\n").trim();
1468
- const injectedHeading = text.search(/##\s+(Rules|Commands|Gotchas|History)\b/i);
1469
- const stripped = injectedHeading > 0 ? text.slice(0, injectedHeading).trim() : text;
1470
- return stripped.replace(/\s+/g, " ");
1471
- }
1472
- function dedupeMemoriesForInjection(memories4) {
1473
- const seen = /* @__PURE__ */ new Set();
1474
- return memories4.filter((memory) => {
1475
- const key = canonicalInjectionText(memory);
1476
- if (!key) return false;
1477
- if (seen.has(key)) return false;
1478
- seen.add(key);
1479
- return true;
1480
- });
1481
- }
1482
- function dedupeRankedMemoriesForInjection(ranked) {
1483
- const seen = /* @__PURE__ */ new Set();
1484
- return ranked.filter((item) => {
1485
- const key = canonicalInjectionText(item.memory);
1486
- if (!key) return false;
1487
- if (seen.has(key)) return false;
1488
- seen.add(key);
1489
- return true;
1490
- });
1491
- }
1492
- function canonicalInjectionText(memory) {
1493
- return renderMemoryText(memory).toLowerCase().replace(/[`*_]/g, "").replace(/\s+/g, " ").trim();
1494
- }
1495
- var HISTORY_KINDS = /* @__PURE__ */ new Set([
1496
- "decision_summary",
1497
- "correction_summary",
1498
- "review_summary",
1499
- "repo_synthesis"
1500
- ]);
1501
- function selectRepoHistory(db, repo, limit) {
1502
- if (limit <= 0) return [];
1503
- return listHistorySnippets(db, { repo, limit: Math.max(limit * 3, 6) }).filter((snippet) => !snippet.session_id && HISTORY_KINDS.has(snippet.kind)).slice(0, limit);
1504
- }
1505
- async function selectRelevantHistory(db, repo, query, limit) {
1506
- if (limit <= 0) return [];
1507
- const results = await searchHistorySnippets(db, query, {
1508
- repo,
1509
- limit: Math.max(limit * 3, 6)
1510
- });
1511
- return results.filter(
1512
- (result) => result.lexical_score >= HISTORY_LEXICAL_RELEVANCE_FLOOR || result.similarity >= HISTORY_VECTOR_RELEVANCE_FLOOR
1513
- ).map((result) => result.snippet).filter((snippet) => HISTORY_KINDS.has(snippet.kind)).slice(0, limit);
1514
- }
1515
- var HISTORY_ENTRY_MAX_CHARS = 120;
1516
- var HISTORY_MAX_ENTRIES_PER_SNIPPET = 2;
1517
- function renderHistorySnippet(snippet) {
1518
- const lines = snippet.text.split("\n").map((line) => line.trim()).filter(Boolean).filter((line) => !line.startsWith("Repo: ") && !line.endsWith(":"));
1519
- const entries = lines.slice(0, HISTORY_MAX_ENTRIES_PER_SNIPPET).map(
1520
- (line) => line.length > HISTORY_ENTRY_MAX_CHARS ? line.slice(0, HISTORY_ENTRY_MAX_CHARS - 1).trimEnd() + "\u2026" : line
1521
- );
1522
- const body = entries.length > 0 ? entries.join(" | ") : "";
1523
- return `- [${snippet.kind}] ${body}`;
1524
- }
1525
- function pathMatches(mem, targetPath) {
1526
- if (mem.scope === "repo" || mem.scope === "team" || mem.scope === "global") return true;
1527
- if (!mem.path_scope) return true;
1528
- const pattern = mem.path_scope;
1529
- if (pattern.endsWith("**")) {
1530
- const prefix = pattern.slice(0, -2);
1531
- return targetPath.startsWith(prefix);
1532
- }
1533
- if (pattern.includes("*")) {
1534
- const regex = new RegExp(
1535
- "^" + pattern.replace(/\*/g, "[^/]*").replace(/\*\*/g, ".*") + "$"
1536
- );
1537
- return regex.test(targetPath);
1538
- }
1539
- return targetPath.startsWith(pattern);
1540
- }
1541
- function scopeScore(mem, targetPath) {
1542
- if (!targetPath) {
1543
- if (mem.scope === "repo" || mem.scope === "team") return 0.9;
1544
- if (mem.scope === "global") return 0.8;
1545
- return 0.7;
1546
- }
1547
- if (mem.scope === "global") return 0.8;
1548
- if (mem.scope === "path" && mem.path_scope) return 1;
1549
- if (mem.scope === "repo" || mem.scope === "team") return 0.75;
1550
- return pathMatches(mem, targetPath) ? 0.6 : 0;
1551
- }
1552
- function freshnessScore(mem) {
1553
- const basis = mem.last_validated_at ?? mem.last_injected_at ?? mem.updated_at;
1554
- const ageMs = Date.now() - new Date(basis).getTime();
1555
- const ageDays = ageMs / 864e5;
1556
- return Math.max(0, 1 - ageDays / 180);
1557
- }
1558
- function typePriority(type) {
1559
- switch (type) {
1560
- case "rule":
1561
- return 0;
1562
- case "command":
1563
- return 1;
1564
- case "gotcha":
1565
- return 2;
1566
- case "review_pattern":
1567
- return 3;
1568
- case "decision":
1569
- return 4;
1570
- default:
1571
- return 5;
1572
- }
1573
- }
1574
- function typeScore(type) {
1575
- switch (type) {
1576
- case "rule":
1577
- return 1;
1578
- case "command":
1579
- return 0.95;
1580
- case "decision":
1581
- return 0.9;
1582
- case "gotcha":
1583
- return 0.8;
1584
- case "review_pattern":
1585
- return 0.75;
1586
- default:
1587
- return 0.5;
1588
- }
1589
- }
1590
- function dedupeById(memories4) {
1591
- const seen = /* @__PURE__ */ new Set();
1592
- const out = [];
1593
- for (const m of memories4) {
1594
- if (seen.has(m.id)) continue;
1595
- seen.add(m.id);
1596
- out.push(m);
1597
- }
1598
- return out;
1599
- }
1600
-
1601
- // src/adapters/markdown.ts
1602
- function exportMarkdown(db, repo) {
1603
- const result = compileContext(db, { repo });
1604
- if (!result.text) {
1605
- return `# ${repo}
1606
-
1607
- No active memories above confidence threshold.
1608
- `;
1609
- }
1610
- return result.text;
1611
- }
1612
- function exportClaude(db, repo) {
1613
- const result = compileContext(db, { repo });
1614
- if (!result.text) return "";
1615
- return `# CLAUDE.md \u2014 Auto-generated by Recall
1616
- # Do not edit manually. Run \`recall export -r ${repo} -f claude\` to regenerate.
1617
-
1618
- ${result.text}`;
1619
- }
1620
- function exportCodex(db, repo) {
1621
- const result = compileContext(db, { repo });
1622
- if (!result.text) return "";
1623
- return `# AGENTS.md \u2014 Auto-generated by Recall
1624
- # Do not edit manually. Run \`recall export -r ${repo} -f codex\` to regenerate.
1625
-
1626
- ${result.text}`;
1627
- }
1628
-
1629
- // src/repo/discovery.ts
1630
- import { existsSync as existsSync3, readdirSync } from "fs";
1631
- import { execFileSync } from "child_process";
1632
- import { join as join3, resolve } from "path";
1633
- var repoPathCache = /* @__PURE__ */ new Map();
1634
- var SKIP_DIRS = /* @__PURE__ */ new Set([
1635
- ".git",
1636
- "node_modules",
1637
- "dist",
1638
- "build",
1639
- "coverage",
1640
- ".next",
1641
- ".turbo",
1642
- ".venv",
1643
- "venv"
1644
- ]);
1645
- function ensureRepoBootstrapped(db, opts) {
1646
- const repo = normalizeRepoSlug(opts.repo);
1647
- const repoPathHint = opts.repoPathHint ?? null;
1648
- if (!repo && !repoPathHint) {
1649
- return {
1650
- repo: null,
1651
- repo_path: null,
1652
- created_ids: [],
1653
- status: "skipped"
1654
- };
1655
- }
1656
- const resolvedRepo = repo ?? inferRepoSlugFromPath(repoPathHint);
1657
- if (!resolvedRepo) {
1658
- return {
1659
- repo: null,
1660
- repo_path: null,
1661
- created_ids: [],
1662
- status: "unresolved"
1663
- };
1664
- }
1665
- if (queryMemories(db, { repo: resolvedRepo }).length > 0) {
1666
- return {
1667
- repo: resolvedRepo,
1668
- repo_path: null,
1669
- created_ids: [],
1670
- status: "already_known"
1671
- };
1672
- }
1673
- const repoPath = resolveLocalRepoPath(resolvedRepo, {
1674
- repoPathHint,
1675
- searchRoots: opts.searchRoots
1676
- });
1677
- if (!repoPath) {
1678
- return {
1679
- repo: resolvedRepo,
1680
- repo_path: null,
1681
- created_ids: [],
1682
- status: "unresolved"
1683
- };
1684
- }
1685
- const createdIds = scanAndStore(db, repoPath);
1686
- return {
1687
- repo: resolvedRepo,
1688
- repo_path: repoPath,
1689
- created_ids: createdIds,
1690
- status: createdIds.length > 0 ? "bootstrapped" : "scanned_empty"
1691
- };
1692
- }
1693
- function resolveLocalRepoPath(repo, opts = {}) {
1694
- const normalizedRepo = normalizeRepoSlug(repo);
1695
- if (!normalizedRepo) return null;
1696
- if (repoPathCache.has(normalizedRepo)) {
1697
- return repoPathCache.get(normalizedRepo) ?? null;
1698
- }
1699
- const directHint = normalizeRepoPathHint(opts.repoPathHint);
1700
- if (directHint && pathMatchesRepo(directHint, normalizedRepo)) {
1701
- repoPathCache.set(normalizedRepo, directHint);
1702
- return directHint;
1703
- }
1704
- const candidates = collectCandidateRepos(opts.searchRoots ?? getDefaultSearchRoots());
1705
- const basenameMatches = [];
1706
- for (const candidate of candidates) {
1707
- const candidateRepo = inferRepoSlugFromPath(candidate);
1708
- if (candidateRepo === normalizedRepo) {
1709
- repoPathCache.set(normalizedRepo, candidate);
1710
- return candidate;
1711
- }
1712
- if (candidate.endsWith(`/${normalizedRepo.split("/").at(-1)}`)) {
1713
- basenameMatches.push(candidate);
1714
- }
1715
- }
1716
- const fallback = basenameMatches.length === 1 ? basenameMatches[0] : null;
1717
- repoPathCache.set(normalizedRepo, fallback);
1718
- return fallback;
1719
- }
1720
- function inferRepoSlugFromPath(repoPath) {
1721
- const root = normalizeRepoPathHint(repoPath);
1722
- if (!root) return null;
1723
- try {
1724
- const remote = execFileSync(
1725
- "git",
1726
- ["-C", root, "remote", "get-url", "origin"],
1727
- { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }
1728
- ).trim();
1729
- return extractRepoSlugFromRemote2(remote);
1730
- } catch {
1731
- const parts = root.split("/").filter(Boolean);
1732
- return parts.at(-1) ?? null;
1733
- }
1734
- }
1735
- function extractRepoSlugFromRemote2(remote) {
1736
- const trimmed = remote.trim().replace(/\.git$/, "");
1737
- const parts = trimmed.split(/[:/]/).filter(Boolean);
1738
- if (parts.length < 2) return null;
1739
- return `${parts.at(-2)}/${parts.at(-1)}`;
1740
- }
1741
- function pathMatchesRepo(repoPath, repo) {
1742
- const inferred = inferRepoSlugFromPath(repoPath);
1743
- if (inferred === repo) return true;
1744
- return repoPath.endsWith(`/${repo.split("/").at(-1)}`);
1745
- }
1746
- function normalizeRepoSlug(repo) {
1747
- if (!repo) return null;
1748
- const trimmed = repo.trim().replace(/\.git$/, "").replace(/^https?:\/\/[^/]+\//, "");
1749
- if (!trimmed.includes("/")) return null;
1750
- return trimmed.replace(/^git@[^:]+:/, "");
1751
- }
1752
- function normalizeRepoPathHint(repoPath) {
1753
- if (!repoPath) return null;
1754
- const expanded = repoPath.trim().replace(/^~(?=\/)/, process.env.HOME ?? "~");
1755
- try {
1756
- const root = execFileSync(
1757
- "git",
1758
- ["-C", expanded, "rev-parse", "--show-toplevel"],
1759
- { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }
1760
- ).trim();
1761
- return root || null;
1762
- } catch {
1763
- const resolved = resolve(expanded);
1764
- return existsSync3(join3(resolved, ".git")) ? resolved : null;
1765
- }
1766
- }
1767
- function getDefaultSearchRoots() {
1768
- const configured = process.env.RECALL_REPO_ROOTS?.split(",").map((value) => value.trim()).filter(Boolean);
1769
- if (configured?.length) return configured;
1770
- const home = process.env.HOME ?? process.cwd();
1771
- return [join3(home, "Projects")];
1772
- }
1773
- function collectCandidateRepos(searchRoots) {
1774
- const seen = /* @__PURE__ */ new Set();
1775
- const repos = [];
1776
- for (const root of searchRoots) {
1777
- walkRepos(resolve(root), 4, seen, repos);
1778
- }
1779
- return repos;
1780
- }
1781
- function walkRepos(dir, depthRemaining, seen, repos) {
1782
- if (depthRemaining < 0 || seen.has(dir) || !existsSync3(dir)) return;
1783
- seen.add(dir);
1784
- if (existsSync3(join3(dir, ".git"))) {
1785
- repos.push(dir);
1786
- return;
1787
- }
1788
- let entries;
1789
- try {
1790
- entries = readdirSync(dir, { withFileTypes: true });
1791
- } catch {
1792
- return;
1793
- }
1794
- for (const entry of entries) {
1795
- if (!entry.isDirectory()) continue;
1796
- if (SKIP_DIRS.has(entry.name)) continue;
1797
- walkRepos(join3(dir, entry.name), depthRemaining - 1, seen, repos);
1798
- }
1799
- }
1800
-
1801
- // src/artifacts/context.ts
1802
- import { existsSync as existsSync4, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync } from "fs";
1803
- import { join as join4 } from "path";
1804
- import { execFileSync as execFileSync2 } from "child_process";
1805
- function getRepoContextArtifactPath(repoPath) {
1806
- return join4(repoPath, ".recall", "context.md");
1807
- }
1808
- function renderRepoContextArtifact(db, repo) {
1809
- const compiled = exportMarkdown(db, repo).trimEnd();
1810
- const generatedAt = (/* @__PURE__ */ new Date()).toISOString();
1811
- return [
1812
- "<!-- Auto-generated by Recall. Do not edit manually. -->",
1813
- `<!-- Generated at: ${generatedAt} -->`,
1814
- "",
1815
- "# Recall Context",
1816
- "",
1817
- `Repo: \`${repo}\``,
1818
- "",
1819
- "Read this file before making repo-specific assumptions.",
1820
- "",
1821
- compiled,
1822
- ""
1823
- ].join("\n");
1824
- }
1825
- function writeRepoContextArtifact(db, input) {
1826
- const repo = input.repo ?? inferRepoSlugFromPath(input.repo_path) ?? null;
1827
- const repoPath = input.repo_path ?? (repo ? resolveLocalRepoPath(repo) : null);
1828
- if (!repo || !repoPath) {
1829
- return {
1830
- repo,
1831
- repo_path: repoPath,
1832
- output_path: null,
1833
- written: false
1834
- };
1835
- }
1836
- const outputPath = getRepoContextArtifactPath(repoPath);
1837
- mkdirSync2(join4(repoPath, ".recall"), { recursive: true });
1838
- ensureRepoContextExcluded(repoPath);
1839
- const content = renderRepoContextArtifact(db, repo);
1840
- const existing = existsSync4(outputPath) ? readFileSync2(outputPath, "utf-8") : null;
1841
- if (existing !== content) {
1842
- writeFileSync(outputPath, content);
1843
- }
1844
- return {
1845
- repo,
1846
- repo_path: repoPath,
1847
- output_path: outputPath,
1848
- written: existing !== content
1849
- };
1850
- }
1851
- function ensureRepoContextExcluded(repoPath) {
1852
- try {
1853
- const excludePath = execFileSync2(
1854
- "git",
1855
- ["-C", repoPath, "rev-parse", "--git-path", "info/exclude"],
1856
- { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] }
1857
- ).trim();
1858
- if (!excludePath) return;
1859
- const existing = existsSync4(excludePath) ? readFileSync2(excludePath, "utf-8") : "";
1860
- if (existing.split("\n").some((line) => line.trim() === ".recall/")) return;
1861
- const prefix = existing && !existing.endsWith("\n") ? "\n" : "";
1862
- writeFileSync(
1863
- excludePath,
1864
- `${existing}${prefix}# Recall generated context
1865
- .recall/
1866
- `
1867
- );
1868
- } catch {
1869
- }
1870
- }
1871
-
1872
- // src/eval/harness.ts
1873
- import { eq as eq8, sql, and as and3, gte, like } from "drizzle-orm";
1874
- import { randomUUID as randomUUID4 } from "crypto";
1875
- function startEvalSession(db, repo) {
1876
- const id = randomUUID4();
1877
- db.insert(evalSessions).values({
1878
- id,
1879
- repo,
1880
- started_at: (/* @__PURE__ */ new Date()).toISOString()
1881
- }).run();
1882
- return id;
1883
- }
1884
- function endEvalSession(db, sessionId) {
1885
- db.update(evalSessions).set({ ended_at: (/* @__PURE__ */ new Date()).toISOString() }).where(eq8(evalSessions.id, sessionId)).run();
1886
- }
1887
- function incrementEvalCounter(db, sessionId, field, amount = 1) {
1888
- const col = evalSessions[field];
1889
- db.update(evalSessions).set({ [field]: sql`${col} + ${amount}` }).where(eq8(evalSessions.id, sessionId)).run();
1890
- }
1891
- function computeMetrics(db, options = {}) {
1892
- const conditions = [];
1893
- if (options.repo) conditions.push(eq8(evalSessions.repo, options.repo));
1894
- if (options.since) conditions.push(gte(evalSessions.started_at, options.since));
1895
- const sessions = conditions.length > 0 ? db.select().from(evalSessions).where(and3(...conditions)).all() : db.select().from(evalSessions).all();
1896
- if (sessions.length === 0) {
1897
- const maintenance2 = computeMaintenanceMetrics(db);
1898
- return {
1899
- total_sessions: 0,
1900
- injection_rate: 0,
1901
- follow_rate: 0,
1902
- override_rate: 0,
1903
- correction_frequency: 0,
1904
- avg_confidence_at_injection: 0,
1905
- memory_effectiveness: 0,
1906
- ...maintenance2 ? { maintenance: maintenance2 } : {}
1907
- };
1908
- }
1909
- const totals = sessions.reduce(
1910
- (acc, s) => ({
1911
- injected: acc.injected + s.memories_injected,
1912
- followed: acc.followed + s.memories_followed,
1913
- overridden: acc.overridden + s.memories_overridden,
1914
- corrections: acc.corrections + s.user_corrections,
1915
- test_passes: acc.test_passes + s.test_passes,
1916
- test_failures: acc.test_failures + s.test_failures
1917
- }),
1918
- {
1919
- injected: 0,
1920
- followed: 0,
1921
- overridden: 0,
1922
- corrections: 0,
1923
- test_passes: 0,
1924
- test_failures: 0
1925
- }
1926
- );
1927
- const totalTests = totals.test_passes + totals.test_failures;
1928
- const feedbackRows = db.select().from(feedbackEvents).all();
1929
- const injectedFeedback = feedbackRows.filter((f) => f.injected);
1930
- let avgConfidence = 0;
1931
- if (injectedFeedback.length > 0) {
1932
- const memIds = [...new Set(injectedFeedback.map((f) => f.memory_id))];
1933
- let totalConf = 0;
1934
- let count = 0;
1935
- for (const memId of memIds) {
1936
- const mem = db.select({ confidence: memories.confidence }).from(memories).where(eq8(memories.id, memId)).get();
1937
- if (mem) {
1938
- totalConf += mem.confidence;
1939
- count++;
1940
- }
1941
- }
1942
- avgConfidence = count > 0 ? totalConf / count : 0;
1943
- }
1944
- const effectiveness = totals.injected > 0 ? (totals.followed - totals.overridden) / totals.injected : 0;
1945
- const maintenance = computeMaintenanceMetrics(db);
1946
- return {
1947
- total_sessions: sessions.length,
1948
- injection_rate: totals.injected / Math.max(sessions.length, 1),
1949
- follow_rate: totals.injected > 0 ? totals.followed / totals.injected : 0,
1950
- override_rate: totals.injected > 0 ? totals.overridden / totals.injected : 0,
1951
- correction_frequency: totals.corrections / Math.max(sessions.length, 1),
1952
- avg_confidence_at_injection: avgConfidence,
1953
- memory_effectiveness: effectiveness,
1954
- ...maintenance ? { maintenance } : {}
1955
- };
1956
- }
1957
- function computeMaintenanceMetrics(db) {
1958
- const rows = db.select().from(memoryMaintenanceTasks).all();
1959
- if (rows.length === 0) return void 0;
1960
- let completed = 0;
1961
- let abandoned = 0;
1962
- const completed_by_kind = {};
1963
- let completionDurations = [];
1964
- let mergeCompleted = 0;
1965
- for (const row of rows) {
1966
- if (row.status === "completed") {
1967
- completed += 1;
1968
- completed_by_kind[row.kind] = (completed_by_kind[row.kind] ?? 0) + 1;
1969
- if (row.kind === "merge_duplicates") mergeCompleted += 1;
1970
- if (row.completed_at) {
1971
- const delta = new Date(row.completed_at).getTime() - new Date(row.created_at).getTime();
1972
- if (Number.isFinite(delta) && delta >= 0) completionDurations.push(delta);
1973
- }
1974
- } else if (row.status === "abandoned") {
1975
- abandoned += 1;
1976
- }
1977
- }
1978
- const mergeTouched = db.select().from(auditTrail).where(and3(
1979
- like(auditTrail.reason, "merged_%"),
1980
- like(auditTrail.actor, "maintenance:%")
1981
- )).all();
1982
- const touchedMemoryIds = new Set(mergeTouched.map((r) => r.memory_id));
1983
- let mergeRollbacks = 0;
1984
- if (touchedMemoryIds.size > 0) {
1985
- const rollbacks = db.select().from(auditTrail).where(eq8(auditTrail.action, "rolled_back")).all();
1986
- for (const r of rollbacks) {
1987
- if (touchedMemoryIds.has(r.memory_id)) mergeRollbacks += 1;
1988
- }
1989
- }
1990
- const merge_precision = mergeCompleted >= 5 && touchedMemoryIds.size > 0 ? Math.max(0, 1 - mergeRollbacks / touchedMemoryIds.size) : null;
1991
- const mean_completion_ms = completionDurations.length ? completionDurations.reduce((a, b) => a + b, 0) / completionDurations.length : null;
1992
- return {
1993
- total_completed: completed,
1994
- total_abandoned: abandoned,
1995
- abandon_rate: completed + abandoned > 0 ? abandoned / (completed + abandoned) : 0,
1996
- mean_completion_ms,
1997
- completed_by_kind,
1998
- merge_precision,
1999
- merge_rollbacks: mergeRollbacks
2000
- };
2001
- }
2002
- function formatMetricsReport(metrics) {
2003
- const pct = (n) => `${(n * 100).toFixed(1)}%`;
2004
- const lines = [
2005
- `# Recall Evaluation Report`,
2006
- ``,
2007
- `Sessions: ${metrics.total_sessions}`,
2008
- `Avg memories injected/session: ${metrics.injection_rate.toFixed(1)}`,
2009
- ``,
2010
- `## Trust`,
2011
- `Follow rate: ${pct(metrics.follow_rate)}`,
2012
- `Override rate: ${pct(metrics.override_rate)}`,
2013
- `Effectiveness: ${pct(metrics.memory_effectiveness)}`,
2014
- ``,
2015
- `## Learning`,
2016
- `Corrections/session: ${metrics.correction_frequency.toFixed(1)}`,
2017
- `Avg confidence at injection: ${metrics.avg_confidence_at_injection.toFixed(2)}`
2018
- ];
2019
- if (metrics.maintenance) {
2020
- const m = metrics.maintenance;
2021
- lines.push(``, `## Maintenance (tier-2)`);
2022
- lines.push(`Completed tasks: ${m.total_completed}`);
2023
- lines.push(`Abandoned tasks: ${m.total_abandoned}`);
2024
- lines.push(`Abandon rate: ${pct(m.abandon_rate)}`);
2025
- if (m.mean_completion_ms != null) {
2026
- lines.push(`Mean completion: ${(m.mean_completion_ms / 1e3).toFixed(1)}s`);
2027
- }
2028
- if (m.merge_precision != null) {
2029
- lines.push(`Merge precision: ${pct(m.merge_precision)} (rollbacks: ${m.merge_rollbacks})`);
2030
- }
2031
- const kinds = Object.entries(m.completed_by_kind).sort((a, b) => b[1] - a[1]).map(([k, n]) => `${k}=${n}`).join(", ");
2032
- if (kinds) lines.push(`By kind: ${kinds}`);
2033
- }
2034
- return lines.join("\n");
2035
- }
2036
-
2037
- // src/eval/retrieval.ts
2038
- import { readFileSync as readFileSync3 } from "fs";
2039
- function loadRetrievalEvalFile(path) {
2040
- return RetrievalEvalFile.parse(JSON.parse(readFileSync3(path, "utf8")));
2041
- }
2042
- async function runRetrievalEval(db, input, options = {}) {
2043
- const providers = options.providers?.length ? options.providers : ["current"];
2044
- const providerReports = [];
2045
- for (const provider of providers) {
2046
- const cases = [];
2047
- const embeddingConfig = provider === "current" ? loadEmbeddingConfigFromEnv() : embeddingConfigForProvider(provider);
2048
- if (embeddingConfig) {
2049
- await bootstrapEmbeddings(db, embeddingConfig);
2050
- }
2051
- for (const raw of input.cases) {
2052
- const testCase = RetrievalEvalCase.parse(raw);
2053
- const config = caseConfig(testCase);
2054
- const baselineCompiled = compileContext(db, {
2055
- repo: testCase.repo,
2056
- path: testCase.path,
2057
- config
2058
- });
2059
- const hybridCompiled = await compileContextHybrid(db, {
2060
- repo: testCase.repo,
2061
- path: testCase.path,
2062
- query_text: testCase.query_text,
2063
- config: {
2064
- ...config,
2065
- include_candidates: testCase.include_candidates
2066
- },
2067
- embedding_config: embeddingConfig
2068
- });
2069
- const baseline = evaluateCaseRun(db, testCase, baselineCompiled.memories_included, baselineCompiled.token_estimate);
2070
- const hybrid = evaluateCaseRun(db, testCase, hybridCompiled.memories_included, hybridCompiled.token_estimate);
2071
- cases.push({
2072
- name: testCase.name,
2073
- baseline,
2074
- hybrid,
2075
- improved: !baseline.passed && hybrid.passed,
2076
- regressed: baseline.passed && !hybrid.passed
2077
- });
2078
- }
2079
- const total = cases.length;
2080
- const baselinePassed = cases.filter((item) => item.baseline.passed).length;
2081
- const hybridPassed = cases.filter((item) => item.hybrid.passed).length;
2082
- const improved = cases.filter((item) => item.improved).length;
2083
- const regressed = cases.filter((item) => item.regressed).length;
2084
- const baselineExpectedAnyHits = cases.filter((item) => item.baseline.expected_any_hit).length;
2085
- const hybridExpectedAnyHits = cases.filter((item) => item.hybrid.expected_any_hit).length;
2086
- const baselineForbiddenHits = cases.filter((item) => item.baseline.forbidden_hits.length > 0).length;
2087
- const hybridForbiddenHits = cases.filter((item) => item.hybrid.forbidden_hits.length > 0).length;
2088
- const reciprocalRanks = cases.map((item) => item.hybrid.first_expected_rank).filter((rank) => rank != null).map((rank) => 1 / rank);
2089
- providerReports.push({
2090
- provider,
2091
- summary: {
2092
- total_cases: total,
2093
- baseline_passed: baselinePassed,
2094
- hybrid_passed: hybridPassed,
2095
- improved_cases: improved,
2096
- regressed_cases: regressed,
2097
- baseline_expected_any_hit_rate: ratio(baselineExpectedAnyHits, total),
2098
- hybrid_expected_any_hit_rate: ratio(hybridExpectedAnyHits, total),
2099
- baseline_forbidden_hit_rate: ratio(baselineForbiddenHits, total),
2100
- hybrid_forbidden_hit_rate: ratio(hybridForbiddenHits, total)
2101
- },
2102
- metrics: {
2103
- recall_at_k: ratio(hybridExpectedAnyHits, total),
2104
- mrr: reciprocalRanks.length > 0 ? reciprocalRanks.reduce((sum, value) => sum + value, 0) / total : 0,
2105
- override_rate: ratio(hybridForbiddenHits, total)
2106
- },
2107
- cases
2108
- });
2109
- }
2110
- return {
2111
- summary: providerReports[0].summary,
2112
- cases: providerReports[0].cases,
2113
- provider_reports: providerReports
2114
- };
2115
- }
2116
- function formatRetrievalEvalReport(report) {
2117
- const pct = (value) => `${(value * 100).toFixed(1)}%`;
2118
- if (report.provider_reports.length > 1) {
2119
- const lines = [
2120
- "# Retrieval Eval",
2121
- "",
2122
- "## Provider Comparison"
2123
- ];
2124
- for (const provider of report.provider_reports) {
2125
- lines.push(
2126
- `- ${provider.provider}: passed=${provider.summary.hybrid_passed}/${provider.summary.total_cases} recall@k=${pct(provider.metrics.recall_at_k)} mrr=${provider.metrics.mrr.toFixed(3)} override=${pct(provider.metrics.override_rate)}`
2127
- );
2128
- }
2129
- for (const provider of report.provider_reports) {
2130
- lines.push("", `## ${provider.provider}`);
2131
- lines.push(formatSingleProviderReport(provider.summary, provider.cases));
2132
- }
2133
- return lines.join("\n");
2134
- }
2135
- return formatSingleProviderReport(report.summary, report.cases);
2136
- }
2137
- function formatSingleProviderReport(summary, cases) {
2138
- const pct = (value) => `${(value * 100).toFixed(1)}%`;
2139
- const lines = [
2140
- "# Retrieval Eval",
2141
- "",
2142
- `Cases: ${summary.total_cases}`,
2143
- `Baseline passed: ${summary.baseline_passed}`,
2144
- `Hybrid passed: ${summary.hybrid_passed}`,
2145
- `Improved: ${summary.improved_cases}`,
2146
- `Regressed: ${summary.regressed_cases}`,
2147
- "",
2148
- `Baseline expected-any hit rate: ${pct(summary.baseline_expected_any_hit_rate)}`,
2149
- `Hybrid expected-any hit rate: ${pct(summary.hybrid_expected_any_hit_rate)}`,
2150
- `Baseline forbidden hit rate: ${pct(summary.baseline_forbidden_hit_rate)}`,
2151
- `Hybrid forbidden hit rate: ${pct(summary.hybrid_forbidden_hit_rate)}`
2152
- ];
2153
- const failedCases = cases.filter((item) => !item.hybrid.passed || item.regressed || item.improved);
2154
- if (failedCases.length > 0) {
2155
- lines.push("", "## Case Details");
2156
- for (const item of failedCases) {
2157
- lines.push(`- ${item.name}`);
2158
- lines.push(` baseline: ${describeRun(item.baseline)}`);
2159
- lines.push(` hybrid: ${describeRun(item.hybrid)}`);
2160
- }
2161
- }
2162
- return lines.join("\n");
2163
- }
2164
- function caseConfig(testCase) {
2165
- return {
2166
- ...testCase.confidence_threshold != null ? { confidence_threshold: testCase.confidence_threshold } : {},
2167
- ...testCase.max_lines != null ? { max_lines: testCase.max_lines } : {},
2168
- ...testCase.max_commands != null ? { max_commands: testCase.max_commands } : {},
2169
- ...testCase.max_gotchas != null ? { max_gotchas: testCase.max_gotchas } : {},
2170
- ...testCase.token_budget != null ? { token_budget: testCase.token_budget } : {}
2171
- };
2172
- }
2173
- function evaluateCaseRun(db, testCase, memoryIds, tokenEstimate) {
2174
- const includedTexts = memoryIds.map((id) => getMemory(db, id)?.text).filter((text) => Boolean(text));
2175
- const expectedAllMissing = testCase.expected_all_texts.filter((expected) => !includedTexts.includes(expected));
2176
- const expectedAnyHit = testCase.expected_any_texts.length === 0 ? true : testCase.expected_any_texts.some((expected) => includedTexts.includes(expected));
2177
- const forbiddenHits = testCase.forbidden_texts.filter((forbidden) => includedTexts.includes(forbidden));
2178
- const relevantTexts = [
2179
- ...testCase.expected_all_texts,
2180
- ...testCase.expected_any_texts
2181
- ];
2182
- const firstExpectedRank = relevantTexts.length === 0 ? null : includedTexts.findIndex((text) => relevantTexts.includes(text)) + 1 || null;
2183
- let countViolation;
2184
- if (testCase.min_included != null && memoryIds.length < testCase.min_included) {
2185
- countViolation = `included ${memoryIds.length} < min ${testCase.min_included}`;
2186
- } else if (testCase.max_included != null && memoryIds.length > testCase.max_included) {
2187
- countViolation = `included ${memoryIds.length} > max ${testCase.max_included}`;
2188
- }
2189
- const passed = expectedAllMissing.length === 0 && expectedAnyHit && forbiddenHits.length === 0 && !countViolation;
2190
- return {
2191
- included_ids: memoryIds,
2192
- included_texts: includedTexts,
2193
- token_estimate: tokenEstimate,
2194
- passed,
2195
- expected_all_missing: expectedAllMissing,
2196
- expected_any_hit: expectedAnyHit,
2197
- forbidden_hits: forbiddenHits,
2198
- first_expected_rank: firstExpectedRank,
2199
- count_violation: countViolation
2200
- };
2201
- }
2202
- function describeRun(result) {
2203
- const parts = [
2204
- result.passed ? "pass" : "fail",
2205
- `included=${result.included_ids.length}`
2206
- ];
2207
- if (result.expected_all_missing.length > 0) {
2208
- parts.push(`missing_all=${result.expected_all_missing.join(" | ")}`);
2209
- }
2210
- if (!result.expected_any_hit) {
2211
- parts.push("expected_any=miss");
2212
- }
2213
- if (result.forbidden_hits.length > 0) {
2214
- parts.push(`forbidden=${result.forbidden_hits.join(" | ")}`);
2215
- }
2216
- if (result.count_violation) {
2217
- parts.push(result.count_violation);
2218
- }
2219
- return parts.join(" ; ");
2220
- }
2221
- function ratio(value, total) {
2222
- return total > 0 ? value / total : 0;
2223
- }
2224
- function embeddingConfigForProvider(provider) {
2225
- const overrideDimensions = process.env.RECALL_EMBEDDING_DIMS ? parseInt(process.env.RECALL_EMBEDDING_DIMS, 10) : null;
2226
- if (provider === "bge-small-en-v1.5") {
2227
- return {
2228
- provider,
2229
- model: "Xenova/bge-small-en-v1.5",
2230
- dimensions: overrideDimensions ?? 384,
2231
- version: "eval",
2232
- similarity_threshold: 0.8
2233
- };
2234
- }
2235
- if (provider === "multilingual-e5") {
2236
- return {
2237
- provider,
2238
- model: "Xenova/multilingual-e5-small",
2239
- dimensions: overrideDimensions ?? 384,
2240
- version: "eval",
2241
- similarity_threshold: 0.8
2242
- };
2243
- }
2244
- return {
2245
- provider: "nomic",
2246
- model: "nomic-ai/nomic-embed-text-v1.5",
2247
- dimensions: overrideDimensions ?? 512,
2248
- version: "eval",
2249
- similarity_threshold: 0.8
2250
- };
2251
- }
2252
-
2253
- // src/feedback/implicit.ts
2254
- import { eq as eq9 } from "drizzle-orm";
2255
- import { randomUUID as randomUUID5 } from "crypto";
2256
- import { execSync as execSync2 } from "child_process";
2257
- var SIGNAL_WEIGHTS = {
2258
- test_pass: 0.03,
2259
- test_fail: -0.15,
2260
- file_unchanged: 0.02,
2261
- file_rewritten: -0.1,
2262
- task_accepted: 0.05,
2263
- task_rejected: -0.2
2264
- };
2265
- function recordSignal(db, memoryId, sessionId, signalType, context) {
2266
- const id = randomUUID5();
2267
- db.insert(implicitSignals).values({
2268
- id,
2269
- memory_id: memoryId,
2270
- session_id: sessionId,
2271
- signal_type: signalType,
2272
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
2273
- context: context ?? null
2274
- }).run();
2275
- const weight = SIGNAL_WEIGHTS[signalType];
2276
- if (weight > 0) {
2277
- promoteMemory(db, memoryId, "passive_gain");
2278
- } else if (weight < 0) {
2279
- demoteMemory(db, memoryId, `implicit:${signalType}`);
2280
- }
2281
- return id;
2282
- }
2283
- function getSignals(db, memoryId) {
2284
- return db.select().from(implicitSignals).where(eq9(implicitSignals.memory_id, memoryId)).all();
2285
- }
2286
- function runTests(repoPath, command) {
2287
- try {
2288
- const output = execSync2(command, {
2289
- cwd: repoPath,
2290
- encoding: "utf-8",
2291
- timeout: 12e4,
2292
- stdio: ["pipe", "pipe", "pipe"]
2293
- });
2294
- return { passed: true, output };
2295
- } catch (err) {
2296
- return {
2297
- passed: false,
2298
- output: err.stdout ?? err.stderr ?? err.message
2299
- };
2300
- }
2301
- }
2302
- function recordTestSignals(db, sessionId, injectedMemoryIds, testResult) {
2303
- const signalType = testResult.passed ? "test_pass" : "test_fail";
2304
- const ids = [];
2305
- for (const memId of injectedMemoryIds) {
2306
- const id = recordSignal(
2307
- db,
2308
- memId,
2309
- sessionId,
2310
- signalType,
2311
- testResult.output?.slice(0, 500)
2312
- );
2313
- ids.push(id);
2314
- }
2315
- return ids;
2316
- }
2317
- function getSignalStats(db, memoryId) {
2318
- const signals = getSignals(db, memoryId);
2319
- const stats = {
2320
- test_pass: 0,
2321
- test_fail: 0,
2322
- file_unchanged: 0,
2323
- file_rewritten: 0,
2324
- task_accepted: 0,
2325
- task_rejected: 0
2326
- };
2327
- for (const s of signals) {
2328
- stats[s.signal_type] = (stats[s.signal_type] ?? 0) + 1;
2329
- }
2330
- return stats;
2331
- }
2332
-
2333
- // src/policy/engine.ts
2334
- import { eq as eq10, and as and4 } from "drizzle-orm";
2335
- import { randomUUID as randomUUID6 } from "crypto";
2336
- function createPolicy(db, orgId, ruleType, config) {
2337
- const id = randomUUID6();
2338
- const now2 = (/* @__PURE__ */ new Date()).toISOString();
2339
- db.insert(policyRules).values({
2340
- id,
2341
- org_id: orgId,
2342
- rule_type: ruleType,
2343
- config,
2344
- enabled: true,
2345
- created_at: now2,
2346
- updated_at: now2
2347
- }).run();
2348
- return id;
2349
- }
2350
- function listPolicies(db, orgId) {
2351
- return db.select().from(policyRules).where(eq10(policyRules.org_id, orgId)).all().map(rowToPolicy);
2352
- }
2353
- function togglePolicy(db, policyId, enabled) {
2354
- db.update(policyRules).set({ enabled, updated_at: (/* @__PURE__ */ new Date()).toISOString() }).where(eq10(policyRules.id, policyId)).run();
2355
- }
2356
- function deletePolicy(db, policyId) {
2357
- db.delete(policyRules).where(eq10(policyRules.id, policyId)).run();
2358
- }
2359
- function evaluatePolicy(db, orgId, memory) {
2360
- const rules = listPolicies(db, orgId).filter((r) => r.enabled);
2361
- const violations = [];
2362
- for (const rule of rules) {
2363
- const cfg = rule.config;
2364
- switch (rule.rule_type) {
2365
- case "min_confidence": {
2366
- const min = cfg.min_confidence ?? 0.6;
2367
- if (memory.confidence < min) {
2368
- violations.push({
2369
- rule_id: rule.id,
2370
- rule_type: rule.rule_type,
2371
- message: `Confidence ${memory.confidence.toFixed(2)} below minimum ${min}`,
2372
- blocking: true
2373
- });
2374
- }
2375
- break;
2376
- }
2377
- case "require_approval": {
2378
- const forTypes = cfg.for_types;
2379
- if (!forTypes || forTypes.includes(memory.type)) {
2380
- violations.push({
2381
- rule_id: rule.id,
2382
- rule_type: rule.rule_type,
2383
- message: `Memory type "${memory.type}" requires approval before activation`,
2384
- blocking: true
2385
- });
2386
- }
2387
- break;
2388
- }
2389
- case "allowed_sources": {
2390
- const allowed = cfg.sources;
2391
- if (allowed && !allowed.includes(memory.source)) {
2392
- violations.push({
2393
- rule_id: rule.id,
2394
- rule_type: rule.rule_type,
2395
- message: `Source "${memory.source}" not in allowed list: ${allowed.join(", ")}`,
2396
- blocking: true
2397
- });
2398
- }
2399
- break;
2400
- }
2401
- case "blocked_scopes": {
2402
- const blocked = cfg.scopes;
2403
- if (blocked && blocked.includes(memory.scope)) {
2404
- violations.push({
2405
- rule_id: rule.id,
2406
- rule_type: rule.rule_type,
2407
- message: `Scope "${memory.scope}" is blocked by policy`,
2408
- blocking: true
2409
- });
2410
- }
2411
- break;
2412
- }
2413
- case "max_active_per_repo": {
2414
- const max = cfg.max ?? 50;
2415
- if (memory.repo) {
2416
- const active = queryMemories(db, { repo: memory.repo, status: "active" });
2417
- if (active.length >= max) {
2418
- violations.push({
2419
- rule_id: rule.id,
2420
- rule_type: rule.rule_type,
2421
- message: `Repo "${memory.repo}" has ${active.length}/${max} active memories`,
2422
- blocking: true
2423
- });
2424
- }
2425
- }
2426
- break;
2427
- }
2428
- case "require_evidence_count": {
2429
- const minEvidence = cfg.min_evidence ?? 2;
2430
- if (memory.evidence.length < minEvidence) {
2431
- violations.push({
2432
- rule_id: rule.id,
2433
- rule_type: rule.rule_type,
2434
- message: `Memory has ${memory.evidence.length} evidence entries, needs ${minEvidence}`,
2435
- blocking: true
2436
- });
2437
- }
2438
- break;
2439
- }
2440
- case "auto_approve_pattern": {
2441
- break;
2442
- }
2443
- }
2444
- }
2445
- return violations;
2446
- }
2447
- function requestApproval(db, memoryId, orgId, requestedBy) {
2448
- const id = randomUUID6();
2449
- const now2 = (/* @__PURE__ */ new Date()).toISOString();
2450
- db.insert(approvalRequests).values({
2451
- id,
2452
- memory_id: memoryId,
2453
- org_id: orgId,
2454
- requested_by: requestedBy,
2455
- status: "pending",
2456
- created_at: now2
2457
- }).run();
2458
- recordAudit(db, memoryId, "approval_requested", requestedBy, null);
2459
- return id;
2460
- }
2461
- function resolveApproval(db, approvalId, status, reviewedBy, reason) {
2462
- const row = db.select().from(approvalRequests).where(eq10(approvalRequests.id, approvalId)).get();
2463
- if (!row) return false;
2464
- const now2 = (/* @__PURE__ */ new Date()).toISOString();
2465
- db.update(approvalRequests).set({
2466
- status,
2467
- reviewed_by: reviewedBy,
2468
- reason: reason ?? null,
2469
- resolved_at: now2
2470
- }).where(eq10(approvalRequests.id, approvalId)).run();
2471
- if (status === "approved") {
2472
- confirmMemory(db, row.memory_id);
2473
- } else {
2474
- rejectMemory(db, row.memory_id);
2475
- }
2476
- recordAudit(db, row.memory_id, "approval_resolved", reviewedBy, reason ?? null);
2477
- return true;
2478
- }
2479
- function listPendingApprovals(db, orgId) {
2480
- return db.select().from(approvalRequests).where(
2481
- and4(
2482
- eq10(approvalRequests.org_id, orgId),
2483
- eq10(approvalRequests.status, "pending")
2484
- )
2485
- ).all();
2486
- }
2487
- function rowToPolicy(row) {
2488
- return {
2489
- ...row,
2490
- config: typeof row.config === "string" ? JSON.parse(row.config) : row.config ?? {},
2491
- enabled: Boolean(row.enabled)
2492
- };
2493
- }
2494
-
2495
- // src/pruning/pruner.ts
2496
- import { eq as eq11 } from "drizzle-orm";
2497
- var DEFAULT_CONFIG2 = {
2498
- stale_days: 90,
2499
- rejected_retention_days: 30,
2500
- transient_retention_days: 7,
2501
- min_health_score: 0.2,
2502
- dry_run: false
2503
- };
2504
- function pruneMemories(db, config = {}) {
2505
- const cfg = { ...DEFAULT_CONFIG2, ...config };
2506
- const now2 = Date.now();
2507
- const dayMs = 864e5;
2508
- const result = {
2509
- stale_rejected: [],
2510
- rejected_pruned: [],
2511
- transient_pruned: [],
2512
- unhealthy_demoted: [],
2513
- total: 0
2514
- };
2515
- const staleCutoff = new Date(now2 - cfg.stale_days * dayMs).toISOString();
2516
- const staleCandidates = queryMemories(db, {
2517
- repo: cfg.repo,
2518
- limit: void 0
2519
- }).filter((mem) => mem.status !== "rejected" && mem.status !== "transient");
2520
- for (const mem of staleCandidates) {
2521
- const lastActivity = mem.last_validated_at ?? mem.last_injected_at ?? mem.updated_at;
2522
- if (lastActivity < staleCutoff) {
2523
- if (!cfg.dry_run) {
2524
- db.update(memories).set({ status: "rejected", dedupe_key: null, updated_at: (/* @__PURE__ */ new Date()).toISOString() }).where(eq11(memories.id, mem.id)).run();
2525
- queueMemoryEmbeddingSync(db, mem.id);
2526
- recordAudit(db, mem.id, "rejected", "auto-pruner", `Stale: no activity since ${lastActivity}`);
2527
- }
2528
- result.stale_rejected.push(mem.id);
2529
- }
2530
- }
2531
- const rejectedCutoff = new Date(
2532
- now2 - cfg.rejected_retention_days * dayMs
2533
- ).toISOString();
2534
- const rejectedMemories = queryMemories(db, {
2535
- repo: cfg.repo,
2536
- status: "rejected"
2537
- });
2538
- for (const mem of rejectedMemories) {
2539
- if (mem.updated_at < rejectedCutoff) {
2540
- if (!cfg.dry_run) {
2541
- db.delete(memories).where(eq11(memories.id, mem.id)).run();
2542
- recordAudit(db, mem.id, "pruned", "auto-pruner", `Rejected memory past ${cfg.rejected_retention_days}d retention`);
2543
- }
2544
- result.rejected_pruned.push(mem.id);
2545
- }
2546
- }
2547
- const transientCutoff = new Date(
2548
- now2 - cfg.transient_retention_days * dayMs
2549
- ).toISOString();
2550
- const transientMemories = queryMemories(db, {
2551
- repo: cfg.repo,
2552
- status: "transient"
2553
- });
2554
- for (const mem of transientMemories) {
2555
- if (mem.updated_at < transientCutoff) {
2556
- if (!cfg.dry_run) {
2557
- db.delete(memories).where(eq11(memories.id, mem.id)).run();
2558
- recordAudit(db, mem.id, "pruned", "auto-pruner", `Transient memory past ${cfg.transient_retention_days}d retention`);
2559
- }
2560
- result.transient_pruned.push(mem.id);
2561
- }
2562
- }
2563
- const activeMemories = queryMemories(db, {
2564
- repo: cfg.repo,
2565
- status: "active"
2566
- });
2567
- for (const mem of activeMemories) {
2568
- const health = computeHealthScore(db, mem.id);
2569
- if (health && health.score < cfg.min_health_score) {
2570
- if (!cfg.dry_run) {
2571
- db.update(memories).set({ status: "candidate", updated_at: (/* @__PURE__ */ new Date()).toISOString() }).where(eq11(memories.id, mem.id)).run();
2572
- queueMemoryEmbeddingSync(db, mem.id);
2573
- recordAudit(
2574
- db,
2575
- mem.id,
2576
- "demoted",
2577
- "auto-pruner",
2578
- `Health score ${health.score.toFixed(2)} below threshold ${cfg.min_health_score}`
2579
- );
2580
- }
2581
- result.unhealthy_demoted.push(mem.id);
2582
- }
2583
- }
2584
- result.total = result.stale_rejected.length + result.rejected_pruned.length + result.transient_pruned.length + result.unhealthy_demoted.length;
2585
- return result;
2586
- }
2587
- function formatPruneReport(result, dryRun) {
2588
- const prefix = dryRun ? "[DRY RUN] " : "";
2589
- const lines = [
2590
- `${prefix}Prune Report`,
2591
- ``,
2592
- `Stale rejected: ${result.stale_rejected.length}`,
2593
- `Rejected pruned: ${result.rejected_pruned.length}`,
2594
- `Transient pruned: ${result.transient_pruned.length}`,
2595
- `Unhealthy demoted: ${result.unhealthy_demoted.length}`,
2596
- `Total affected: ${result.total}`
2597
- ];
2598
- if (result.stale_rejected.length > 0) {
2599
- lines.push("", "Stale Rejected:");
2600
- for (const id of result.stale_rejected.slice(0, 10)) {
2601
- lines.push(` ${id.slice(0, 8)}`);
2602
- }
2603
- }
2604
- if (result.unhealthy_demoted.length > 0) {
2605
- lines.push("", "Unhealthy:");
2606
- for (const id of result.unhealthy_demoted.slice(0, 10)) {
2607
- lines.push(` ${id.slice(0, 8)}`);
2608
- }
2609
- }
2610
- return lines.join("\n");
2611
- }
2612
-
2613
- // src/models/activity.ts
2614
- import { and as and5, desc as desc2, eq as eq12, gte as gte2 } from "drizzle-orm";
2615
- import { randomUUID as randomUUID7 } from "crypto";
2616
- function createActivityEvent(db, input) {
2617
- const safeInput = {
2618
- ...input,
2619
- request: redactSensitiveValue(input.request ?? {}),
2620
- result: redactSensitiveValue(input.result ?? {})
2621
- };
2622
- const dedupeKey = activityEventDedupeKey(safeInput);
2623
- if (dedupeKey) {
2624
- const existingId = findActivityEventByDedupeKey(db, dedupeKey);
2625
- if (existingId) return existingId;
2626
- } else {
2627
- const fuzzyId = findRecentDuplicateActivityEvent(db, safeInput);
2628
- if (fuzzyId) return fuzzyId;
2629
- }
2630
- const id = randomUUID7();
2631
- const result = db.insert(activityEvents).values({
2632
- id,
2633
- session_id: safeInput.session_id ?? null,
2634
- repo: safeInput.repo ?? null,
2635
- path: safeInput.path ?? null,
2636
- source: safeInput.source,
2637
- event_type: safeInput.event_type,
2638
- memory_ids: safeInput.memory_ids ?? [],
2639
- dedupe_key: dedupeKey,
2640
- request: safeInput.request,
2641
- result: safeInput.result,
2642
- created_at: (/* @__PURE__ */ new Date()).toISOString()
2643
- }).onConflictDoNothing({ target: activityEvents.dedupe_key }).run();
2644
- if (Number(result.changes ?? 0) === 0 && dedupeKey) {
2645
- const existingId = findActivityEventByDedupeKey(db, dedupeKey);
2646
- if (existingId) return existingId;
2647
- }
2648
- return id;
2649
- }
2650
- function findActivityEventByDedupeKey(db, dedupeKey) {
2651
- const row = db.select({ id: activityEvents.id }).from(activityEvents).where(eq12(activityEvents.dedupe_key, dedupeKey)).get();
2652
- return row?.id ?? null;
2653
- }
2654
- function findRecentDuplicateActivityEvent(db, input) {
2655
- if (!input.session_id) return null;
2656
- const since = new Date(Date.now() - 2e3).toISOString();
2657
- const rows = db.select().from(activityEvents).where(and5(
2658
- eq12(activityEvents.session_id, input.session_id),
2659
- eq12(activityEvents.source, input.source),
2660
- eq12(activityEvents.event_type, input.event_type),
2661
- gte2(activityEvents.created_at, since)
2662
- )).all();
2663
- const requestKey = JSON.stringify(input.request ?? {});
2664
- const resultKey = JSON.stringify(input.result ?? {});
2665
- const repo = input.repo ?? null;
2666
- const path = input.path ?? null;
2667
- for (const row of rows) {
2668
- if (row.repo !== repo || row.path !== path) continue;
2669
- const request = typeof row.request === "string" ? JSON.parse(row.request) : row.request ?? {};
2670
- const result = typeof row.result === "string" ? JSON.parse(row.result) : row.result ?? {};
2671
- if (JSON.stringify(request) === requestKey && JSON.stringify(result) === resultKey) {
2672
- return row.id;
2673
- }
2674
- }
2675
- return null;
2676
- }
2677
- function listActivityEvents(db, query = {}) {
2678
- const conditions = [];
2679
- if (query.repo) conditions.push(eq12(activityEvents.repo, query.repo));
2680
- if (query.session_id) conditions.push(eq12(activityEvents.session_id, query.session_id));
2681
- if (query.source) conditions.push(eq12(activityEvents.source, query.source));
2682
- if (query.event_type) conditions.push(eq12(activityEvents.event_type, query.event_type));
2683
- if (query.since) conditions.push(gte2(activityEvents.created_at, query.since));
2684
- const base = db.select().from(activityEvents);
2685
- const rows = conditions.length > 0 ? base.where(and5(...conditions)).orderBy(desc2(activityEvents.created_at)).all() : base.orderBy(desc2(activityEvents.created_at)).all();
2686
- const limited = query.limit ? rows.slice(0, query.limit) : rows;
2687
- return limited.map(rowToActivityEvent);
2688
- }
2689
- function listActivitySessions(db, query = {}) {
2690
- const events = listActivityEvents(db, query).filter((event) => event.session_id);
2691
- const grouped = /* @__PURE__ */ new Map();
2692
- for (const event of events) {
2693
- const sessionId = event.session_id;
2694
- const bucket = grouped.get(sessionId) ?? [];
2695
- bucket.push(event);
2696
- grouped.set(sessionId, bucket);
2697
- }
2698
- const sessions = [...grouped.entries()].map(([session_id, items]) => {
2699
- const sorted = [...items].sort((a, b) => a.created_at.localeCompare(b.created_at));
2700
- return {
2701
- session_id,
2702
- repo: sorted[0]?.repo ?? null,
2703
- event_count: items.length,
2704
- event_types: [...new Set(items.map((item) => item.event_type))],
2705
- first_at: sorted[0].created_at,
2706
- last_at: sorted[sorted.length - 1].created_at
2707
- };
2708
- });
2709
- sessions.sort((a, b) => b.last_at.localeCompare(a.last_at));
2710
- return query.limit ? sessions.slice(0, query.limit) : sessions;
2711
- }
2712
- function rowToActivityEvent(row) {
2713
- const memory_ids = typeof row.memory_ids === "string" ? JSON.parse(row.memory_ids) : Array.isArray(row.memory_ids) ? row.memory_ids : [];
2714
- const request = typeof row.request === "string" ? JSON.parse(row.request) : row.request ?? {};
2715
- const result = typeof row.result === "string" ? JSON.parse(row.result) : row.result ?? {};
2716
- return {
2717
- id: row.id,
2718
- session_id: row.session_id,
2719
- repo: row.repo,
2720
- path: row.path,
2721
- source: row.source,
2722
- event_type: row.event_type,
2723
- memory_ids,
2724
- request,
2725
- result,
2726
- created_at: row.created_at
2727
- };
2728
- }
2729
-
2730
- // src/session/lifecycle.ts
2731
- function resolveLifecycleSource(input) {
2732
- if (input.source) return input.source;
2733
- return input.client ? tagActivitySource("hook", input.client) : "daemon";
2734
- }
2735
- function startSessionLifecycle(db, input) {
2736
- const repo = input.repo ?? inferRepoSlugFromPath(input.repo_path) ?? null;
2737
- const bootstrap = ensureRepoBootstrapped(db, {
2738
- repo,
2739
- repoPathHint: input.repo_path
2740
- });
2741
- if (bootstrap.status === "bootstrapped" || bootstrap.status === "scanned_empty") {
2742
- createActivityEvent(db, {
2743
- session_id: input.session_id,
2744
- repo: bootstrap.repo,
2745
- path: input.path ?? null,
2746
- source: resolveLifecycleSource(input),
2747
- event_type: "scan",
2748
- memory_ids: bootstrap.created_ids,
2749
- request: {
2750
- repo_path: bootstrap.repo_path,
2751
- client: input.client ?? null,
2752
- trigger: "session_start_bootstrap"
2753
- },
2754
- result: {
2755
- created: bootstrap.created_ids.length,
2756
- status: bootstrap.status
2757
- }
2758
- });
2759
- }
2760
- const artifact = writeRepoContextArtifact(db, {
2761
- repo: bootstrap.repo,
2762
- repo_path: bootstrap.repo_path ?? input.repo_path ?? null
2763
- });
2764
- createActivityEvent(db, {
2765
- session_id: input.session_id,
2766
- repo: bootstrap.repo,
2767
- path: input.path ?? null,
2768
- source: resolveLifecycleSource(input),
2769
- event_type: "session_start",
2770
- request: {
2771
- client: input.client ?? null,
2772
- repo_path: bootstrap.repo_path ?? input.repo_path ?? null,
2773
- meta: input.meta ?? {}
2774
- },
2775
- result: {
2776
- bootstrap_status: bootstrap.status,
2777
- created: bootstrap.created_ids.length,
2778
- artifact_path: artifact.output_path,
2779
- artifact_written: artifact.written
2780
- }
2781
- });
2782
- return {
2783
- session_id: input.session_id,
2784
- repo: bootstrap.repo,
2785
- repo_path: bootstrap.repo_path ?? input.repo_path ?? null,
2786
- bootstrap_status: bootstrap.status,
2787
- created_ids: bootstrap.created_ids
2788
- };
2789
- }
2790
- function recordSessionLifecycleEvent(db, input) {
2791
- const repo = input.repo ?? inferRepoSlugFromPath(input.repo_path) ?? null;
2792
- createActivityEvent(db, {
2793
- session_id: input.session_id,
2794
- repo,
2795
- path: input.path ?? null,
2796
- source: resolveLifecycleSource(input),
2797
- event_type: "session_event",
2798
- request: {
2799
- client: input.client ?? null,
2800
- name: input.name,
2801
- repo_path: input.repo_path ?? null,
2802
- meta: input.meta ?? {}
2803
- },
2804
- result: input.payload ?? {}
2805
- });
2806
- return {
2807
- session_id: input.session_id,
2808
- repo,
2809
- repo_path: input.repo_path ?? null,
2810
- bootstrap_status: "skipped",
2811
- created_ids: []
2812
- };
2813
- }
2814
- function endSessionLifecycle(db, input) {
2815
- const repo = input.repo ?? inferRepoSlugFromPath(input.repo_path) ?? null;
2816
- createActivityEvent(db, {
2817
- session_id: input.session_id,
2818
- repo,
2819
- path: input.path ?? null,
2820
- source: resolveLifecycleSource(input),
2821
- event_type: "session_end",
2822
- request: {
2823
- client: input.client ?? null,
2824
- repo_path: input.repo_path ?? null,
2825
- meta: input.meta ?? {}
2826
- },
2827
- result: input.payload ?? {}
2828
- });
2829
- return {
2830
- session_id: input.session_id,
2831
- repo,
2832
- repo_path: input.repo_path ?? null,
2833
- bootstrap_status: "skipped",
2834
- created_ids: []
2835
- };
2836
- }
2837
-
2838
- // src/mcp/fallback.ts
2839
- async function captureCorrectionFallback(db, input, source) {
2840
- const sessionId = input.session_id ?? `${source}-capture`;
2841
- const ids = await processCorrection(db, input.text, {
2842
- sessionId,
2843
- repo: input.repo,
2844
- path: input.path,
2845
- agent: input.agent,
2846
- prev_assistant_turn: input.prev_assistant_turn,
2847
- recent_tool_calls: input.recent_tool_calls
2848
- });
2849
- createActivityEvent(db, {
2850
- session_id: sessionId,
2851
- repo: input.repo ?? null,
2852
- path: input.path ?? null,
2853
- source,
2854
- event_type: "correction",
2855
- memory_ids: ids,
2856
- request: {
2857
- agent: input.agent ?? null,
2858
- prev_assistant_turn: input.prev_assistant_turn ?? null,
2859
- recent_tool_calls: normalizeRecentToolCalls(input.recent_tool_calls),
2860
- text: input.text
2861
- },
2862
- result: {
2863
- created: ids,
2864
- created_count: ids.length
2865
- }
2866
- });
2867
- return {
2868
- ids,
2869
- session_id: sessionId
2870
- };
2871
- }
2872
- function signalOutcomeFallback(db, input, source) {
2873
- const feedbackId = recordFeedback(
2874
- db,
2875
- input.memory_id,
2876
- input.session_id,
2877
- input.injected ?? true,
2878
- input.outcome
2879
- );
2880
- resolveMemoryInjectionOutcome(db, input.memory_id, input.session_id, input.outcome);
2881
- const memory = getMemory(db, input.memory_id);
2882
- createActivityEvent(db, {
2883
- session_id: input.session_id,
2884
- repo: memory?.repo ?? null,
2885
- path: memory?.path_scope ?? null,
2886
- source,
2887
- event_type: "feedback",
2888
- memory_ids: [input.memory_id],
2889
- request: {
2890
- context: input.context ?? null,
2891
- injected: input.injected ?? true,
2892
- outcome: input.outcome
2893
- },
2894
- result: {
2895
- feedback_id: feedbackId
2896
- }
2897
- });
2898
- return {
2899
- feedback_id: feedbackId
2900
- };
2901
- }
2902
- function sessionEndFallback(db, input) {
2903
- const result = endSessionLifecycle(db, {
2904
- session_id: input.session_id,
2905
- client: input.agent ?? "mcp",
2906
- repo: input.repo ?? null,
2907
- repo_path: input.repo_path ?? null,
2908
- path: input.path ?? null,
2909
- payload: {
2910
- ended_at: (/* @__PURE__ */ new Date()).toISOString(),
2911
- turn_count: input.turn_count ?? null
2912
- }
2913
- });
2914
- return {
2915
- session_id: result.session_id,
2916
- repo: result.repo
2917
- };
2918
- }
2919
- function normalizeRecentToolCalls(toolCalls) {
2920
- if (!toolCalls) return [];
2921
- return toolCalls.map((toolCall) => ({
2922
- name: toolCall.name,
2923
- path: toolCall.path,
2924
- input_summary: toolCall.input_summary,
2925
- exit_code: toolCall.exit_code
2926
- }));
2927
- }
2928
-
2929
- export {
2930
- RECALL_DB_USER_VERSION,
2931
- getDbPath,
2932
- initDb,
2933
- getDbUserVersion,
2934
- resetDb,
2935
- evaluateScannedMemory,
2936
- scanAndStore,
2937
- listInjectedMemoryIdsForSession,
2938
- listPendingMemoryInjections,
2939
- pathMatchesMemory,
2940
- toolCallTouchesMemory,
2941
- listInjectedHistoryIdsForSession,
2942
- createHistorySnippet,
2943
- listHistorySnippets,
2944
- findHistorySnippetBySession,
2945
- findHistorySnippetByRepoKind,
2946
- updateHistorySnippet,
2947
- removeHistoryVecRow,
2948
- removeHistoryFtsRow,
2949
- syncHistoryFtsIndex,
2950
- bootstrapHistoryEmbeddings,
2951
- verifyHistoryEmbeddings,
2952
- searchHistorySnippets,
2953
- compileContext,
2954
- compileContextHybrid,
2955
- exportMarkdown,
2956
- exportClaude,
2957
- exportCodex,
2958
- ensureRepoBootstrapped,
2959
- inferRepoSlugFromPath,
2960
- writeRepoContextArtifact,
2961
- startEvalSession,
2962
- endEvalSession,
2963
- incrementEvalCounter,
2964
- computeMetrics,
2965
- formatMetricsReport,
2966
- loadRetrievalEvalFile,
2967
- runRetrievalEval,
2968
- formatRetrievalEvalReport,
2969
- recordSignal,
2970
- runTests,
2971
- recordTestSignals,
2972
- getSignalStats,
2973
- createPolicy,
2974
- listPolicies,
2975
- togglePolicy,
2976
- deletePolicy,
2977
- evaluatePolicy,
2978
- requestApproval,
2979
- resolveApproval,
2980
- listPendingApprovals,
2981
- pruneMemories,
2982
- formatPruneReport,
2983
- createActivityEvent,
2984
- listActivityEvents,
2985
- listActivitySessions,
2986
- startSessionLifecycle,
2987
- recordSessionLifecycleEvent,
2988
- endSessionLifecycle,
2989
- captureCorrectionFallback,
2990
- signalOutcomeFallback,
2991
- sessionEndFallback
2992
- };
2993
- //# sourceMappingURL=chunk-DSNYEUZW.js.map