memorix 1.10.2 → 1.10.4

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 (101) hide show
  1. package/CHANGELOG.md +82 -1
  2. package/README.md +3 -1
  3. package/README.zh-CN.md +3 -1
  4. package/dist/cli/index.js +2281 -1486
  5. package/dist/cli/memcode.js +0 -0
  6. package/dist/index.js +1874 -1126
  7. package/dist/{maintenance-jobs-DVRF-46r.d.ts → maintenance-jobs-DweoCoTT.d.ts} +25 -15
  8. package/dist/maintenance-runner.d.ts +1 -1
  9. package/dist/maintenance-runner.js +802 -194
  10. package/dist/media-audio-runner.js +793 -186
  11. package/dist/media-video-runner.js +801 -194
  12. package/dist/memcode-runtime/CHANGELOG.md +64 -1
  13. package/dist/sdk.js +14036 -13317
  14. package/dist/types.d.ts +1 -1
  15. package/dist/vector-backfill-runner.d.ts +1 -1
  16. package/dist/vector-backfill-runner.js +801 -194
  17. package/docs/ARCHITECTURE.md +219 -0
  18. package/docs/CONFIGURATION.md +49 -0
  19. package/docs/DESIGN_DECISIONS.md +37 -0
  20. package/docs/DEVELOPMENT.md +1 -1
  21. package/docs/INTEGRATIONS.md +1 -1
  22. package/docs/MODULES.md +7 -1
  23. package/docs/PERFORMANCE.md +14 -0
  24. package/docs/README.md +2 -1
  25. package/docs/ROADMAP-1.9.12-2.0.md +18 -2
  26. package/docs/SETUP.md +19 -4
  27. package/package.json +1 -1
  28. package/plugins/antigravity/memorix/plugin.json +1 -1
  29. package/plugins/claude/memorix/.claude-plugin/plugin.json +1 -1
  30. package/plugins/codebuddy/memorix/.codebuddy-plugin/plugin.json +1 -1
  31. package/plugins/codex/memorix/.codex-plugin/plugin.json +1 -1
  32. package/plugins/copilot/memorix/plugin.json +1 -1
  33. package/plugins/gemini/memorix/gemini-extension.json +1 -1
  34. package/plugins/hermes/memorix/plugin.yaml +1 -1
  35. package/plugins/omp/memorix/package.json +1 -1
  36. package/plugins/openclaw/memorix/.codex-plugin/plugin.json +1 -1
  37. package/plugins/pi/memorix/package.json +1 -1
  38. package/server.json +2 -2
  39. package/src/cli/commands/agent-integrations.ts +1 -1
  40. package/src/cli/commands/background.ts +1 -1
  41. package/src/cli/commands/context.ts +3 -2
  42. package/src/cli/commands/doctor.ts +9 -0
  43. package/src/cli/commands/explain.ts +3 -2
  44. package/src/cli/commands/init.ts +6 -2
  45. package/src/cli/commands/setup.ts +9 -6
  46. package/src/cli/commands/uninstall.ts +15 -0
  47. package/src/cli/tui/App.tsx +9 -16
  48. package/src/cli/tui/ConfigureView.tsx +2 -0
  49. package/src/cli/tui/chat-service.ts +6 -9
  50. package/src/cli/tui/data.ts +2 -2
  51. package/src/codegraph/auto-context.ts +10 -3
  52. package/src/codegraph/derived-view.ts +63 -0
  53. package/src/codegraph/store.ts +37 -0
  54. package/src/codegraph/types.ts +3 -0
  55. package/src/compact/engine.ts +10 -33
  56. package/src/config/dotenv-loader.ts +1 -0
  57. package/src/config/resolved-config.ts +18 -2
  58. package/src/config/retrieval-strategy.ts +22 -0
  59. package/src/config/toml-loader.ts +6 -0
  60. package/src/config/yaml-loader.ts +11 -2
  61. package/src/core/derived-view.ts +15 -0
  62. package/src/core/maintenance-result.ts +33 -0
  63. package/src/core/retrieval-contracts.ts +57 -0
  64. package/src/core/retrieval-facade.ts +18 -0
  65. package/src/core/retrieval-policy.ts +44 -0
  66. package/src/core/runtime-context.ts +42 -0
  67. package/src/dashboard/server.ts +5 -6
  68. package/src/embedding/api-provider.ts +18 -8
  69. package/src/hooks/handler.ts +0 -1
  70. package/src/integrations/registry.ts +2 -1
  71. package/src/knowledge/workset.ts +0 -2
  72. package/src/llm/provider.ts +2 -1
  73. package/src/memory/consolidation.ts +3 -2
  74. package/src/memory/feedback-model.ts +1 -4
  75. package/src/memory/observations.ts +226 -104
  76. package/src/multimodal/image-loader.ts +2 -2
  77. package/src/runtime/control-plane-maintenance.ts +1 -0
  78. package/src/runtime/isolated-maintenance.ts +1 -0
  79. package/src/runtime/maintenance-jobs.ts +123 -32
  80. package/src/runtime/open-browser.ts +25 -0
  81. package/src/runtime/project-maintenance.ts +69 -1
  82. package/src/sdk.ts +3 -2
  83. package/src/search/fts-view.ts +53 -0
  84. package/src/search/orama-view.ts +40 -0
  85. package/src/search/retrieval-facade.ts +38 -0
  86. package/src/search/semantic-index.ts +13 -0
  87. package/src/search/semantic-view.ts +34 -0
  88. package/src/server.ts +21 -9
  89. package/src/store/obs-store.ts +15 -0
  90. package/src/store/orama-store.ts +143 -45
  91. package/src/store/sqlite-db.ts +22 -0
  92. package/src/store/sqlite-store.ts +27 -0
  93. package/src/types.ts +1 -1
  94. package/src/workspace/mcp-adapters/pi.ts +58 -0
  95. package/plugins/pi/memorix/skills/memorix-git-memory/SKILL.md +0 -26
  96. package/plugins/pi/memorix/skills/memorix-memory/SKILL.md +0 -51
  97. package/plugins/pi/memorix/skills/memorix-mini-skills/SKILL.md +0 -31
  98. package/plugins/pi/memorix/skills/memorix-orchestrate/SKILL.md +0 -28
  99. package/plugins/pi/memorix/skills/memorix-reasoning/SKILL.md +0 -30
  100. package/plugins/pi/memorix/skills/memorix-sessions/SKILL.md +0 -25
  101. package/plugins/pi/memorix/skills/memorix-troubleshooting/SKILL.md +0 -27
@@ -193,6 +193,7 @@ function loadYamlConfig(projectRoot, options = {}) {
193
193
  llm: { ...userConfig.llm, ...projectConfig.llm },
194
194
  agent: { ...userConfig.agent, ...projectConfig.agent },
195
195
  embedding: { ...userConfig.embedding, ...projectConfig.embedding },
196
+ retrieval: { ...userConfig.retrieval, ...projectConfig.retrieval },
196
197
  rerank: { ...userConfig.rerank, ...projectConfig.rerank },
197
198
  git: { ...userConfig.git, ...projectConfig.git },
198
199
  codegraph: { ...userConfig.codegraph, ...projectConfig.codegraph },
@@ -1344,6 +1345,12 @@ CREATE TABLE IF NOT EXISTS maintenance_jobs (
1344
1345
  lease_owner TEXT,
1345
1346
  lease_expires_at INTEGER,
1346
1347
  last_error TEXT,
1348
+ attempted INTEGER NOT NULL DEFAULT 0,
1349
+ succeeded INTEGER NOT NULL DEFAULT 0,
1350
+ failed INTEGER NOT NULL DEFAULT 0,
1351
+ remaining INTEGER NOT NULL DEFAULT 0,
1352
+ progress_recorded INTEGER NOT NULL DEFAULT 0,
1353
+ rerun_requested INTEGER NOT NULL DEFAULT 0,
1347
1354
  created_at INTEGER NOT NULL,
1348
1355
  updated_at INTEGER NOT NULL,
1349
1356
  completed_at INTEGER
@@ -1764,6 +1771,22 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_maintenance_jobs_active_dedupe
1764
1771
  ON task_continuity_events(project_id, task_id, event_key)
1765
1772
  WHERE event_key IS NOT NULL`);
1766
1773
  }
1774
+ },
1775
+ {
1776
+ id: "1.11-maintenance-progress",
1777
+ apply: (db2) => {
1778
+ addColumnIfMissing(db2, "maintenance_jobs", "attempted", "attempted INTEGER NOT NULL DEFAULT 0");
1779
+ addColumnIfMissing(db2, "maintenance_jobs", "succeeded", "succeeded INTEGER NOT NULL DEFAULT 0");
1780
+ addColumnIfMissing(db2, "maintenance_jobs", "failed", "failed INTEGER NOT NULL DEFAULT 0");
1781
+ addColumnIfMissing(db2, "maintenance_jobs", "remaining", "remaining INTEGER NOT NULL DEFAULT 0");
1782
+ addColumnIfMissing(db2, "maintenance_jobs", "progress_recorded", "progress_recorded INTEGER NOT NULL DEFAULT 0");
1783
+ }
1784
+ },
1785
+ {
1786
+ id: "1.11-maintenance-rerun",
1787
+ apply: (db2) => {
1788
+ addColumnIfMissing(db2, "maintenance_jobs", "rerun_requested", "rerun_requested INTEGER NOT NULL DEFAULT 0");
1789
+ }
1767
1790
  }
1768
1791
  ];
1769
1792
  _dbCache = /* @__PURE__ */ new Map();
@@ -2280,6 +2303,24 @@ var init_media_store = __esm({
2280
2303
  }
2281
2304
  });
2282
2305
 
2306
+ // src/core/maintenance-result.ts
2307
+ function assertMaintenanceProgress(progress) {
2308
+ if (!progress) return;
2309
+ const counts = [progress.attempted, progress.succeeded, progress.failed, progress.remaining];
2310
+ if (counts.some((count2) => !Number.isSafeInteger(count2) || count2 < 0)) {
2311
+ throw new Error("maintenance progress must contain non-negative safe integers");
2312
+ }
2313
+ if (progress.succeeded + progress.failed > progress.attempted) {
2314
+ throw new Error("maintenance progress outcomes exceed attempted work");
2315
+ }
2316
+ }
2317
+ var init_maintenance_result = __esm({
2318
+ "src/core/maintenance-result.ts"() {
2319
+ "use strict";
2320
+ init_esm_shims();
2321
+ }
2322
+ });
2323
+
2283
2324
  // src/runtime/maintenance-jobs.ts
2284
2325
  var maintenance_jobs_exports = {};
2285
2326
  __export(maintenance_jobs_exports, {
@@ -2313,6 +2354,12 @@ function rowToJob2(row) {
2313
2354
  ...row.lease_owner ? { leaseOwner: row.lease_owner } : {},
2314
2355
  ...row.lease_expires_at != null ? { leaseExpiresAt: Number(row.lease_expires_at) } : {},
2315
2356
  ...row.last_error ? { lastError: row.last_error } : {},
2357
+ ...Number(row.progress_recorded ?? 0) === 1 ? { progress: {
2358
+ attempted: Number(row.attempted ?? 0),
2359
+ succeeded: Number(row.succeeded ?? 0),
2360
+ failed: Number(row.failed ?? 0),
2361
+ remaining: Number(row.remaining ?? 0)
2362
+ } } : {},
2316
2363
  createdAt: Number(row.created_at),
2317
2364
  updatedAt: Number(row.updated_at),
2318
2365
  ...row.completed_at != null ? { completedAt: Number(row.completed_at) } : {}
@@ -2338,6 +2385,7 @@ var init_maintenance_jobs = __esm({
2338
2385
  "src/runtime/maintenance-jobs.ts"() {
2339
2386
  "use strict";
2340
2387
  init_esm_shims();
2388
+ init_maintenance_result();
2341
2389
  init_sqlite_db();
2342
2390
  init_secret_filter();
2343
2391
  MAINTENANCE_JOB_KINDS = [
@@ -2348,6 +2396,7 @@ var init_maintenance_jobs = __esm({
2348
2396
  "consolidation",
2349
2397
  "codegraph-refresh",
2350
2398
  "observation-qualify",
2399
+ "observation-project",
2351
2400
  "claim-derive",
2352
2401
  "claim-requalification",
2353
2402
  "knowledge-compile",
@@ -2386,6 +2435,16 @@ var init_maintenance_jobs = __esm({
2386
2435
  this.commit();
2387
2436
  return rowToJob2(existing);
2388
2437
  }
2438
+ if (existing.status === "running") {
2439
+ this.db.prepare(`
2440
+ UPDATE maintenance_jobs
2441
+ SET rerun_requested = 1, payload_json = ?, updated_at = ?
2442
+ WHERE id = ?
2443
+ `).run(payloadJson, now3, existing.id);
2444
+ const updated2 = this.getRow(existing.id);
2445
+ this.commit();
2446
+ return rowToJob2(updated2);
2447
+ }
2389
2448
  const nextRunAfter = Math.min(Number(existing.run_after), runAfter);
2390
2449
  this.db.prepare(`
2391
2450
  UPDATE maintenance_jobs
@@ -2513,8 +2572,10 @@ var init_maintenance_jobs = __esm({
2513
2572
  this.db.prepare(`
2514
2573
  UPDATE maintenance_jobs
2515
2574
  SET
2516
- status = CASE WHEN attempts >= max_attempts THEN 'failed' ELSE 'retry' END,
2517
- run_after = CASE WHEN attempts >= max_attempts THEN run_after ELSE ? END,
2575
+ status = CASE WHEN attempts >= max_attempts AND rerun_requested = 0 THEN 'failed' ELSE 'retry' END,
2576
+ run_after = CASE WHEN attempts >= max_attempts AND rerun_requested = 0 THEN run_after ELSE ? END,
2577
+ attempts = CASE WHEN rerun_requested = 1 AND attempts >= max_attempts THEN 0 ELSE attempts END,
2578
+ rerun_requested = 0,
2518
2579
  lease_owner = NULL,
2519
2580
  lease_expires_at = NULL,
2520
2581
  last_error = COALESCE(last_error, 'worker lease expired'),
@@ -2577,14 +2638,55 @@ var init_maintenance_jobs = __esm({
2577
2638
  `).run(expiresAt, now3, id, workerId);
2578
2639
  return Number(result.changes) > 0;
2579
2640
  }
2580
- complete(id, workerId, now3 = Date.now()) {
2581
- this.db.prepare(`
2582
- UPDATE maintenance_jobs
2583
- SET status = 'completed', lease_owner = NULL, lease_expires_at = NULL,
2584
- completed_at = ?, updated_at = ?
2585
- WHERE id = ? AND status = 'running' AND lease_owner = ?
2586
- `).run(now3, now3, id, workerId);
2587
- return this.get(id);
2641
+ complete(id, workerId, now3 = Date.now(), progress) {
2642
+ assertMaintenanceProgress(progress);
2643
+ this.begin();
2644
+ try {
2645
+ const current = this.db.prepare(`
2646
+ SELECT rerun_requested FROM maintenance_jobs
2647
+ WHERE id = ? AND status = 'running' AND lease_owner = ?
2648
+ `).get(id, workerId);
2649
+ if (!current) {
2650
+ this.commit();
2651
+ return void 0;
2652
+ }
2653
+ if (Number(current.rerun_requested) === 1) {
2654
+ this.db.prepare(`
2655
+ UPDATE maintenance_jobs
2656
+ SET status = 'pending', attempts = 0, run_after = ?,
2657
+ rerun_requested = 0, lease_owner = NULL, lease_expires_at = NULL,
2658
+ attempted = 0, succeeded = 0, failed = 0, remaining = 0,
2659
+ progress_recorded = 0, last_error = NULL, completed_at = NULL,
2660
+ updated_at = ?
2661
+ WHERE id = ?
2662
+ `).run(now3, now3, id);
2663
+ } else {
2664
+ this.db.prepare(`
2665
+ UPDATE maintenance_jobs
2666
+ SET status = 'completed', lease_owner = NULL, lease_expires_at = NULL,
2667
+ attempted = COALESCE(?, attempted), succeeded = COALESCE(?, succeeded),
2668
+ failed = COALESCE(?, failed), remaining = COALESCE(?, remaining),
2669
+ progress_recorded = CASE WHEN ? THEN 1 ELSE progress_recorded END,
2670
+ completed_at = ?, updated_at = ?
2671
+ WHERE id = ?
2672
+ `).run(
2673
+ progress?.attempted ?? null,
2674
+ progress?.succeeded ?? null,
2675
+ progress?.failed ?? null,
2676
+ progress?.remaining ?? null,
2677
+ progress ? 1 : 0,
2678
+ now3,
2679
+ now3,
2680
+ id
2681
+ );
2682
+ }
2683
+ const updated = this.get(id);
2684
+ this.commit();
2685
+ return updated;
2686
+ } catch (error) {
2687
+ this.rollback();
2688
+ throw error;
2689
+ }
2588
2690
  }
2589
2691
  reschedule(id, workerId, options) {
2590
2692
  const now3 = options.now ?? Date.now();
@@ -2593,22 +2695,37 @@ var init_maintenance_jobs = __esm({
2593
2695
  const status = options.status === "retry" ? "retry" : "pending";
2594
2696
  const hasLastError = options.lastError !== void 0;
2595
2697
  const lastError = hasLastError ? errorText(options.lastError) : null;
2698
+ const progress = options.progress;
2699
+ assertMaintenanceProgress(progress);
2596
2700
  this.db.prepare(`
2597
2701
  UPDATE maintenance_jobs
2598
- SET status = ?, run_after = ?, attempts = CASE WHEN ? THEN 0 ELSE attempts END,
2599
- payload_json = COALESCE(?, payload_json),
2702
+ SET status = ?,
2703
+ run_after = CASE WHEN rerun_requested = 1 AND ? = 0 THEN ? ELSE ? END,
2704
+ attempts = CASE WHEN rerun_requested = 1 AND ? = 0 THEN 0 WHEN ? THEN 0 ELSE attempts END,
2705
+ payload_json = CASE WHEN rerun_requested = 1 THEN payload_json ELSE COALESCE(?, payload_json) END,
2706
+ attempted = COALESCE(?, attempted), succeeded = COALESCE(?, succeeded),
2707
+ failed = COALESCE(?, failed), remaining = COALESCE(?, remaining),
2708
+ progress_recorded = CASE WHEN ? THEN 1 ELSE progress_recorded END,
2600
2709
  last_error = CASE
2601
2710
  WHEN ? THEN NULL
2602
2711
  WHEN ? THEN ?
2603
2712
  ELSE last_error
2604
2713
  END,
2605
- lease_owner = NULL, lease_expires_at = NULL, updated_at = ?
2714
+ rerun_requested = 0, lease_owner = NULL, lease_expires_at = NULL, updated_at = ?
2606
2715
  WHERE id = ? AND status = 'running' AND lease_owner = ?
2607
2716
  `).run(
2608
2717
  status,
2718
+ status === "retry" ? 1 : 0,
2719
+ now3,
2609
2720
  now3 + delayMs,
2721
+ status === "retry" ? 1 : 0,
2610
2722
  options.resetAttempts ? 1 : 0,
2611
2723
  payloadJson,
2724
+ progress?.attempted ?? null,
2725
+ progress?.succeeded ?? null,
2726
+ progress?.failed ?? null,
2727
+ progress?.remaining ?? null,
2728
+ progress ? 1 : 0,
2612
2729
  options.clearLastError ? 1 : 0,
2613
2730
  hasLastError ? 1 : 0,
2614
2731
  lastError,
@@ -2626,6 +2743,15 @@ var init_maintenance_jobs = __esm({
2626
2743
  `).run(now3, now3, projectId, dedupeKey);
2627
2744
  return Number(result.changes ?? 0);
2628
2745
  }
2746
+ /** A successful foreground projection can acknowledge its pending outbox row. */
2747
+ acknowledgePending(projectId, kind, dedupeKey, now3 = Date.now()) {
2748
+ const result = this.db.prepare(`
2749
+ UPDATE maintenance_jobs
2750
+ SET status = 'completed', completed_at = ?, updated_at = ?
2751
+ WHERE project_id = ? AND kind = ? AND dedupe_key = ? AND status = 'pending'
2752
+ `).run(now3, now3, projectId, kind, dedupeKey);
2753
+ return Number(result.changes ?? 0);
2754
+ }
2629
2755
  fail(id, workerId, error, now3 = Date.now()) {
2630
2756
  this.begin();
2631
2757
  try {
@@ -2638,15 +2764,18 @@ var init_maintenance_jobs = __esm({
2638
2764
  return void 0;
2639
2765
  }
2640
2766
  const attempts = Number(current.attempts);
2641
- const exhausted = attempts >= Number(current.max_attempts);
2767
+ const rerunRequested = Number(current.rerun_requested) === 1;
2768
+ const exhausted = attempts >= Number(current.max_attempts) && !rerunRequested;
2642
2769
  const status = exhausted ? "failed" : "retry";
2643
2770
  const runAfter = exhausted ? Number(current.run_after) : now3 + getMaintenanceRetryDelayMs(attempts);
2771
+ const nextAttempts = rerunRequested && attempts >= Number(current.max_attempts) ? 0 : attempts;
2644
2772
  this.db.prepare(`
2645
2773
  UPDATE maintenance_jobs
2646
- SET status = ?, run_after = ?, lease_owner = NULL, lease_expires_at = NULL,
2774
+ SET status = ?, run_after = ?, attempts = ?, rerun_requested = 0,
2775
+ lease_owner = NULL, lease_expires_at = NULL,
2647
2776
  last_error = ?, updated_at = ?
2648
2777
  WHERE id = ?
2649
- `).run(status, runAfter, errorText(error), now3, id);
2778
+ `).run(status, runAfter, nextAttempts, errorText(error), now3, id);
2650
2779
  const updated = this.getRow(id);
2651
2780
  this.commit();
2652
2781
  return rowToJob2(updated);
@@ -2724,12 +2853,16 @@ var init_maintenance_jobs = __esm({
2724
2853
  status: result.status,
2725
2854
  lastError: result.lastError,
2726
2855
  clearLastError: result.clearLastError,
2856
+ progress: result.progress,
2727
2857
  now: now3
2728
2858
  });
2729
2859
  return { state: "rescheduled", job: updated2 };
2730
2860
  }
2731
- const updated = this.store.complete(job.id, this.workerId, now3);
2732
- return { state: "completed", job: updated };
2861
+ if (result?.progress && result.progress.remaining > 0) {
2862
+ throw new Error("maintenance job reported completion with remaining work");
2863
+ }
2864
+ const updated = this.store.complete(job.id, this.workerId, now3, result?.progress);
2865
+ return { state: updated?.status === "pending" ? "rescheduled" : "completed", job: updated };
2733
2866
  } catch (error) {
2734
2867
  const updated = this.store.fail(job.id, this.workerId, error, now3);
2735
2868
  return { state: "failed", job: updated };
@@ -3261,6 +3394,7 @@ function mergeTomlConfig(base, override) {
3261
3394
  llm: { ...base.memory?.llm, ...override.memory?.llm }
3262
3395
  },
3263
3396
  embedding: { ...base.embedding, ...override.embedding },
3397
+ retrieval: { ...base.retrieval, ...override.retrieval },
3264
3398
  rerank: { ...base.rerank, ...override.rerank },
3265
3399
  hooks: { ...base.hooks, ...override.hooks },
3266
3400
  git: { ...base.git, ...override.git },
@@ -3350,6 +3484,32 @@ var init_toml_loader = __esm({
3350
3484
  }
3351
3485
  });
3352
3486
 
3487
+ // src/config/retrieval-strategy.ts
3488
+ function isCjkHeavyQuery(query) {
3489
+ if (!query) return false;
3490
+ const matches = query.match(CJK);
3491
+ return (matches?.length ?? 0) / query.length > 0.3;
3492
+ }
3493
+ function normalizeRetrievalStrategy(value) {
3494
+ if (value === "vector" || value === "hybrid") return value;
3495
+ return void 0;
3496
+ }
3497
+ function firstRetrievalStrategy(fallback, ...values) {
3498
+ for (const value of values) {
3499
+ const normalized = normalizeRetrievalStrategy(value);
3500
+ if (normalized) return normalized;
3501
+ }
3502
+ return fallback;
3503
+ }
3504
+ var CJK;
3505
+ var init_retrieval_strategy = __esm({
3506
+ "src/config/retrieval-strategy.ts"() {
3507
+ "use strict";
3508
+ init_esm_shims();
3509
+ CJK = /[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g;
3510
+ }
3511
+ });
3512
+
3353
3513
  // src/config/resolved-config.ts
3354
3514
  var resolved_config_exports = {};
3355
3515
  __export(resolved_config_exports, {
@@ -3396,7 +3556,8 @@ function getResolvedConfig(options = {}) {
3396
3556
  const isRequesty = memoryLlmProvider === "requesty";
3397
3557
  const isApiRoute = memoryLlmProvider === "apiroute";
3398
3558
  const isCheaperInference = memoryLlmProvider === "cheaperinference";
3399
- const usesPresetKeyOnly = isAtlasCloud || isRequesty || isApiRoute || isCheaperInference;
3559
+ const isRuncrate = memoryLlmProvider === "runcrate";
3560
+ const usesPresetKeyOnly = isAtlasCloud || isRequesty || isApiRoute || isCheaperInference || isRuncrate;
3400
3561
  const memoryLlmApiKey = first(
3401
3562
  process.env.MEMORIX_LLM_API_KEY,
3402
3563
  process.env.MEMORIX_API_KEY,
@@ -3404,7 +3565,7 @@ function getResolvedConfig(options = {}) {
3404
3565
  yaml.llm?.apiKey,
3405
3566
  legacy.llm?.apiKey,
3406
3567
  // Never borrow another provider's credentials for these gateway presets.
3407
- isAtlasCloud ? process.env.ATLASCLOUD_API_KEY : isRequesty ? process.env.REQUESTY_API_KEY : isApiRoute ? process.env.API_ROUTE_API_KEY : isCheaperInference ? process.env.CHEAPER_INFERENCE_API_KEY : process.env.OPENAI_API_KEY,
3568
+ isAtlasCloud ? process.env.ATLASCLOUD_API_KEY : isRequesty ? process.env.REQUESTY_API_KEY : isApiRoute ? process.env.API_ROUTE_API_KEY : isCheaperInference ? process.env.CHEAPER_INFERENCE_API_KEY : isRuncrate ? process.env.RUNCRATE_API_KEY : process.env.OPENAI_API_KEY,
3408
3569
  usesPresetKeyOnly ? void 0 : process.env.ANTHROPIC_API_KEY,
3409
3570
  usesPresetKeyOnly ? void 0 : openRouterMemoryLlmApiKey
3410
3571
  );
@@ -3458,6 +3619,10 @@ function getResolvedConfig(options = {}) {
3458
3619
  apiKey: first(process.env.MEMORIX_EMBEDDING_API_KEY, toml.embedding?.api_key, yaml.embedding?.apiKey, legacy.embeddingApi?.apiKey, openRouterEmbeddingApiKey, requestyEmbeddingApiKey),
3459
3620
  dimensions: firstNumber(parseNumber(process.env.MEMORIX_EMBEDDING_DIMENSIONS), toml.embedding?.dimensions, yaml.embedding?.dimensions, legacy.embeddingApi?.dimensions)
3460
3621
  },
3622
+ retrieval: {
3623
+ cjk: firstRetrievalStrategy("vector", process.env.MEMORIX_RETRIEVAL_CJK, toml.retrieval?.cjk, yaml.retrieval?.cjk),
3624
+ ascii: firstRetrievalStrategy("hybrid", process.env.MEMORIX_RETRIEVAL_ASCII, toml.retrieval?.ascii, yaml.retrieval?.ascii)
3625
+ },
3461
3626
  rerank: resolveRerankLane({
3462
3627
  toml,
3463
3628
  yaml,
@@ -3475,6 +3640,7 @@ function getResolvedConfig(options = {}) {
3475
3640
  codegraph: {
3476
3641
  excludePatterns: firstArray(toml.codegraph?.exclude_patterns, yaml.codegraph?.excludePatterns),
3477
3642
  maxFileBytes: firstNumber(toml.codegraph?.max_file_bytes, yaml.codegraph?.maxFileBytes),
3643
+ autoRefresh: first(toml.codegraph?.auto_refresh, yaml.codegraph?.autoRefresh, "auto"),
3478
3644
  externalContext: first(
3479
3645
  normalizeExternalContext(process.env.MEMORIX_CODEGRAPH_EXTERNAL_CONTEXT),
3480
3646
  toml.codegraph?.external_context,
@@ -3578,6 +3744,8 @@ function getEnvSourceNames() {
3578
3744
  "MEMORIX_EMBEDDING_BASE_URL",
3579
3745
  "MEMORIX_EMBEDDING_MODEL",
3580
3746
  "MEMORIX_EMBEDDING_DIMENSIONS",
3747
+ "MEMORIX_RETRIEVAL_CJK",
3748
+ "MEMORIX_RETRIEVAL_ASCII",
3581
3749
  "MEMORIX_RERANK_PROVIDER",
3582
3750
  "MEMORIX_RERANK_MODEL",
3583
3751
  "MEMORIX_RERANK_BASE_URL",
@@ -3589,6 +3757,7 @@ function getEnvSourceNames() {
3589
3757
  "REQUESTY_API_KEY",
3590
3758
  "API_ROUTE_API_KEY",
3591
3759
  "CHEAPER_INFERENCE_API_KEY",
3760
+ "RUNCRATE_API_KEY",
3592
3761
  "ATLASCLOUD_API_KEY"
3593
3762
  ].filter((name) => process.env[name]);
3594
3763
  }
@@ -3685,6 +3854,7 @@ var init_resolved_config = __esm({
3685
3854
  init_toml_loader();
3686
3855
  init_yaml_loader();
3687
3856
  init_dotenv_loader();
3857
+ init_retrieval_strategy();
3688
3858
  }
3689
3859
  });
3690
3860
 
@@ -4467,8 +4637,8 @@ async function loadCacheJsonl(filePath) {
4467
4637
  loaded = cache3.size;
4468
4638
  } catch {
4469
4639
  }
4470
- if (onDiskCount % 250 === 0) {
4471
- await new Promise((resolve2) => setImmediate(resolve2));
4640
+ if (onDiskCount % CACHE_LOAD_YIELD_EVERY === 0) {
4641
+ await new Promise((resolve2) => setTimeout(resolve2, 0));
4472
4642
  }
4473
4643
  }
4474
4644
  diskCacheEntryCount = onDiskCount;
@@ -4797,6 +4967,12 @@ async function fetchWithRetry(url, apiKey, body, options = {}, attempt = 0, nati
4797
4967
  if (err instanceof Error && (err.name === "AbortError" || controller.signal.aborted || options.signal?.aborted)) {
4798
4968
  throw new Error(`Embedding API timeout after ${timeoutMs}ms: ${url}`);
4799
4969
  }
4970
+ if (options.retry !== false && attempt < MAX_RETRIES2) {
4971
+ const delay3 = BASE_DELAY_MS * Math.pow(2, attempt);
4972
+ console.error(`[memorix] Embedding transport failure, retry ${attempt + 1}/${MAX_RETRIES2} in ${delay3}ms`);
4973
+ await waitForRetry(delay3, options.signal);
4974
+ return fetchWithRetry(url, apiKey, body, options, attempt + 1, nativeGemini);
4975
+ }
4800
4976
  throw err;
4801
4977
  }
4802
4978
  try {
@@ -4875,7 +5051,7 @@ async function waitForRetry(waitMs, signal) {
4875
5051
  abortSignal.addEventListener("abort", onAbort, { once: true });
4876
5052
  });
4877
5053
  }
4878
- var cache3, MAX_CACHE_ENTRIES, MAX_CACHE_PAYLOAD_BYTES, BYTES_PER_DIM, DEFAULT_ASSUMED_DIMENSIONS, MAX_MIGRATION_VALUE_BYTES, cachePayloadBytes3, cacheDimensions, diskCacheEntryCount, diskCacheDirty2, diskSaveTimer, diskCacheLoaded, diskCacheLoadPromise, diskCacheLoadCount, jsonlLineCountCalls, MAX_INPUT_CHARS, MAX_CONCURRENCY, DISK_SAVE_DEBOUNCE_MS, DEFAULT_MAX_BATCH_SIZE, DASHSCOPE_MAX_BATCH_SIZE, MAX_RETRIES2, BASE_DELAY_MS, EmbeddingAPIError, APIEmbeddingProvider;
5054
+ var cache3, MAX_CACHE_ENTRIES, MAX_CACHE_PAYLOAD_BYTES, BYTES_PER_DIM, DEFAULT_ASSUMED_DIMENSIONS, MAX_MIGRATION_VALUE_BYTES, cachePayloadBytes3, cacheDimensions, diskCacheEntryCount, diskCacheDirty2, diskSaveTimer, diskCacheLoaded, diskCacheLoadPromise, diskCacheLoadCount, jsonlLineCountCalls, MAX_INPUT_CHARS, MAX_CONCURRENCY, DISK_SAVE_DEBOUNCE_MS, DEFAULT_MAX_BATCH_SIZE, DASHSCOPE_MAX_BATCH_SIZE, MAX_RETRIES2, BASE_DELAY_MS, CACHE_LOAD_YIELD_EVERY, EmbeddingAPIError, APIEmbeddingProvider;
4879
5055
  var init_api_provider = __esm({
4880
5056
  "src/embedding/api-provider.ts"() {
4881
5057
  "use strict";
@@ -4903,6 +5079,7 @@ var init_api_provider = __esm({
4903
5079
  DASHSCOPE_MAX_BATCH_SIZE = 10;
4904
5080
  MAX_RETRIES2 = 3;
4905
5081
  BASE_DELAY_MS = 500;
5082
+ CACHE_LOAD_YIELD_EVERY = 32;
4906
5083
  EmbeddingAPIError = class extends Error {
4907
5084
  status;
4908
5085
  constructor(status, detail) {
@@ -4954,7 +5131,7 @@ var init_api_provider = __esm({
4954
5131
  console.error(`[memorix] Dimension shortening: ${config.requestedDimensions}d requested`);
4955
5132
  }
4956
5133
  if (allowNetworkProbe) {
4957
- startDiskCacheLoad();
5134
+ setImmediate(startDiskCacheLoad);
4958
5135
  }
4959
5136
  return new _APIEmbeddingProvider(config, probeDimensions);
4960
5137
  }
@@ -5026,10 +5203,8 @@ var init_api_provider = __esm({
5026
5203
  return this.embedInput({ modality: "text", text: normalized }, { intent: "document", ...options });
5027
5204
  }
5028
5205
  const hash4 = textHash2(normalized, this.cacheKeyNamespace);
5029
- if (diskCacheLoaded) {
5030
- const cached = cache3.get(hash4);
5031
- if (cached) return cached;
5032
- }
5206
+ const cached = cache3.get(hash4);
5207
+ if (cached) return cached;
5033
5208
  const apiCall = async () => {
5034
5209
  const body = {
5035
5210
  model: this.config.model,
@@ -5054,8 +5229,8 @@ var init_api_provider = __esm({
5054
5229
  let embedding;
5055
5230
  if (!diskCacheLoaded && diskCacheLoadPromise) {
5056
5231
  const cacheRace = diskCacheLoadPromise.then(() => {
5057
- const cached = cache3.get(hash4);
5058
- if (cached) return cached;
5232
+ const cached2 = cache3.get(hash4);
5233
+ if (cached2) return cached2;
5059
5234
  return null;
5060
5235
  });
5061
5236
  const result = await Promise.race([
@@ -6584,6 +6759,7 @@ var init_provider2 = __esm({
6584
6759
  requesty: { baseUrl: "https://router.requesty.ai/v1", model: "openai/gpt-4.1-nano" },
6585
6760
  apiroute: { baseUrl: "https://global.api-route.com/v1", model: "deepseek-v4.1-flash" },
6586
6761
  cheaperinference: { baseUrl: "https://api.cheaperinference.com/v1", model: "gpt-5.4-mini" },
6762
+ runcrate: { baseUrl: "https://api.runcrate.ai/v1", model: "deepseek-ai/DeepSeek-V4.1-Flash" },
6587
6763
  atlascloud: { baseUrl: "https://api.atlascloud.ai/v1", model: "deepseek-ai/deepseek-v3.2" },
6588
6764
  custom: { baseUrl: "http://localhost:11434/v1", model: "llama3" }
6589
6765
  };
@@ -6760,6 +6936,7 @@ var sqlite_store_exports = {};
6760
6936
  __export(sqlite_store_exports, {
6761
6937
  SqliteBackend: () => SqliteBackend
6762
6938
  });
6939
+ import { randomUUID as randomUUID4 } from "crypto";
6763
6940
  import path7 from "path";
6764
6941
  import fs4 from "fs";
6765
6942
  function obsToRow(obs) {
@@ -7148,6 +7325,32 @@ var init_sqlite_store = __esm({
7148
7325
  }, "Observation atomic write");
7149
7326
  try {
7150
7327
  const tx = {
7328
+ enqueueMaintenanceJob: async (input) => {
7329
+ const payloadJson = JSON.stringify(input.payload ?? {});
7330
+ const existing = this.db.prepare(`
7331
+ SELECT id, status FROM maintenance_jobs
7332
+ WHERE project_id = ? AND kind = ? AND dedupe_key = ?
7333
+ AND status IN ('pending', 'running', 'retry')
7334
+ LIMIT 1
7335
+ `).get(input.projectId, input.kind, input.dedupeKey);
7336
+ if (existing) {
7337
+ if (existing.status === "running") {
7338
+ this.db.prepare(`
7339
+ UPDATE maintenance_jobs
7340
+ SET rerun_requested = 1, payload_json = ?, updated_at = ?
7341
+ WHERE id = ?
7342
+ `).run(payloadJson, Date.now(), existing.id);
7343
+ }
7344
+ return;
7345
+ }
7346
+ const now3 = Date.now();
7347
+ this.db.prepare(`
7348
+ INSERT INTO maintenance_jobs (
7349
+ id, project_id, kind, dedupe_key, payload_json, status, attempts,
7350
+ max_attempts, run_after, created_at, updated_at
7351
+ ) VALUES (?, ?, ?, ?, ?, 'pending', 0, 8, ?, ?, ?)
7352
+ `).run(randomUUID4(), input.projectId, input.kind, input.dedupeKey, payloadJson, now3, now3, now3);
7353
+ },
7151
7354
  loadAll: async () => this.rawLoadAll(),
7152
7355
  getById: async (id) => this.rawGetById(id),
7153
7356
  findByTopicKey: async (projectId, topicKey) => this.rawFindByTopicKey(projectId, topicKey),
@@ -7218,6 +7421,7 @@ __export(obs_store_exports, {
7218
7421
  DegradedBackend: () => DegradedBackend,
7219
7422
  createObservationStore: () => createObservationStore,
7220
7423
  getObservationStore: () => getObservationStore,
7424
+ getObservationStoreDataDir: () => getObservationStoreDataDir,
7221
7425
  initObservationStore: () => initObservationStore,
7222
7426
  resetObservationStore: () => resetObservationStore,
7223
7427
  setObservationStore: () => setObservationStore
@@ -7228,6 +7432,12 @@ function getObservationStore() {
7228
7432
  }
7229
7433
  return _store2;
7230
7434
  }
7435
+ function getObservationStoreDataDir() {
7436
+ if (!_store2 || !_storeDataDir) {
7437
+ throw new Error("[memorix] ObservationStore data directory is not bound");
7438
+ }
7439
+ return _storeDataDir;
7440
+ }
7231
7441
  function setObservationStore(store) {
7232
7442
  _store2 = store;
7233
7443
  }
@@ -7406,6 +7616,9 @@ async function loadLanceDb() {
7406
7616
  return null;
7407
7617
  }
7408
7618
  }
7619
+ async function isSemanticIndexAvailable() {
7620
+ return await loadLanceDb() !== null;
7621
+ }
7409
7622
  function semanticIndexEnabled() {
7410
7623
  return process.env.MEMORIX_SEMANTIC_INDEX !== "off" && process.env.MEMORIX_SEMANTIC_INDEX !== "orama";
7411
7624
  }
@@ -7535,6 +7748,22 @@ async function listSemanticVectorIds(dataDir, profile) {
7535
7748
  const rows = await state.table.query().select(["observation_id"]).toArray();
7536
7749
  return new Set(rows.map((row) => Number(row.observation_id)).filter(Number.isSafeInteger));
7537
7750
  }
7751
+ async function getSemanticIndexStats(dataDir, profile) {
7752
+ const state = await getState(dataDir, profile);
7753
+ if (!state?.table) return null;
7754
+ return {
7755
+ rowCount: await state.table.countRows(),
7756
+ version: typeof state.table.version === "function" ? await state.table.version() : 0
7757
+ };
7758
+ }
7759
+ function optimizeSemanticIndex(dataDir, profile) {
7760
+ const key = stateKey(dataDir, profile);
7761
+ return queueOperation(key, async () => {
7762
+ const state = await getState(dataDir, profile);
7763
+ if (state) await optimizeState(state);
7764
+ mutationCounts.set(key, 0);
7765
+ });
7766
+ }
7538
7767
  function resolveIndexThreshold() {
7539
7768
  const raw = Number.parseInt(process.env.MEMORIX_SEMANTIC_INDEX_THRESHOLD ?? "", 10);
7540
7769
  return Number.isSafeInteger(raw) && raw > 0 ? raw : DEFAULT_INDEX_THRESHOLD;
@@ -7586,6 +7815,20 @@ async function searchSemanticVectors(options) {
7586
7815
  distance: Number(row._distance ?? Number.POSITIVE_INFINITY)
7587
7816
  })).filter((row) => Number.isFinite(row.distance));
7588
7817
  }
7818
+ async function closeSemanticIndexProfile(dataDir, profile) {
7819
+ const key = stateKey(dataDir, profile);
7820
+ await flushPendingVectorBatch(key);
7821
+ await writeQueues.get(key);
7822
+ const state = await statePromises.get(key)?.catch(() => null);
7823
+ try {
7824
+ state?.connection?.close?.();
7825
+ } catch {
7826
+ }
7827
+ statePromises.delete(key);
7828
+ writeQueues.delete(key);
7829
+ indexBuilds.delete(key);
7830
+ mutationCounts.delete(key);
7831
+ }
7589
7832
  var SEMANTIC_INDEX_DIR, TABLE_PREFIX, DEFAULT_INDEX_THRESHOLD, MAX_INDEX_PARTITIONS, DEFAULT_WRITE_BATCH_SIZE, DEFAULT_WRITE_FLUSH_MS, DEFAULT_OPTIMIZE_EVERY, DEFAULT_VERSION_RETENTION_MS, statePromises, writeQueues, indexBuilds, mutationCounts, pendingVectorBatches, availability, requireFromHere2;
7590
7833
  var init_semantic_index = __esm({
7591
7834
  "src/search/semantic-index.ts"() {
@@ -7608,6 +7851,59 @@ var init_semantic_index = __esm({
7608
7851
  }
7609
7852
  });
7610
7853
 
7854
+ // src/search/semantic-view.ts
7855
+ function createSemanticDerivedView(dataDir, profile) {
7856
+ return {
7857
+ async status() {
7858
+ if (!await isSemanticIndexAvailable()) return { state: "unavailable" };
7859
+ const stats = await getSemanticIndexStats(dataDir, profile);
7860
+ return stats ? { state: "ready", generation: stats.version, rowCount: stats.rowCount } : { state: "missing" };
7861
+ },
7862
+ async refresh(records) {
7863
+ if (records.length === 1) await upsertSemanticVector(dataDir, profile, records[0]);
7864
+ else await upsertSemanticVectors(dataDir, profile, records);
7865
+ },
7866
+ rebuild: () => ensureSemanticIndex(dataDir, profile),
7867
+ compact: () => optimizeSemanticIndex(dataDir, profile),
7868
+ close: () => closeSemanticIndexProfile(dataDir, profile)
7869
+ };
7870
+ }
7871
+ var init_semantic_view = __esm({
7872
+ "src/search/semantic-view.ts"() {
7873
+ "use strict";
7874
+ init_esm_shims();
7875
+ init_semantic_index();
7876
+ }
7877
+ });
7878
+
7879
+ // src/core/retrieval-contracts.ts
7880
+ function createRetrievalPlan(options) {
7881
+ const requestedLimit = Number.isFinite(options.limit) ? Math.floor(options.limit ?? 20) : 20;
7882
+ const requestedTokens = Number.isFinite(options.maxTokens) ? Math.floor(options.maxTokens ?? 0) : 0;
7883
+ return {
7884
+ query: options.query.trim(),
7885
+ quality: options.quality ?? "balanced",
7886
+ limit: Math.max(1, Math.min(1e4, requestedLimit)),
7887
+ ...options.projectId ? { projectId: options.projectId } : {},
7888
+ status: options.status ?? "active",
7889
+ ...options.source ? { source: options.source } : {},
7890
+ ...options.type ? { type: options.type } : {},
7891
+ ...options.since ? { since: options.since } : {},
7892
+ ...options.until ? { until: options.until } : {},
7893
+ maxTokens: Math.max(0, requestedTokens),
7894
+ trackAccess: options.trackAccess !== false,
7895
+ reader: options.reader,
7896
+ surfacedIds: [...options.surfacedIds ?? []],
7897
+ signal: options.signal
7898
+ };
7899
+ }
7900
+ var init_retrieval_contracts = __esm({
7901
+ "src/core/retrieval-contracts.ts"() {
7902
+ "use strict";
7903
+ init_esm_shims();
7904
+ }
7905
+ });
7906
+
7611
7907
  // src/search/derived-view-receipt.ts
7612
7908
  function sanitizeDerivedViewFailureReason(reason) {
7613
7909
  const safe = sanitizeCredentials(reason).replace(/(?:[A-Za-z]:[\\/]|\\\\[^\\/\s]+[\\/]|\/(?:home|Users|tmp|var|private|mnt|workspace|workspaces)\/)[^\s"'<>|]*/gi, "[path]").replace(/\s+/g, " ").trim();
@@ -8241,6 +8537,7 @@ var orama_store_exports = {};
8241
8537
  __export(orama_store_exports, {
8242
8538
  _classifyQueryTier: () => classifyQueryTier,
8243
8539
  batchGenerateEmbeddings: () => batchGenerateEmbeddings,
8540
+ countIndexedDocuments: () => countIndexedDocuments,
8244
8541
  createSearchTokenizer: () => createSearchTokenizer,
8245
8542
  generateEmbedding: () => generateEmbedding,
8246
8543
  generateEmbeddingInput: () => generateEmbeddingInput,
@@ -8264,10 +8561,19 @@ __export(orama_store_exports, {
8264
8561
  queueSemanticVector: () => queueSemanticVector,
8265
8562
  removeObservation: () => removeObservation,
8266
8563
  resetDb: () => resetDb,
8564
+ resolveSearchFuzzyTolerance: () => resolveSearchFuzzyTolerance,
8267
8565
  searchObservations: () => searchObservations,
8566
+ searchObservationsDetailed: () => searchObservationsDetailed,
8268
8567
  updateObservationMetadata: () => updateObservationMetadata
8269
8568
  });
8270
8569
  import { components, create, insert as insert2, insertMultiple, search, remove as remove2, update, count, getByID } from "@orama/orama";
8570
+ function resolveSearchFuzzyTolerance(query, quality) {
8571
+ if (quality === "fast") return void 0;
8572
+ const characters = [...query];
8573
+ const cjkCount = characters.filter((char) => /[\u3400-\u4dbf\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]/u.test(char)).length;
8574
+ if (characters.length > 0 && cjkCount / characters.length > 0.3) return void 0;
8575
+ return query.length > 6 ? 2 : 1;
8576
+ }
8271
8577
  function rememberSearchMode(key, value) {
8272
8578
  if (!lastSearchModeByProject.has(key) && lastSearchModeByProject.size >= MAX_SEARCH_MODE_KEYS) {
8273
8579
  const oldest = lastSearchModeByProject.keys().next().value;
@@ -8446,6 +8752,46 @@ async function searchPersistentLexically(options, projectIds, limit2) {
8446
8752
  return null;
8447
8753
  }
8448
8754
  }
8755
+ async function searchLanceInVectorOrder(options, projectIds, limit2, queryVector, provider2) {
8756
+ try {
8757
+ const { getObservationDataDir: getObservationDataDir2 } = await Promise.resolve().then(() => (init_observations(), observations_exports));
8758
+ const dataDir = getObservationDataDir2();
8759
+ if (!dataDir) return null;
8760
+ const vectorHits = await searchSemanticVectors({
8761
+ dataDir,
8762
+ profile: createSemanticIndexProfile(provider2),
8763
+ vector: queryVector,
8764
+ projectId: projectIds ?? options.projectId,
8765
+ status: "all",
8766
+ limit: Math.min(1e4, Math.max(limit2, 1) * 4)
8767
+ });
8768
+ if (!vectorHits || vectorHits.length === 0) return null;
8769
+ const store = getObservationStore();
8770
+ const hits = [];
8771
+ const seen = /* @__PURE__ */ new Set();
8772
+ for (const hit of vectorHits) {
8773
+ if (seen.has(hit.observationId)) continue;
8774
+ seen.add(hit.observationId);
8775
+ const observation = await store.getById(hit.observationId);
8776
+ if (!observation) continue;
8777
+ if (projectIds && !projectIds.includes(observation.projectId)) continue;
8778
+ if (options.status !== "all" && (observation.status ?? "active") !== (options.status ?? "active")) continue;
8779
+ if (options.type && observation.type !== options.type) continue;
8780
+ if (options.source && observation.source !== options.source) continue;
8781
+ const document2 = observationToSearchDocument(observation);
8782
+ hits.push({
8783
+ id: document2.id,
8784
+ score: 1 / (1 + hits.length),
8785
+ document: document2
8786
+ });
8787
+ if (hits.length >= limit2) break;
8788
+ }
8789
+ if (hits.length === 0) return null;
8790
+ return { count: hits.length, hits };
8791
+ } catch {
8792
+ return null;
8793
+ }
8794
+ }
8449
8795
  async function searchPersistentSemantically(options, projectIds, limit2, queryVector, provider2) {
8450
8796
  try {
8451
8797
  const { getObservationDataDir: getObservationDataDir2 } = await Promise.resolve().then(() => (init_observations(), observations_exports));
@@ -8610,6 +8956,9 @@ async function getDb(options = {}) {
8610
8956
  }
8611
8957
  }
8612
8958
  }
8959
+ async function countIndexedDocuments(database) {
8960
+ return count(database ?? await getDb({ allowNetworkProbe: false }));
8961
+ }
8613
8962
  async function resetDb() {
8614
8963
  dbGeneration++;
8615
8964
  db = null;
@@ -8639,7 +8988,7 @@ async function queueSemanticVector(dataDir, record80) {
8639
8988
  const profile = provider2 ? createSemanticIndexProfile(provider2) : null;
8640
8989
  if (!profile) return;
8641
8990
  try {
8642
- await upsertSemanticVector(dataDir, profile, record80);
8991
+ await createSemanticDerivedView(dataDir, profile).refresh([record80]);
8643
8992
  } catch {
8644
8993
  }
8645
8994
  }
@@ -8730,7 +9079,7 @@ async function attachCachedVectors(database, observations2) {
8730
9079
  }
8731
9080
  }
8732
9081
  if (semanticDataDir && semanticProfile && semanticRecords.length > 0) {
8733
- void upsertSemanticVectors(semanticDataDir, semanticProfile, semanticRecords).catch(() => {
9082
+ void createSemanticDerivedView(semanticDataDir, semanticProfile).refresh(semanticRecords).catch(() => {
8734
9083
  });
8735
9084
  }
8736
9085
  await new Promise((resolve2) => setImmediate(resolve2));
@@ -8841,7 +9190,9 @@ async function removeObservation(oramaId) {
8841
9190
  const database = await getDb();
8842
9191
  await remove2(database, oramaId);
8843
9192
  }
8844
- async function searchObservations(options) {
9193
+ async function searchObservationsDetailed(options) {
9194
+ const retrievalPlan = createRetrievalPlan(options);
9195
+ options = { ...options, ...retrievalPlan };
8845
9196
  const searchStartedAt = Date.now();
8846
9197
  const perf = !!process.env.MEMORIX_PERF;
8847
9198
  const t0 = perf ? performance.now() : 0;
@@ -8855,10 +9206,12 @@ async function searchObservations(options) {
8855
9206
  const modeKey = options.projectId ?? SEARCH_MODE_DEFAULT_KEY;
8856
9207
  const quality = options.quality ?? "balanced";
8857
9208
  const database = await getDb();
8858
- rememberSearchMode(
8859
- modeKey,
8860
- quality === "fast" ? "fulltext (fast profile)" : embeddingEnabled ? "hybrid" : "fulltext"
8861
- );
9209
+ let requestMode = quality === "fast" ? "fulltext (fast profile)" : embeddingEnabled ? "hybrid" : "fulltext";
9210
+ const setMode = (mode) => {
9211
+ requestMode = mode;
9212
+ rememberSearchMode(modeKey, mode);
9213
+ };
9214
+ setMode(requestMode);
8862
9215
  let projectIds = null;
8863
9216
  if (options.projectId) {
8864
9217
  try {
@@ -8879,7 +9232,7 @@ async function searchObservations(options) {
8879
9232
  filters["source"] = options.source;
8880
9233
  }
8881
9234
  const hasQuery = options.query && options.query.trim().length > 0;
8882
- const originalQuery = options.query;
9235
+ const originalQuery = retrievalPlan.query;
8883
9236
  const tier = quality === "fast" ? "fast" : hasQuery ? classifyQueryTier(originalQuery) : "fast";
8884
9237
  mark(`tier=${tier}`);
8885
9238
  if (quality === "thorough" && hasQuery) {
@@ -8913,7 +9266,10 @@ async function searchObservations(options) {
8913
9266
  // Fuzzy tolerance: allow 1-char typos for short queries, 2 for longer
8914
9267
  // Fuzzy matching is useful for ordinary recall, but grows sharply with
8915
9268
  // corpus size. The fast profile deliberately uses exact lexical matching.
8916
- ...hasQuery && quality !== "fast" ? { tolerance: originalQuery.length > 6 ? 2 : 1 } : {}
9269
+ ...hasQuery ? (() => {
9270
+ const tolerance = resolveSearchFuzzyTolerance(originalQuery, quality);
9271
+ return tolerance === void 0 ? {} : { tolerance };
9272
+ })() : {}
8917
9273
  };
8918
9274
  let queryVector = null;
8919
9275
  let embeddingProviderForSearch = null;
@@ -8930,10 +9286,7 @@ async function searchObservations(options) {
8930
9286
  embeddingUnavailable = true;
8931
9287
  fallbackUsed = true;
8932
9288
  fallbackReason = "embedding dimension mismatch; lexical search used";
8933
- rememberSearchMode(
8934
- modeKey,
8935
- `fulltext (embedding dimension mismatch: provider ${provider2.dimensions}d vs index ${activeVectorDimensions}d)`
8936
- );
9289
+ setMode(`fulltext (embedding dimension mismatch: provider ${provider2.dimensions}d vs index ${activeVectorDimensions}d)`);
8937
9290
  console.error(
8938
9291
  `[memorix] Embedding provider dimension mismatch (${provider2.dimensions}d provider vs ${activeVectorDimensions}d index); using fulltext search`
8939
9292
  );
@@ -8955,7 +9308,7 @@ async function searchObservations(options) {
8955
9308
  mark("embedding");
8956
9309
  const cjkRatio = (originalQuery.match(/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g) || []).length / originalQuery.length;
8957
9310
  const isCJKHeavy = cjkRatio > 0.3;
8958
- rememberSearchMode(modeKey, "hybrid");
9311
+ setMode("hybrid");
8959
9312
  searchParams = {
8960
9313
  ...searchParams,
8961
9314
  mode: "hybrid",
@@ -8978,32 +9331,41 @@ async function searchObservations(options) {
8978
9331
  embeddingUnavailable = true;
8979
9332
  fallbackUsed = true;
8980
9333
  fallbackReason = "embedding failed or timed out; lexical search used";
8981
- rememberSearchMode(modeKey, "fulltext (embedding unavailable)");
9334
+ setMode("fulltext (embedding unavailable)");
8982
9335
  console.error("[memorix] Embedding failed or timed out, falling back to fulltext search");
8983
9336
  }
8984
9337
  }
8985
9338
  mark("preSearch");
8986
9339
  let results;
9340
+ const retrieval = getResolvedConfig().retrieval;
9341
+ const wantLanceOrder = (isCjkHeavyQuery(originalQuery ?? "") ? retrieval.cjk : retrieval.ascii) === "vector";
9342
+ let lanceOrderUsed = false;
9343
+ let persistent = null;
9344
+ if (wantLanceOrder && queryVector && embeddingProviderForSearch) {
9345
+ persistent = await searchLanceInVectorOrder(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch);
9346
+ if (persistent) lanceOrderUsed = true;
9347
+ else {
9348
+ fallbackUsed = true;
9349
+ fallbackReason = fallbackReason ?? "lance vector index empty; hybrid search used";
9350
+ }
9351
+ }
8987
9352
  const persistentCorpusEligible = await shouldUsePersistentSearch(projectIds, options.projectId);
8988
9353
  const canUsePersistentLexical = persistentCorpusEligible && Boolean(hasQuery) && !queryVector && (quality === "fast" || tier === "fast" || !embeddingEnabled || embeddingUnavailable);
8989
- let persistent = persistentCorpusEligible && queryVector && embeddingProviderForSearch ? await searchPersistentSemantically(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch) : canUsePersistentLexical ? await searchPersistentLexically(options, projectIds, requestLimit) : null;
9354
+ if (!persistent) persistent = persistentCorpusEligible && queryVector && embeddingProviderForSearch ? await searchPersistentSemantically(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch) : canUsePersistentLexical ? await searchPersistentLexically(options, projectIds, requestLimit) : null;
8990
9355
  const durableStore = getOptionalObservationStore();
8991
9356
  if (!persistent && queryVector && durableStore?.hasLexicalIndex?.() && count(database) === 0) {
8992
9357
  persistent = await searchPersistentLexically(options, projectIds, requestLimit);
8993
9358
  }
8994
9359
  if (persistent) {
8995
9360
  results = persistent;
8996
- rememberSearchMode(
8997
- modeKey,
8998
- queryVector ? "hybrid" : quality === "fast" ? "fulltext (fast profile)" : "fulltext"
8999
- );
9361
+ setMode(lanceOrderUsed ? "vector" : queryVector ? "hybrid" : quality === "fast" ? "fulltext (fast profile)" : "fulltext");
9000
9362
  mark(queryVector ? "persistentHybridSearch" : "sqliteFtsSearch");
9001
9363
  } else {
9002
9364
  try {
9003
9365
  results = await search(database, searchParams);
9004
9366
  } catch (error) {
9005
9367
  if (queryVector && isVectorDimensionMismatchError(error)) {
9006
- rememberSearchMode(modeKey, "fulltext (embedding dimension mismatch)");
9368
+ setMode("fulltext (embedding dimension mismatch)");
9007
9369
  console.error("[memorix] Vector search dimension mismatch detected, retrying without embeddings");
9008
9370
  results = await search(database, stripVectorSearchParams(searchParams));
9009
9371
  } else {
@@ -9026,7 +9388,7 @@ async function searchObservations(options) {
9026
9388
  },
9027
9389
  similarity: 0.25
9028
9390
  };
9029
- rememberSearchMode(modeKey, "vector-only (hybrid empty fallback)");
9391
+ setMode("vector-only (hybrid empty fallback)");
9030
9392
  fallbackUsed = true;
9031
9393
  fallbackReason = "hybrid search returned no results; vector-only fallback used";
9032
9394
  results = await search(database, vectorOnlyParams);
@@ -9144,14 +9506,16 @@ async function searchObservations(options) {
9144
9506
  filesModified: doc.filesModified?.split?.("\n") ?? (Array.isArray(doc.filesModified) ? doc.filesModified : [])
9145
9507
  });
9146
9508
  }
9509
+ const topScore = Math.max(...intermediate.map((entry) => entry.score));
9510
+ const affinityTieWindow = topScore * 0.92;
9147
9511
  intermediate = intermediate.map((entry) => {
9148
9512
  const memory = memoryContentMap.get(entry.id);
9149
9513
  if (!memory) return entry;
9150
9514
  const { score: affinityScore } = calculateProjectAffinity(memory, affinityContext);
9515
+ if (entry.score < affinityTieWindow) return entry;
9151
9516
  return {
9152
9517
  ...entry,
9153
- score: entry.score * affinityScore
9154
- // Apply affinity as multiplier
9518
+ score: entry.score * (0.98 + affinityScore * 0.02)
9155
9519
  };
9156
9520
  });
9157
9521
  intermediate.sort((a, b) => b.score - a.score);
@@ -9269,7 +9633,7 @@ async function searchObservations(options) {
9269
9633
  const rerankedTop = neural.map((row) => candidateMap.get(row.id)).filter((entry) => entry != null);
9270
9634
  if (rerankedTop.length > 0) {
9271
9635
  intermediate = [...rerankedTop, ...intermediate.slice(RERANK_TOP_K)];
9272
- rememberSearchMode(modeKey, (lastSearchModeByProject.get(modeKey) ?? "fulltext") + " + neural rerank");
9636
+ setMode(requestMode + " + neural rerank");
9273
9637
  mark("rerank(usedNeural=true)");
9274
9638
  }
9275
9639
  }
@@ -9286,7 +9650,7 @@ async function searchObservations(options) {
9286
9650
  );
9287
9651
  mark(`rerank(usedLLM=${usedLLM})`);
9288
9652
  if (usedLLM) {
9289
- rememberSearchMode(modeKey, (lastSearchModeByProject.get(modeKey) ?? "fulltext") + " + LLM rerank");
9653
+ setMode(requestMode + " + LLM rerank");
9290
9654
  const rerankedTop = reranked.map((row) => candidateMap.get(row.id)).filter((entry) => entry != null);
9291
9655
  if (rerankedTop.length > 0) {
9292
9656
  intermediate = [...rerankedTop, ...intermediate.slice(RERANK_TOP_K)];
@@ -9349,9 +9713,9 @@ async function searchObservations(options) {
9349
9713
  if (options.maxTokens && options.maxTokens > 0) {
9350
9714
  entries = applyTokenBudget(entries, options.maxTokens);
9351
9715
  }
9352
- rememberSearchDiagnostics(modeKey, {
9716
+ const diagnostics = {
9353
9717
  version: "1",
9354
- mode: getLastSearchMode(options.projectId),
9718
+ mode: requestMode,
9355
9719
  rawCandidateCount: results.hits.length,
9356
9720
  candidateCount,
9357
9721
  selectedCount: entries.length,
@@ -9360,14 +9724,25 @@ async function searchObservations(options) {
9360
9724
  fallbackUsed,
9361
9725
  ...fallbackReason ? { fallbackReason } : {},
9362
9726
  elapsedMs: Math.max(0, Date.now() - searchStartedAt)
9363
- });
9364
- if (options.trackAccess !== false) {
9365
- const returnedKeys = new Set(entries.map((entry) => makeEntryKey(entry.projectId, entry.id)));
9727
+ };
9728
+ rememberSearchDiagnostics(modeKey, diagnostics);
9729
+ const recordAccess = (selected) => {
9730
+ if (options.trackAccess === false || selected.length === 0) return;
9731
+ const returnedKeys = new Set(selected.map((entry) => makeEntryKey(entry.projectId, entry.id)));
9366
9732
  const hitDocs = results.hits.map((hit) => ({ id: hit.id, doc: hit.document })).filter(({ doc }) => returnedKeys.has(makeEntryKey(doc.projectId, doc.observationId)));
9367
9733
  recordAccessBatch(hitDocs).catch(() => {
9368
9734
  });
9735
+ };
9736
+ const derivedViews = getSearchDerivedViews();
9737
+ if (fallbackUsed && fallbackReason) {
9738
+ derivedViews.embedding = { freshness: "stale", rebuildStatus: "failed", failureReason: fallbackReason };
9369
9739
  }
9370
- return entries;
9740
+ return { entries, diagnostics, derivedViews, recordAccess };
9741
+ }
9742
+ async function searchObservations(options) {
9743
+ const result = await searchObservationsDetailed(options);
9744
+ result.recordAccess?.(result.entries);
9745
+ return result.entries;
9371
9746
  }
9372
9747
  async function getObservationsByIds(ids, projectId) {
9373
9748
  const database = await getDb();
@@ -9492,6 +9867,10 @@ var init_orama_store = __esm({
9492
9867
  init_policy();
9493
9868
  init_timeout();
9494
9869
  init_obs_store();
9870
+ init_resolved_config();
9871
+ init_retrieval_strategy();
9872
+ init_semantic_view();
9873
+ init_retrieval_contracts();
9495
9874
  init_semantic_index();
9496
9875
  init_derived_view_receipt();
9497
9876
  db = null;
@@ -9686,7 +10065,12 @@ var init_lifecycle = __esm({
9686
10065
  });
9687
10066
 
9688
10067
  // src/store/evidence-store.ts
9689
- import { createHash as createHash5, randomUUID as randomUUID4 } from "crypto";
10068
+ var evidence_store_exports = {};
10069
+ __export(evidence_store_exports, {
10070
+ EvidenceCardStore: () => EvidenceCardStore,
10071
+ buildEvidenceCardId: () => buildEvidenceCardId
10072
+ });
10073
+ import { createHash as createHash5, randomUUID as randomUUID5 } from "crypto";
9690
10074
  function safeJson(value, fallback) {
9691
10075
  if (typeof value !== "string" || value.length === 0) return fallback;
9692
10076
  try {
@@ -9735,6 +10119,9 @@ function sourceKind(observation) {
9735
10119
  if (observation.sourceDetail === "hook") return "hook";
9736
10120
  return observation.source ?? "agent";
9737
10121
  }
10122
+ function buildEvidenceCardId(projectId, candidateKind, candidateId) {
10123
+ return `evidence:${candidateKind}:${projectId}:${candidateId}`;
10124
+ }
9738
10125
  var EvidenceCardStore;
9739
10126
  var init_evidence_store = __esm({
9740
10127
  "src/store/evidence-store.ts"() {
@@ -9875,7 +10262,7 @@ var init_evidence_store = __esm({
9875
10262
  }
9876
10263
  recordEvent(projectId, cardId, kind, detail) {
9877
10264
  const event = {
9878
- id: randomUUID4(),
10265
+ id: randomUUID5(),
9879
10266
  projectId,
9880
10267
  cardId,
9881
10268
  kind,
@@ -9956,7 +10343,7 @@ var init_maintenance_targets = __esm({
9956
10343
  });
9957
10344
 
9958
10345
  // src/knowledge/workspace-store.ts
9959
- import { randomUUID as randomUUID5 } from "crypto";
10346
+ import { randomUUID as randomUUID6 } from "crypto";
9960
10347
  function arrayValue(raw) {
9961
10348
  if (typeof raw !== "string" || !raw) return [];
9962
10349
  try {
@@ -10097,7 +10484,7 @@ var init_workspace_store = __esm({
10097
10484
  }
10098
10485
  createProposal(input) {
10099
10486
  const proposal = {
10100
- id: input.id ?? randomUUID5(),
10487
+ id: input.id ?? randomUUID6(),
10101
10488
  ...input,
10102
10489
  status: input.status ?? "pending",
10103
10490
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
@@ -10383,11 +10770,11 @@ __export(consolidation_exports, {
10383
10770
  });
10384
10771
  function tokenize(text2) {
10385
10772
  return new Set(
10386
- text2.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff\s-]/g, " ").split(/\s+/).filter((t2) => t2.length > 1)
10773
+ text2.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, " ").split(/\s+/).filter((t2) => t2.length > 1)
10387
10774
  );
10388
10775
  }
10389
10776
  function jaccardSimilarity(a, b) {
10390
- if (a.size === 0 && b.size === 0) return 1;
10777
+ if (a.size === 0 && b.size === 0) return 0;
10391
10778
  let intersection = 0;
10392
10779
  for (const token of a) {
10393
10780
  if (b.has(token)) intersection++;
@@ -10764,7 +11151,7 @@ var init_types2 = __esm({
10764
11151
  });
10765
11152
 
10766
11153
  // src/media/asset-store.ts
10767
- import { createHash as createHash7, randomUUID as randomUUID6 } from "crypto";
11154
+ import { createHash as createHash7, randomUUID as randomUUID7 } from "crypto";
10768
11155
  import { copyFile, lstat, mkdir as mkdir3, open, readFile as readFile3, readdir, rename as rename2, rm, stat as stat2, writeFile as writeFile3 } from "fs/promises";
10769
11156
  import path11 from "path";
10770
11157
  function mediaRoot(dataDir) {
@@ -10835,7 +11222,7 @@ async function destinationExists(destination) {
10835
11222
  async function persistBuffer(bytes, destination) {
10836
11223
  await mkdir3(path11.dirname(destination), { recursive: true });
10837
11224
  if (await destinationExists(destination)) return false;
10838
- const temporary = `${destination}.${randomUUID6()}.tmp`;
11225
+ const temporary = `${destination}.${randomUUID7()}.tmp`;
10839
11226
  try {
10840
11227
  await writeFile3(temporary, bytes, { flag: "wx" });
10841
11228
  await rename2(temporary, destination);
@@ -63737,7 +64124,7 @@ var require_gaxios = __commonJS({
63737
64124
  var retry_js_1 = require_retry3();
63738
64125
  var stream_1 = __require("stream");
63739
64126
  var interceptor_js_1 = require_interceptor();
63740
- var randomUUID16 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
64127
+ var randomUUID17 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
63741
64128
  var HTTP_STATUS_NO_CONTENT = 204;
63742
64129
  var Gaxios = class {
63743
64130
  agentCache = /* @__PURE__ */ new Map();
@@ -64010,7 +64397,7 @@ var require_gaxios = __commonJS({
64010
64397
  */
64011
64398
  ["Blob", "File", "FormData"].includes(opts.data?.constructor?.name || "");
64012
64399
  if (opts.multipart?.length) {
64013
- const boundary = await randomUUID16();
64400
+ const boundary = await randomUUID17();
64014
64401
  preparedHeaders.set("content-type", `multipart/related; boundary=${boundary}`);
64015
64402
  opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary));
64016
64403
  } else if (shouldDirectlyPassData) {
@@ -144471,14 +144858,23 @@ var init_video_jobs = __esm({
144471
144858
  }
144472
144859
  });
144473
144860
 
144474
- // src/memory/feedback-model.ts
144861
+ // src/core/retrieval-policy.ts
144475
144862
  function feedbackWeightMultiplier(weight) {
144476
144863
  return Math.max(0.35, Math.min(1.4, 0.35 + Math.max(0, Math.min(2, weight)) * 0.525));
144477
144864
  }
144865
+ var init_retrieval_policy = __esm({
144866
+ "src/core/retrieval-policy.ts"() {
144867
+ "use strict";
144868
+ init_esm_shims();
144869
+ }
144870
+ });
144871
+
144872
+ // src/memory/feedback-model.ts
144478
144873
  var init_feedback_model = __esm({
144479
144874
  "src/memory/feedback-model.ts"() {
144480
144875
  "use strict";
144481
144876
  init_esm_shims();
144877
+ init_retrieval_policy();
144482
144878
  }
144483
144879
  });
144484
144880
 
@@ -144490,7 +144886,7 @@ __export(feedback_exports, {
144490
144886
  applyMemoryFeedback: () => applyMemoryFeedback,
144491
144887
  feedbackWeightMultiplier: () => feedbackWeightMultiplier
144492
144888
  });
144493
- import { randomUUID as randomUUID7 } from "crypto";
144889
+ import { randomUUID as randomUUID8 } from "crypto";
144494
144890
  function applyMemoryFeedback(current, event) {
144495
144891
  const delta = event.signal === "revoke" ? 0 : FEEDBACK_DELTAS[event.signal];
144496
144892
  const weight = Math.max(0, Math.min(2, current.weight + delta));
@@ -144608,7 +145004,7 @@ var init_feedback = __esm({
144608
145004
  if (!target) throw new Error("The feedback event to revoke was not found in the same candidate scope.");
144609
145005
  }
144610
145006
  const event = {
144611
- id: randomUUID7(),
145007
+ id: randomUUID8(),
144612
145008
  projectId: input.projectId,
144613
145009
  candidateKind: input.candidateKind,
144614
145010
  candidateId: input.candidateId,
@@ -144996,7 +145392,7 @@ var init_retention = __esm({
144996
145392
  });
144997
145393
 
144998
145394
  // src/memory/owner.ts
144999
- import { randomUUID as randomUUID8 } from "crypto";
145395
+ import { randomUUID as randomUUID9 } from "crypto";
145000
145396
  import { promises as fs9 } from "fs";
145001
145397
  import path16 from "path";
145002
145398
  function ownerPath(dataDir) {
@@ -145026,7 +145422,7 @@ async function resolveLocalMemoryOwner(dataDir, options = {}) {
145026
145422
  await fs9.mkdir(path16.dirname(filePath), { recursive: true });
145027
145423
  const created = {
145028
145424
  version: 1,
145029
- id: "local-" + randomUUID8(),
145425
+ id: "local-" + randomUUID9(),
145030
145426
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
145031
145427
  };
145032
145428
  try {
@@ -145049,7 +145445,7 @@ var init_owner = __esm({
145049
145445
  });
145050
145446
 
145051
145447
  // src/memory/long-term-store.ts
145052
- import { randomUUID as randomUUID9 } from "crypto";
145448
+ import { randomUUID as randomUUID10 } from "crypto";
145053
145449
  function optionalText2(value) {
145054
145450
  return typeof value === "string" && value.trim() ? value : void 0;
145055
145451
  }
@@ -145209,7 +145605,7 @@ var init_long_term_store = __esm({
145209
145605
  }
145210
145606
  insertEvidence(input) {
145211
145607
  const evidence = {
145212
- id: randomUUID9(),
145608
+ id: randomUUID10(),
145213
145609
  ...input,
145214
145610
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
145215
145611
  };
@@ -145236,7 +145632,7 @@ var init_long_term_store = __esm({
145236
145632
  }
145237
145633
  recordEvent(input) {
145238
145634
  const event = {
145239
- id: randomUUID9(),
145635
+ id: randomUUID10(),
145240
145636
  ...input,
145241
145637
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
145242
145638
  };
@@ -145326,7 +145722,7 @@ __export(long_term_exports, {
145326
145722
  selectLongTermMemoriesForTask: () => selectLongTermMemoriesForTask,
145327
145723
  supersedeLongTermMemory: () => supersedeLongTermMemory
145328
145724
  });
145329
- import { randomUUID as randomUUID10 } from "crypto";
145725
+ import { randomUUID as randomUUID11 } from "crypto";
145330
145726
  function isOneOf(value, values) {
145331
145727
  return typeof value === "string" && values.includes(value);
145332
145728
  }
@@ -145508,7 +145904,7 @@ async function createManualLongTermMemory(input) {
145508
145904
  const owner = await resolveLocalMemoryOwner(input.dataDir, { create: true });
145509
145905
  if (!owner) throw new Error("Memorix could not resolve a local memory owner.");
145510
145906
  assertScope(input.scope);
145511
- const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID10(), relation: "supports" }];
145907
+ const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID11(), relation: "supports" }];
145512
145908
  return createLongTermMemoryWithDataDir({
145513
145909
  dataDir: input.dataDir,
145514
145910
  originProjectId: input.projectId,
@@ -145563,7 +145959,7 @@ async function createLongTermMemoryWithDataDir(input) {
145563
145959
  assertPortableEvidence(input.scope, portability, evidenceInputs);
145564
145960
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
145565
145961
  const memory = {
145566
- id: randomUUID10(),
145962
+ id: randomUUID11(),
145567
145963
  originProjectId: compactText(input.originProjectId, "origin project id", 1e3),
145568
145964
  ownerId: compactText(input.ownerId, "owner id", 160),
145569
145965
  scope: input.scope,
@@ -145918,7 +146314,7 @@ var store_exports = {};
145918
146314
  __export(store_exports, {
145919
146315
  CodeGraphStore: () => CodeGraphStore
145920
146316
  });
145921
- import { randomUUID as randomUUID11 } from "crypto";
146317
+ import { randomUUID as randomUUID12 } from "crypto";
145922
146318
  import { posix as pathPosix } from "path";
145923
146319
  function rowToFile(row) {
145924
146320
  return {
@@ -146847,8 +147243,9 @@ var init_store = __esm({
146847
147243
  * so an interrupted scan cannot be advertised as complete.
146848
147244
  */
146849
147245
  recordCodeStateSnapshot(input) {
146850
- const id = randomUUID11();
147246
+ const id = randomUUID12();
146851
147247
  let snapshot;
147248
+ let compactNeeded = false;
146852
147249
  const tx = this.db.transaction(() => {
146853
147250
  const previous = this.db.prepare(
146854
147251
  "SELECT id, sourceEpoch FROM code_state_snapshots WHERE projectId = ? ORDER BY sourceEpoch DESC LIMIT 1"
@@ -146892,6 +147289,26 @@ var init_store = __esm({
146892
147289
  for (const file of snapshotFileRows) {
146893
147290
  insertSnapshotFile.run(id, file.projectId, file.id, file.path, file.contentHash);
146894
147291
  }
147292
+ const staleSymbolIds = this.db.prepare(
147293
+ "SELECT id FROM code_symbols WHERE projectId = ? AND stale = 1"
147294
+ ).all(input.projectId).map((row) => row.id);
147295
+ if (staleSymbolIds.length > 0) {
147296
+ const placeholders = staleSymbolIds.map(() => "?").join(", ");
147297
+ this.db.prepare(
147298
+ `DELETE FROM code_edges WHERE projectId = ? AND (fromSymbolId IN (${placeholders}) OR toSymbolId IN (${placeholders}))`
147299
+ ).run(input.projectId, ...staleSymbolIds, ...staleSymbolIds);
147300
+ this.db.prepare("DELETE FROM code_symbols WHERE projectId = ? AND stale = 1").run(input.projectId);
147301
+ compactNeeded = true;
147302
+ }
147303
+ const oldSnapshots = this.db.prepare(
147304
+ "SELECT id FROM code_state_snapshots WHERE projectId = ? ORDER BY sourceEpoch DESC LIMIT -1 OFFSET 2"
147305
+ ).all(input.projectId).map((row) => row.id);
147306
+ if (oldSnapshots.length > 0) {
147307
+ const placeholders = oldSnapshots.map(() => "?").join(", ");
147308
+ this.db.prepare(`DELETE FROM code_state_snapshot_files WHERE snapshotId IN (${placeholders})`).run(...oldSnapshots);
147309
+ this.db.prepare(`DELETE FROM code_state_snapshots WHERE id IN (${placeholders})`).run(...oldSnapshots);
147310
+ compactNeeded = true;
147311
+ }
146895
147312
  snapshot = {
146896
147313
  ...input,
146897
147314
  id,
@@ -146900,11 +147317,24 @@ var init_store = __esm({
146900
147317
  };
146901
147318
  });
146902
147319
  tx();
147320
+ if (compactNeeded) this.compactStorage();
146903
147321
  return snapshot;
146904
147322
  }
147323
+ /** Reclaim WAL/free pages after a derived codegraph sweep. */
147324
+ compactStorage() {
147325
+ try {
147326
+ this.db.pragma("wal_checkpoint(TRUNCATE)");
147327
+ } catch {
147328
+ }
147329
+ try {
147330
+ this.db.exec("VACUUM");
147331
+ } catch {
147332
+ }
147333
+ }
146905
147334
  status(projectId) {
146906
147335
  const files = this.db.prepare(`SELECT COUNT(*) AS count FROM code_files WHERE projectId = ?`).get(projectId).count;
146907
147336
  const symbols = this.db.prepare(`SELECT COUNT(*) AS count FROM code_symbols WHERE projectId = ? AND stale = 0`).get(projectId).count;
147337
+ const staleSymbols = this.db.prepare(`SELECT COUNT(*) AS count FROM code_symbols WHERE projectId = ? AND stale = 1`).get(projectId).count;
146908
147338
  const edges = this.db.prepare(`SELECT COUNT(*) AS count FROM code_edges WHERE projectId = ?`).get(projectId).count;
146909
147339
  const refs = this.db.prepare(`SELECT COUNT(*) AS count FROM observation_code_refs WHERE projectId = ?`).get(projectId).count;
146910
147340
  const semanticSymbols = this.db.prepare(`SELECT COUNT(*) AS count FROM code_symbols WHERE projectId = ? AND stale = 0 AND source = 'typescript-compiler'`).get(projectId).count;
@@ -146912,6 +147342,8 @@ var init_store = __esm({
146912
147342
  const parserErrors = this.db.prepare(`SELECT COUNT(*) AS count FROM code_files WHERE projectId = ? AND parserError IS NOT NULL`).get(projectId).count;
146913
147343
  const latest = this.db.prepare(`SELECT MAX(indexedAt) AS indexedAt FROM code_files WHERE projectId = ?`).get(projectId);
146914
147344
  const latestSnapshot = this.latestSnapshot(projectId);
147345
+ const snapshots = this.db.prepare(`SELECT COUNT(*) AS count FROM code_state_snapshots WHERE projectId = ?`).get(projectId).count;
147346
+ const snapshotFiles = this.db.prepare(`SELECT COUNT(*) AS count FROM code_state_snapshot_files WHERE projectId = ?`).get(projectId).count;
146915
147347
  return {
146916
147348
  provider: "lite",
146917
147349
  files,
@@ -146921,6 +147353,9 @@ var init_store = __esm({
146921
147353
  semanticSymbols,
146922
147354
  semanticEdges,
146923
147355
  parserErrors,
147356
+ staleSymbols,
147357
+ snapshots,
147358
+ snapshotFiles,
146924
147359
  ...latest?.indexedAt ? { indexedAt: latest.indexedAt } : {},
146925
147360
  ...latestSnapshot ? { latestSnapshot } : {}
146926
147361
  };
@@ -148041,7 +148476,7 @@ var claim_store_exports = {};
148041
148476
  __export(claim_store_exports, {
148042
148477
  ClaimStore: () => ClaimStore
148043
148478
  });
148044
- import { createHash as createHash12, randomUUID as randomUUID12 } from "crypto";
148479
+ import { createHash as createHash12, randomUUID as randomUUID13 } from "crypto";
148045
148480
  function optionalText3(value) {
148046
148481
  return typeof value === "string" && value ? value : void 0;
148047
148482
  }
@@ -148225,7 +148660,7 @@ var init_claim_store = __esm({
148225
148660
  locator, capturedHash, evidenceKey, createdAt
148226
148661
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
148227
148662
  `).run(
148228
- randomUUID12(),
148663
+ randomUUID13(),
148229
148664
  input.claimId,
148230
148665
  input.evidenceKind,
148231
148666
  input.evidenceId,
@@ -148247,7 +148682,7 @@ var init_claim_store = __esm({
148247
148682
  }
148248
148683
  recordEvent(input) {
148249
148684
  const event = {
148250
- id: randomUUID12(),
148685
+ id: randomUUID13(),
148251
148686
  ...input,
148252
148687
  ...input.detail ? { detail: sanitizeCredentials(input.detail) } : {},
148253
148688
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
@@ -148292,7 +148727,7 @@ __export(claims_exports, {
148292
148727
  supersedeClaim: () => supersedeClaim,
148293
148728
  writeClaim: () => writeClaim
148294
148729
  });
148295
- import { createHash as createHash13, randomUUID as randomUUID13 } from "crypto";
148730
+ import { createHash as createHash13, randomUUID as randomUUID14 } from "crypto";
148296
148731
  function compactText2(value, field) {
148297
148732
  if (typeof value !== "string") throw new Error("Claim " + field + " must be text");
148298
148733
  const sanitized = sanitizeCredentials(value).trim().replace(/\s+/g, " ");
@@ -148378,7 +148813,7 @@ function normalizeClaimInput(input) {
148378
148813
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
148379
148814
  return {
148380
148815
  claim: {
148381
- id: randomUUID13(),
148816
+ id: randomUUID14(),
148382
148817
  projectId,
148383
148818
  subject,
148384
148819
  predicate,
@@ -149463,7 +149898,7 @@ var init_workflow_sync = __esm({
149463
149898
  });
149464
149899
 
149465
149900
  // src/knowledge/workflow-store.ts
149466
- import { randomUUID as randomUUID14 } from "crypto";
149901
+ import { randomUUID as randomUUID15 } from "crypto";
149467
149902
  function parseJson(value, fallback) {
149468
149903
  if (typeof value !== "string" || !value) return fallback;
149469
149904
  try {
@@ -149563,7 +149998,7 @@ var init_workflow_store = __esm({
149563
149998
  }
149564
149999
  recordRun(input) {
149565
150000
  const run = {
149566
- id: randomUUID14(),
150001
+ id: randomUUID15(),
149567
150002
  workflowId: input.workflowId,
149568
150003
  projectId: input.projectId,
149569
150004
  task: input.task.trim(),
@@ -149631,7 +150066,7 @@ var init_outcome_types = __esm({
149631
150066
  });
149632
150067
 
149633
150068
  // src/knowledge/outcome-store.ts
149634
- import { randomUUID as randomUUID15 } from "crypto";
150069
+ import { randomUUID as randomUUID16 } from "crypto";
149635
150070
  function optionalText5(value) {
149636
150071
  return typeof value === "string" && value.trim() ? value : void 0;
149637
150072
  }
@@ -149675,7 +150110,7 @@ var init_outcome_store = __esm({
149675
150110
  }
149676
150111
  record(input) {
149677
150112
  const signal = {
149678
- id: randomUUID15(),
150113
+ id: randomUUID16(),
149679
150114
  projectId: text(input.projectId, "project id"),
149680
150115
  candidateKind: oneOf(input.candidateKind, MEMORY_OUTCOME_CANDIDATE_KINDS, "candidate kind"),
149681
150116
  candidateId: text(input.candidateId, "candidate id"),
@@ -150509,6 +150944,15 @@ function observationId(payload) {
150509
150944
  const value = payload.observationId;
150510
150945
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
150511
150946
  }
150947
+ async function automaticCleanupEnabled(projectRoot) {
150948
+ if (!projectRoot) return true;
150949
+ try {
150950
+ const { getResolvedConfig: getResolvedConfig2 } = await Promise.resolve().then(() => (init_resolved_config(), resolved_config_exports));
150951
+ return getResolvedConfig2({ projectRoot }).memory.autoCleanup !== false;
150952
+ } catch {
150953
+ return true;
150954
+ }
150955
+ }
150512
150956
  function workspaceMode(payload) {
150513
150957
  return payload.workspaceMode === "local" || payload.workspaceMode === "versioned" ? payload.workspaceMode : void 0;
150514
150958
  }
@@ -150597,6 +151041,9 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
150597
151041
  if (job.projectId !== projectId) {
150598
151042
  return { action: "reschedule", delayMs: VECTOR_RETRY_DELAY_MS };
150599
151043
  }
151044
+ if ((job.kind === "retention-archive" || job.kind === "consolidation" || job.kind === "long-term-maintenance") && !await automaticCleanupEnabled(projectRoot)) {
151045
+ return { action: "complete" };
151046
+ }
150600
151047
  if (job.kind === "media-video-generation") {
150601
151048
  const { runMiniMaxVideoGenerationJob: runMiniMaxVideoGenerationJob2 } = await Promise.resolve().then(() => (init_video_jobs(), video_jobs_exports));
150602
151049
  return runMiniMaxVideoGenerationJob2(job, { dataDir: projectDir2, projectId });
@@ -150689,6 +151136,33 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
150689
151136
  });
150690
151137
  return { action: "complete" };
150691
151138
  }
151139
+ if (job.kind === "observation-project") {
151140
+ if (!projectRoot) {
151141
+ throw new Error(`Observation projection requires a project root for ${projectId}`);
151142
+ }
151143
+ const id = observationId(job.payload);
151144
+ if (!id) return { action: "complete" };
151145
+ const [
151146
+ { CodeGraphStore: CodeGraphStore2 },
151147
+ { bindObservationToCode: bindObservationToCode2 },
151148
+ { EvidenceCardStore: EvidenceCardStore2 },
151149
+ { getObservationStore: getObservationStore2 }
151150
+ ] = await Promise.all([
151151
+ Promise.resolve().then(() => (init_store(), store_exports)),
151152
+ Promise.resolve().then(() => (init_binder(), binder_exports)),
151153
+ Promise.resolve().then(() => (init_evidence_store(), evidence_store_exports)),
151154
+ Promise.resolve().then(() => (init_obs_store(), obs_store_exports))
151155
+ ]);
151156
+ const observation = await getObservationStore2().getById(id);
151157
+ if (!observation || observation.projectId !== projectId) return { action: "complete" };
151158
+ const codeStore = new CodeGraphStore2();
151159
+ await codeStore.init(projectDir2);
151160
+ await bindObservationToCode2(codeStore, observation);
151161
+ const evidence = new EvidenceCardStore2();
151162
+ await evidence.init(projectDir2);
151163
+ evidence.upsertObservation(observation);
151164
+ return { action: "complete" };
151165
+ }
150692
151166
  if (job.kind === "observation-qualify") {
150693
151167
  const [
150694
151168
  { CodeGraphStore: CodeGraphStore2 },
@@ -150896,7 +151370,15 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
150896
151370
  const after = getVectorStatus2(projectId);
150897
151371
  if (after.missing === 0) {
150898
151372
  resolveSupersededVectorFailures(projectDir2, projectId);
150899
- return { action: "complete" };
151373
+ return {
151374
+ action: "complete",
151375
+ progress: {
151376
+ attempted: result.attempted,
151377
+ succeeded: result.succeeded,
151378
+ failed: result.failed,
151379
+ remaining: 0
151380
+ }
151381
+ };
150900
151382
  }
150901
151383
  if (result.failed > 0 && result.succeeded === 0) {
150902
151384
  const streak = vectorBackfillFailureStreak(job.payload) + 1;
@@ -150911,6 +151393,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
150911
151393
  ...job.payload,
150912
151394
  vectorBackfillFailureStreak: streak
150913
151395
  },
151396
+ progress: {
151397
+ attempted: result.attempted,
151398
+ succeeded: result.succeeded,
151399
+ failed: result.failed,
151400
+ remaining: after.missing
151401
+ },
150914
151402
  lastError: result.lastError ?? `vector backfill made no progress (${result.failed}/${result.attempted} failed)`
150915
151403
  };
150916
151404
  }
@@ -150920,6 +151408,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
150920
151408
  action: "reschedule",
150921
151409
  delayMs: result.attempted === 0 ? VECTOR_RETRY_DELAY_MS : 0,
150922
151410
  resetAttempts: result.succeeded > 0,
151411
+ progress: {
151412
+ attempted: result.attempted,
151413
+ succeeded: result.succeeded,
151414
+ failed: result.failed,
151415
+ remaining: after.missing
151416
+ },
150923
151417
  ...result.succeeded > 0 ? {
150924
151418
  ...priorFailureStreak > 0 ? { payload } : {},
150925
151419
  ...result.failed > 0 && result.lastError ? { lastError: result.lastError } : priorFailureStreak > 0 ? { clearLastError: true } : {}
@@ -151246,10 +151740,22 @@ function resetObservationRuntime() {
151246
151740
  loadedObservationStore = null;
151247
151741
  embeddingWriteMode = "background";
151248
151742
  embeddingWorkerProjectRoot = void 0;
151249
- vectorMissingIds.clear();
151743
+ clearVectorMissingIds();
151250
151744
  vectorSchemaUpgradePromise = null;
151251
151745
  embeddingFailureLogTimestamps.clear();
151252
151746
  }
151747
+ function markVectorMissing(observationId2, projectId) {
151748
+ vectorMissingIds.add(observationId2);
151749
+ vectorMissingProjectIds.set(observationId2, projectId);
151750
+ }
151751
+ function clearVectorMissing(observationId2) {
151752
+ vectorMissingIds.delete(observationId2);
151753
+ vectorMissingProjectIds.delete(observationId2);
151754
+ }
151755
+ function clearVectorMissingIds() {
151756
+ vectorMissingIds.clear();
151757
+ vectorMissingProjectIds.clear();
151758
+ }
151253
151759
  function logEmbeddingFailureOnce(key, message) {
151254
151760
  const now3 = Date.now();
151255
151761
  const last = embeddingFailureLogTimestamps.get(key) ?? 0;
@@ -151316,24 +151822,40 @@ function queueVectorBackfill(projectId, options = {}) {
151316
151822
  });
151317
151823
  }
151318
151824
  async function bindObservationCodeRefsBestEffort(observation) {
151319
- if (!projectDir) return;
151825
+ if (!projectDir) return true;
151320
151826
  try {
151321
151827
  const { CodeGraphStore: CodeGraphStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
151322
151828
  const { bindObservationToCode: bindObservationToCode2 } = await Promise.resolve().then(() => (init_binder(), binder_exports));
151323
151829
  const codeStore = new CodeGraphStore2();
151324
151830
  await codeStore.init(projectDir);
151325
151831
  await bindObservationToCode2(codeStore, observation);
151832
+ return true;
151326
151833
  } catch {
151834
+ return false;
151327
151835
  }
151328
151836
  }
151329
151837
  async function persistEvidenceCard(observation) {
151330
- if (!projectDir) return;
151838
+ if (!projectDir) return true;
151331
151839
  try {
151332
151840
  const evidence = new EvidenceCardStore();
151333
151841
  await evidence.init(projectDir);
151334
151842
  evidence.upsertObservation(observation);
151843
+ return true;
151335
151844
  } catch (error) {
151336
151845
  console.error(`[memorix] Evidence card projection failed for obs-${observation.id}: ${error instanceof Error ? error.message : String(error)}`);
151846
+ return false;
151847
+ }
151848
+ }
151849
+ async function acknowledgeObservationProjection(observation) {
151850
+ if (!projectDir) return;
151851
+ try {
151852
+ const { MaintenanceJobStore: MaintenanceJobStore2 } = await Promise.resolve().then(() => (init_maintenance_jobs(), maintenance_jobs_exports));
151853
+ new MaintenanceJobStore2(projectDir).acknowledgePending(
151854
+ observation.projectId,
151855
+ "observation-project",
151856
+ "observation-project:" + observation.id
151857
+ );
151858
+ } catch {
151337
151859
  }
151338
151860
  }
151339
151861
  function queueClaimDerivation(observation) {
@@ -151362,6 +151884,41 @@ function queueObservationQualification(observation) {
151362
151884
  } catch {
151363
151885
  }
151364
151886
  }
151887
+ async function enqueueObservationDerivedWork(tx, observation) {
151888
+ if (!tx.enqueueMaintenanceJob) return false;
151889
+ if (!isEmbeddingExplicitlyDisabled()) {
151890
+ await tx.enqueueMaintenanceJob({
151891
+ projectId: observation.projectId,
151892
+ kind: "vector-backfill",
151893
+ dedupeKey: "vector-backfill",
151894
+ payload: { limit: 12 }
151895
+ });
151896
+ }
151897
+ if (observation.admissionState === "candidate") {
151898
+ await tx.enqueueMaintenanceJob({
151899
+ projectId: observation.projectId,
151900
+ kind: "observation-qualify",
151901
+ dedupeKey: "observation-qualify",
151902
+ payload: { source: "automatic-capture:" + observation.id, limit: 100 }
151903
+ });
151904
+ }
151905
+ const claimSource = observation.sourceDetail === "explicit" || observation.source === "git" || observation.sourceDetail === "git-ingest";
151906
+ if (claimSource && resolveObservationVisibility(observation) === "project") {
151907
+ await tx.enqueueMaintenanceJob({
151908
+ projectId: observation.projectId,
151909
+ kind: "claim-derive",
151910
+ dedupeKey: "claim-derive:" + observation.id,
151911
+ payload: { observationId: observation.id }
151912
+ });
151913
+ }
151914
+ await tx.enqueueMaintenanceJob({
151915
+ projectId: observation.projectId,
151916
+ kind: "observation-project",
151917
+ dedupeKey: "observation-project:" + observation.id,
151918
+ payload: { observationId: observation.id }
151919
+ });
151920
+ return true;
151921
+ }
151365
151922
  function isVectorCompatibleWithCurrentIndex(embedding) {
151366
151923
  if (!embedding) return false;
151367
151924
  const vectorDimensions = getVectorDimensions();
@@ -151369,10 +151926,13 @@ function isVectorCompatibleWithCurrentIndex(embedding) {
151369
151926
  }
151370
151927
  async function upgradeVectorSchemaAfterFirstEmbedding(embedding) {
151371
151928
  if (isVectorCompatibleWithCurrentIndex(embedding)) return true;
151372
- if (getVectorDimensions() !== null || !embedding.every(Number.isFinite)) return false;
151929
+ if (!embedding.every(Number.isFinite)) return false;
151373
151930
  const targetProjectDir = projectDir;
151374
151931
  if (!vectorSchemaUpgradePromise) {
151375
- vectorSchemaUpgradePromise = reindexObservations().then(() => projectDir === targetProjectDir && isVectorCompatibleWithCurrentIndex(embedding)).catch(() => false).finally(() => {
151932
+ vectorSchemaUpgradePromise = getDb().then(async () => {
151933
+ if (getVectorDimensions() === null && observations.length > 0) await reindexObservations();
151934
+ return projectDir === targetProjectDir && isVectorCompatibleWithCurrentIndex(embedding);
151935
+ }).catch(() => false).finally(() => {
151376
151936
  vectorSchemaUpgradePromise = null;
151377
151937
  });
151378
151938
  }
@@ -151412,9 +151972,9 @@ async function initObservations(dir, options = {}) {
151412
151972
  }
151413
151973
  function scheduleObservationEmbedding(input) {
151414
151974
  const { observationId: observationId2, projectId, searchableText, doc } = input;
151415
- vectorMissingIds.add(observationId2);
151975
+ markVectorMissing(observationId2, projectId);
151416
151976
  if (isEmbeddingExplicitlyDisabled()) {
151417
- vectorMissingIds.delete(observationId2);
151977
+ clearVectorMissing(observationId2);
151418
151978
  return;
151419
151979
  }
151420
151980
  if (embeddingWriteMode === "deferred") {
@@ -151449,13 +152009,13 @@ function scheduleObservationEmbedding(input) {
151449
152009
  vector: embedding
151450
152010
  });
151451
152011
  }
151452
- vectorMissingIds.delete(observationId2);
152012
+ clearVectorMissing(observationId2);
151453
152013
  } catch {
151454
152014
  console.error(`[memorix] Embedding index update failed for obs-${observationId2} (kept in backfill queue)`);
151455
152015
  queueVectorBackfill(projectId);
151456
152016
  }
151457
152017
  } else if (isEmbeddingExplicitlyDisabled()) {
151458
- vectorMissingIds.delete(observationId2);
152018
+ clearVectorMissing(observationId2);
151459
152019
  } else {
151460
152020
  queueVectorBackfill(projectId);
151461
152021
  logEmbeddingFailureOnce(
@@ -151537,7 +152097,6 @@ async function storeObservation(input) {
151537
152097
  throw new Error("Cannot update a memory outside this session's write scope.");
151538
152098
  }
151539
152099
  const observation2 = await upsertObservation(existing, input, now3);
151540
- await input.onPersisted?.(observation2);
151541
152100
  return { observation: observation2, upserted: true };
151542
152101
  }
151543
152102
  }
@@ -151564,6 +152123,7 @@ async function storeObservation(input) {
151564
152123
  let upsertedInsideLock = false;
151565
152124
  let reloadCacheAfterCommit = false;
151566
152125
  let persistedCallbackInvoked = false;
152126
+ let derivedJobsCommitted = false;
151567
152127
  const assignAndPersist = async () => {
151568
152128
  if (projectDir) {
151569
152129
  const store = getObservationStore();
@@ -151619,6 +152179,7 @@ async function storeObservation(input) {
151619
152179
  writeGeneration: transactionGeneration + 1
151620
152180
  };
151621
152181
  await tx.insert(observation);
152182
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, observation);
151622
152183
  await input.onPersisted?.(observation);
151623
152184
  persistedCallbackInvoked = true;
151624
152185
  await tx.saveIdCounter(id + 1);
@@ -151717,15 +152278,17 @@ async function storeObservation(input) {
151717
152278
  await assignAndPersist();
151718
152279
  if (upsertedInsideLock) {
151719
152280
  const updated = await upsertObservation(observation, input, now3);
151720
- await input.onPersisted?.(updated);
151721
152281
  return { observation: updated, upserted: true };
151722
152282
  }
151723
152283
  if (!persistedCallbackInvoked) await input.onPersisted?.(observation);
151724
- await bindObservationCodeRefsBestEffort(observation);
151725
- await persistEvidenceCard(observation);
151726
- queueObservationQualification(observation);
151727
- if (resolveObservationVisibility(observation) === "project") {
151728
- queueClaimDerivation(observation);
152284
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(observation);
152285
+ const evidenceProjected = await persistEvidenceCard(observation);
152286
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(observation);
152287
+ if (!derivedJobsCommitted) {
152288
+ queueObservationQualification(observation);
152289
+ if (resolveObservationVisibility(observation) === "project") {
152290
+ queueClaimDerivation(observation);
152291
+ }
151729
152292
  }
151730
152293
  scheduleObservationEmbedding({
151731
152294
  observationId: observation.id,
@@ -151747,86 +152310,115 @@ async function upsertObservation(existing, input, now3) {
151747
152310
  }
151748
152311
  const fullText = [input.title, input.narrative, ...input.facts ?? [], ...enrichedFiles, ...enrichedConcepts].join(" ");
151749
152312
  const tokens = countTextTokens(fullText);
151750
- existing.entityName = input.entityName;
151751
- existing.type = input.type;
151752
- existing.title = input.title;
151753
- existing.narrative = input.narrative;
151754
- existing.facts = input.facts ?? [];
151755
- existing.attachments = input.attachments;
151756
- existing.filesModified = enrichedFiles;
151757
- existing.concepts = enrichedConcepts;
151758
- existing.tokens = tokens;
151759
- existing.updatedAt = now3;
151760
- existing.hasCausalLanguage = extracted.hasCausalLanguage;
151761
- existing.revisionCount = (existing.revisionCount ?? 1) + 1;
151762
- existing.status = "active";
151763
- if (input.sessionId) existing.sessionId = input.sessionId;
151764
- if (input.progress) existing.progress = input.progress;
151765
- if (input.sourceDetail !== void 0) existing.sourceDetail = input.sourceDetail;
151766
- if (input.valueCategory !== void 0) existing.valueCategory = input.valueCategory;
151767
- if (input.admissionState !== void 0) existing.admissionState = input.admissionState;
151768
- if (input.admissionReason !== void 0) existing.admissionReason = sanitizeCredentials(input.admissionReason);
151769
- if (input.visibility !== void 0) existing.visibility = input.visibility;
151770
- if (input.sharedWithAgentIds !== void 0) existing.sharedWithAgentIds = input.sharedWithAgentIds;
152313
+ const applyUpdate = (current) => ({
152314
+ ...current,
152315
+ entityName: input.entityName,
152316
+ type: input.type,
152317
+ title: input.title,
152318
+ narrative: input.narrative,
152319
+ facts: input.facts ?? [],
152320
+ attachments: input.attachments,
152321
+ filesModified: enrichedFiles,
152322
+ concepts: enrichedConcepts,
152323
+ tokens,
152324
+ updatedAt: now3,
152325
+ hasCausalLanguage: extracted.hasCausalLanguage,
152326
+ revisionCount: (current.revisionCount ?? 1) + 1,
152327
+ status: "active",
152328
+ ...input.sessionId ? { sessionId: input.sessionId } : {},
152329
+ ...input.progress ? { progress: input.progress } : {},
152330
+ ...input.sourceDetail !== void 0 ? { sourceDetail: input.sourceDetail } : {},
152331
+ ...input.valueCategory !== void 0 ? { valueCategory: input.valueCategory } : {},
152332
+ ...input.admissionState !== void 0 ? { admissionState: input.admissionState } : {},
152333
+ ...input.admissionReason !== void 0 ? { admissionReason: sanitizeCredentials(input.admissionReason) } : {},
152334
+ ...input.visibility !== void 0 ? { visibility: input.visibility } : {},
152335
+ ...input.sharedWithAgentIds !== void 0 ? { sharedWithAgentIds: input.sharedWithAgentIds } : {}
152336
+ });
152337
+ let updated = applyUpdate(existing);
152338
+ let derivedJobsCommitted = false;
152339
+ if (projectDir) {
152340
+ const store = getObservationStore();
152341
+ await store.atomic(async (tx) => {
152342
+ const current = await tx.getById(existing.id);
152343
+ if (!current || current.projectId !== existing.projectId) {
152344
+ throw new Error("Topic observation changed before update");
152345
+ }
152346
+ updated = applyUpdate(current);
152347
+ updated.writeGeneration = await tx.getGeneration() + 1;
152348
+ await tx.update(updated);
152349
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, updated);
152350
+ await input.onPersisted?.(updated);
152351
+ });
152352
+ updated.writeGeneration = store.getGeneration();
152353
+ } else {
152354
+ await input.onPersisted?.(updated);
152355
+ }
152356
+ if (corpusLoaded) {
152357
+ const cacheIndex = observations.findIndex((observation) => observation.id === updated.id);
152358
+ if (cacheIndex >= 0) observations[cacheIndex] = updated;
152359
+ }
151771
152360
  const doc = {
151772
- id: makeOramaObservationId(existing.projectId, existing.id),
151773
- observationId: existing.id,
151774
- entityName: existing.entityName,
151775
- type: existing.type,
151776
- title: existing.title,
151777
- narrative: existing.narrative,
151778
- facts: existing.facts.join("\n"),
152361
+ id: makeOramaObservationId(updated.projectId, updated.id),
152362
+ observationId: updated.id,
152363
+ entityName: updated.entityName,
152364
+ type: updated.type,
152365
+ title: updated.title,
152366
+ narrative: updated.narrative,
152367
+ facts: updated.facts.join("\n"),
151779
152368
  filesModified: enrichedFiles.join("\n"),
151780
152369
  concepts: enrichedConcepts.map((c) => c.replace(/-/g, " ")).join(", "),
151781
- attachments: formatAttachmentProvenance(existing.attachments),
152370
+ attachments: formatAttachmentProvenance(updated.attachments),
151782
152371
  tokens,
151783
- createdAt: existing.createdAt,
151784
- projectId: existing.projectId,
152372
+ createdAt: updated.createdAt,
152373
+ projectId: updated.projectId,
151785
152374
  accessCount: 0,
151786
152375
  lastAccessedAt: "",
151787
152376
  status: "active",
151788
- source: existing.source ?? "agent",
151789
- sourceDetail: existing.sourceDetail ?? "",
151790
- valueCategory: existing.valueCategory ?? "",
151791
- admissionState: existing.admissionState ?? "",
151792
- admissionReason: existing.admissionReason ?? "",
151793
- visibility: existing.visibility ?? "project",
151794
- createdByAgentId: existing.createdByAgentId ?? "",
151795
- sharedWithAgentIds: JSON.stringify(existing.sharedWithAgentIds ?? [])
151796
- };
151797
- const oramaId = makeOramaObservationId(existing.projectId, existing.id);
151798
- try {
151799
- const { removeObservation: removeObservation2 } = await Promise.resolve().then(() => (init_orama_store(), orama_store_exports));
151800
- await removeObservation2(oramaId);
151801
- } catch {
151802
- }
151803
- try {
151804
- await insertObservation(doc);
151805
- } catch {
152377
+ source: updated.source ?? "agent",
152378
+ sourceDetail: updated.sourceDetail ?? "",
152379
+ valueCategory: updated.valueCategory ?? "",
152380
+ admissionState: updated.admissionState ?? "",
152381
+ admissionReason: updated.admissionReason ?? "",
152382
+ visibility: updated.visibility ?? "project",
152383
+ createdByAgentId: updated.createdByAgentId ?? "",
152384
+ sharedWithAgentIds: JSON.stringify(updated.sharedWithAgentIds ?? [])
152385
+ };
152386
+ if (corpusLoaded) {
152387
+ const oramaId = makeOramaObservationId(updated.projectId, updated.id);
151806
152388
  try {
151807
- const { removeObservation: removeObs } = await Promise.resolve().then(() => (init_orama_store(), orama_store_exports));
151808
- await removeObs(oramaId);
152389
+ try {
152390
+ await removeObservation(oramaId);
152391
+ } catch {
152392
+ }
151809
152393
  await insertObservation(doc);
151810
152394
  } catch {
152395
+ try {
152396
+ try {
152397
+ await removeObservation(oramaId);
152398
+ } catch {
152399
+ }
152400
+ await insertObservation(doc);
152401
+ } catch (error) {
152402
+ console.error(`[memorix] Observation index projection failed for obs-${updated.id}: ${sanitizeCredentials(error instanceof Error ? error.message : String(error))}`);
152403
+ }
151811
152404
  }
151812
152405
  }
151813
- if (projectDir) {
151814
- const store = getObservationStore();
151815
- await store.update(existing);
151816
- }
151817
- await bindObservationCodeRefsBestEffort(existing);
151818
- await persistEvidenceCard(existing);
151819
- queueObservationQualification(existing);
151820
- if (resolveObservationVisibility(existing) === "project") {
151821
- queueClaimDerivation(existing);
152406
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(updated);
152407
+ const evidenceProjected = await persistEvidenceCard(updated);
152408
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(updated);
152409
+ if (!derivedJobsCommitted) {
152410
+ queueObservationQualification(updated);
152411
+ if (resolveObservationVisibility(updated) === "project") {
152412
+ queueClaimDerivation(updated);
152413
+ }
151822
152414
  }
151823
152415
  scheduleObservationEmbedding({
151824
- observationId: existing.id,
151825
- projectId: existing.projectId,
152416
+ observationId: updated.id,
152417
+ projectId: updated.projectId,
151826
152418
  searchableText: [input.title, input.narrative, ...input.facts ?? []].join(" "),
151827
152419
  doc
151828
152420
  });
151829
- return existing;
152421
+ return updated;
151830
152422
  }
151831
152423
  function getObservation(id, projectId) {
151832
152424
  return observations.find((o) => o.id === id && (projectId ? o.projectId === projectId : true));
@@ -152015,7 +152607,7 @@ async function reindexObservations() {
152015
152607
  if (observations.length === 0) return 0;
152016
152608
  await resetDb();
152017
152609
  searchIndexPrepared = false;
152018
- vectorMissingIds.clear();
152610
+ clearVectorMissingIds();
152019
152611
  let embeddings = observations.map(() => null);
152020
152612
  const provider2 = await getEmbeddingProvider();
152021
152613
  const canBatchEmbedAtStartup = provider2 !== null && !provider2.name.startsWith("api-");
@@ -152080,7 +152672,7 @@ async function reindexObservations() {
152080
152672
  };
152081
152673
  await insertObservation(doc);
152082
152674
  if (!compatibleEmbedding && !isEmbeddingExplicitlyDisabled()) {
152083
- vectorMissingIds.add(obs.id);
152675
+ markVectorMissing(obs.id, obs.projectId);
152084
152676
  }
152085
152677
  count2++;
152086
152678
  } catch (err) {
@@ -152097,7 +152689,17 @@ async function prepareSearchIndex(options = {}) {
152097
152689
  if (!isEmbeddingExplicitlyDisabled()) {
152098
152690
  const store = getObservationStore();
152099
152691
  const projects = await store.listProjectIds?.() ?? [];
152100
- for (const projectId of projects) queueVectorBackfill(projectId);
152692
+ await getDb({ allowNetworkProbe: false }).catch(() => void 0);
152693
+ const persistedIds = projectDir ? await getPersistentSemanticVectorIds(projectDir).catch(() => null) : null;
152694
+ for (const projectId of projects) {
152695
+ const projectObservations = await store.loadByProject(projectId);
152696
+ for (const observation of projectObservations) {
152697
+ if (!persistedIds?.has(observation.id)) markVectorMissing(observation.id, observation.projectId);
152698
+ }
152699
+ if (projectObservations.some((observation) => !persistedIds?.has(observation.id))) {
152700
+ queueVectorBackfill(projectId);
152701
+ }
152702
+ }
152101
152703
  }
152102
152704
  return 0;
152103
152705
  }
@@ -152111,13 +152713,13 @@ async function prepareSearchIndex(options = {}) {
152111
152713
  const hydratedProjectDir = projectDir;
152112
152714
  const queueMissingVectors = async () => {
152113
152715
  if (!hydratedProjectDir || projectDir !== hydratedProjectDir) return;
152114
- vectorMissingIds.clear();
152716
+ clearVectorMissingIds();
152115
152717
  if (!isEmbeddingExplicitlyDisabled()) {
152116
152718
  const persistedSemanticIds = await getPersistentSemanticVectorIds(hydratedProjectDir).catch(() => null);
152117
152719
  const projectsWithMissingVectors = /* @__PURE__ */ new Set();
152118
152720
  for (const obs of observations) {
152119
152721
  if (!hasObservationVector(obs.projectId, obs.id) && !persistedSemanticIds?.has(obs.id)) {
152120
- vectorMissingIds.add(obs.id);
152722
+ markVectorMissing(obs.id, obs.projectId);
152121
152723
  projectsWithMissingVectors.add(obs.projectId);
152122
152724
  }
152123
152725
  }
@@ -152135,6 +152737,9 @@ async function prepareSearchIndex(options = {}) {
152135
152737
  }
152136
152738
  function getVectorMissingIds(projectId) {
152137
152739
  if (!projectId) return [...vectorMissingIds];
152740
+ if (!corpusLoaded) {
152741
+ return [...vectorMissingIds].filter((id) => vectorMissingProjectIds.get(id) === projectId);
152742
+ }
152138
152743
  const observationById = new Map(observations.map((observation) => [observation.id, observation]));
152139
152744
  return [...vectorMissingIds].filter((id) => observationById.get(id)?.projectId === projectId);
152140
152745
  }
@@ -152157,7 +152762,7 @@ function getSearchIndexStatus(projectId) {
152157
152762
  };
152158
152763
  }
152159
152764
  async function probeSearchIndex(projectId) {
152160
- await searchObservations({
152765
+ const result = await searchObservationsDetailed({
152161
152766
  query: "semantic memory retrieval status",
152162
152767
  projectId,
152163
152768
  reader: { projectId },
@@ -152165,14 +152770,15 @@ async function probeSearchIndex(projectId) {
152165
152770
  status: "all",
152166
152771
  trackAccess: false
152167
152772
  });
152168
- return getLastSearchMode(projectId);
152773
+ return result.diagnostics.mode;
152169
152774
  }
152170
152775
  async function backfillVectorEmbeddings(options = {}) {
152171
152776
  if (vectorBackfillRunning) {
152172
152777
  return { attempted: 0, succeeded: 0, failed: 0 };
152173
152778
  }
152174
152779
  vectorBackfillRunning = true;
152175
- const observationById = new Map(observations.map((observation) => [observation.id, observation]));
152780
+ const sourceObservations = corpusLoaded ? observations : options.projectId ? await getObservationStore().loadByProject(options.projectId, { status: "active" }) : await getObservationStore().loadAll();
152781
+ const observationById = new Map(sourceObservations.map((observation) => [observation.id, observation]));
152176
152782
  const limit2 = Number.isFinite(options.limit) ? Math.max(1, Math.floor(options.limit)) : Number.POSITIVE_INFINITY;
152177
152783
  const ids = [...vectorMissingIds].filter((id) => !options.projectId || observationById.get(id)?.projectId === options.projectId).slice(0, limit2);
152178
152784
  let succeeded = 0;
@@ -152185,7 +152791,7 @@ async function backfillVectorEmbeddings(options = {}) {
152185
152791
  for (const id of ids) {
152186
152792
  const observation = observationById.get(id);
152187
152793
  if (!observation) {
152188
- vectorMissingIds.delete(id);
152794
+ clearVectorMissing(id);
152189
152795
  continue;
152190
152796
  }
152191
152797
  candidates.push({
@@ -152203,7 +152809,7 @@ async function backfillVectorEmbeddings(options = {}) {
152203
152809
  const provider2 = await getEmbeddingProvider();
152204
152810
  if (!provider2) {
152205
152811
  if (isEmbeddingExplicitlyDisabled()) {
152206
- for (const candidate of candidates) vectorMissingIds.delete(candidate.id);
152812
+ for (const candidate of candidates) clearVectorMissing(candidate.id);
152207
152813
  } else {
152208
152814
  recordFailure("embedding provider unavailable");
152209
152815
  failed += candidates.length;
@@ -152280,7 +152886,7 @@ async function backfillVectorEmbeddings(options = {}) {
152280
152886
  vector: embedding
152281
152887
  });
152282
152888
  }
152283
- vectorMissingIds.delete(id);
152889
+ clearVectorMissing(id);
152284
152890
  succeeded++;
152285
152891
  } catch (error) {
152286
152892
  recordFailure(vectorBackfillError(error));
@@ -152305,7 +152911,7 @@ async function backfillVectorEmbeddings(options = {}) {
152305
152911
  ...lastFailure ? { lastError: lastFailure } : {}
152306
152912
  };
152307
152913
  }
152308
- var observations, nextId, projectDir, searchIndexPrepared, embeddingWriteMode, embeddingWorkerProjectRoot, corpusLoaded, largeCorpusLazyMode, loadedObservationStore, DEFAULT_ORAMA_HYDRATION_THRESHOLD, vectorMissingIds, vectorBackfillRunning, vectorSchemaUpgradePromise, lastVectorBackfill, embeddingFailureLogTimestamps, EMBEDDING_FAILURE_LOG_COOLDOWN_MS, MAX_EMBEDDING_FAILURE_KEYS;
152914
+ var observations, nextId, projectDir, searchIndexPrepared, embeddingWriteMode, embeddingWorkerProjectRoot, corpusLoaded, largeCorpusLazyMode, loadedObservationStore, DEFAULT_ORAMA_HYDRATION_THRESHOLD, vectorMissingIds, vectorMissingProjectIds, vectorBackfillRunning, vectorSchemaUpgradePromise, lastVectorBackfill, embeddingFailureLogTimestamps, EMBEDDING_FAILURE_LOG_COOLDOWN_MS, MAX_EMBEDDING_FAILURE_KEYS;
152309
152915
  var init_observations = __esm({
152310
152916
  "src/memory/observations.ts"() {
152311
152917
  "use strict";
@@ -152330,6 +152936,7 @@ var init_observations = __esm({
152330
152936
  loadedObservationStore = null;
152331
152937
  DEFAULT_ORAMA_HYDRATION_THRESHOLD = 1e4;
152332
152938
  vectorMissingIds = /* @__PURE__ */ new Set();
152939
+ vectorMissingProjectIds = /* @__PURE__ */ new Map();
152333
152940
  vectorBackfillRunning = false;
152334
152941
  vectorSchemaUpgradePromise = null;
152335
152942
  lastVectorBackfill = null;