memorix 1.10.3 → 1.10.5

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 (76) hide show
  1. package/CHANGELOG.md +88 -1
  2. package/dist/cli/index.js +2300 -1343
  3. package/dist/index.js +1947 -1139
  4. package/dist/{maintenance-jobs-DVRF-46r.d.ts → maintenance-jobs-DweoCoTT.d.ts} +25 -15
  5. package/dist/maintenance-runner.d.ts +1 -1
  6. package/dist/maintenance-runner.js +915 -221
  7. package/dist/media-audio-runner.js +906 -213
  8. package/dist/media-video-runner.js +914 -221
  9. package/dist/memcode-runtime/CHANGELOG.md +88 -1
  10. package/dist/sdk.js +10153 -9360
  11. package/dist/vector-backfill-runner.d.ts +1 -1
  12. package/dist/vector-backfill-runner.js +914 -221
  13. package/docs/AGENT_OPERATOR_PLAYBOOK.md +7 -0
  14. package/docs/ARCHITECTURE.md +238 -0
  15. package/docs/CONFIGURATION.md +17 -0
  16. package/docs/DESIGN_DECISIONS.md +37 -0
  17. package/docs/DEVELOPMENT.md +8 -1
  18. package/docs/MODULES.md +7 -1
  19. package/docs/PERFORMANCE.md +21 -0
  20. package/docs/README.md +3 -1
  21. package/docs/ROADMAP-1.9.12-2.0.md +18 -2
  22. package/package.json +1 -1
  23. package/plugins/antigravity/memorix/plugin.json +1 -1
  24. package/plugins/claude/memorix/.claude-plugin/plugin.json +1 -1
  25. package/plugins/codebuddy/memorix/.codebuddy-plugin/plugin.json +1 -1
  26. package/plugins/codex/memorix/.codex-plugin/plugin.json +1 -1
  27. package/plugins/copilot/memorix/plugin.json +1 -1
  28. package/plugins/gemini/memorix/gemini-extension.json +1 -1
  29. package/plugins/hermes/memorix/plugin.yaml +1 -1
  30. package/plugins/omp/memorix/package.json +1 -1
  31. package/plugins/openclaw/memorix/.codex-plugin/plugin.json +1 -1
  32. package/plugins/pi/memorix/package.json +1 -1
  33. package/server.json +2 -2
  34. package/src/cli/command-guide.ts +3 -1
  35. package/src/cli/commands/http-session-stream-watch.ts +138 -0
  36. package/src/cli/commands/memory.ts +3 -1
  37. package/src/cli/commands/project-detection-cache.ts +61 -0
  38. package/src/cli/commands/serve-http.ts +63 -13
  39. package/src/cli/index.ts +1 -1
  40. package/src/cli/tui/chat-service.ts +6 -9
  41. package/src/cli/tui/data.ts +2 -2
  42. package/src/codegraph/auto-context.ts +9 -2
  43. package/src/codegraph/derived-view.ts +63 -0
  44. package/src/compact/engine.ts +10 -33
  45. package/src/config/resolved-config.ts +11 -0
  46. package/src/config/retrieval-strategy.ts +22 -0
  47. package/src/config/toml-loader.ts +5 -0
  48. package/src/config/yaml-loader.ts +7 -0
  49. package/src/core/derived-view-registry.ts +33 -0
  50. package/src/core/derived-view.ts +15 -0
  51. package/src/core/maintenance-result.ts +33 -0
  52. package/src/core/retrieval-contracts.ts +57 -0
  53. package/src/core/retrieval-facade.ts +18 -0
  54. package/src/core/retrieval-policy.ts +44 -0
  55. package/src/core/runtime-context.ts +42 -0
  56. package/src/embedding/api-provider.ts +32 -10
  57. package/src/embedding/ollama-embed.ts +118 -0
  58. package/src/knowledge/workset.ts +0 -2
  59. package/src/memory/consolidation.ts +3 -2
  60. package/src/memory/feedback-model.ts +1 -4
  61. package/src/memory/observations.ts +192 -92
  62. package/src/runtime/control-plane-maintenance.ts +1 -0
  63. package/src/runtime/isolated-maintenance.ts +1 -0
  64. package/src/runtime/maintenance-jobs.ts +123 -32
  65. package/src/runtime/project-maintenance.ts +69 -1
  66. package/src/sdk.ts +3 -2
  67. package/src/search/fts-view.ts +53 -0
  68. package/src/search/orama-view.ts +40 -0
  69. package/src/search/retrieval-facade.ts +38 -0
  70. package/src/search/semantic-index.ts +51 -6
  71. package/src/search/semantic-view.ts +34 -0
  72. package/src/server.ts +19 -7
  73. package/src/store/obs-store.ts +15 -0
  74. package/src/store/orama-store.ts +158 -68
  75. package/src/store/sqlite-db.ts +22 -0
  76. package/src/store/sqlite-store.ts +27 -0
@@ -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, {
@@ -3459,6 +3619,10 @@ function getResolvedConfig(options = {}) {
3459
3619
  apiKey: first(process.env.MEMORIX_EMBEDDING_API_KEY, toml.embedding?.api_key, yaml.embedding?.apiKey, legacy.embeddingApi?.apiKey, openRouterEmbeddingApiKey, requestyEmbeddingApiKey),
3460
3620
  dimensions: firstNumber(parseNumber(process.env.MEMORIX_EMBEDDING_DIMENSIONS), toml.embedding?.dimensions, yaml.embedding?.dimensions, legacy.embeddingApi?.dimensions)
3461
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
+ },
3462
3626
  rerank: resolveRerankLane({
3463
3627
  toml,
3464
3628
  yaml,
@@ -3580,6 +3744,8 @@ function getEnvSourceNames() {
3580
3744
  "MEMORIX_EMBEDDING_BASE_URL",
3581
3745
  "MEMORIX_EMBEDDING_MODEL",
3582
3746
  "MEMORIX_EMBEDDING_DIMENSIONS",
3747
+ "MEMORIX_RETRIEVAL_CJK",
3748
+ "MEMORIX_RETRIEVAL_ASCII",
3583
3749
  "MEMORIX_RERANK_PROVIDER",
3584
3750
  "MEMORIX_RERANK_MODEL",
3585
3751
  "MEMORIX_RERANK_BASE_URL",
@@ -3688,6 +3854,7 @@ var init_resolved_config = __esm({
3688
3854
  init_toml_loader();
3689
3855
  init_yaml_loader();
3690
3856
  init_dotenv_loader();
3857
+ init_retrieval_strategy();
3691
3858
  }
3692
3859
  });
3693
3860
 
@@ -4082,6 +4249,96 @@ var init_transformers_provider = __esm({
4082
4249
  }
4083
4250
  });
4084
4251
 
4252
+ // src/embedding/ollama-embed.ts
4253
+ async function routeOllamaEmbedding(url, body, fetchImpl = fetch, probeOptions) {
4254
+ const parsed = parseUrl(url);
4255
+ if (!parsed) return { url, body, rewritten: false };
4256
+ const openAIRoute = parsed.pathname.endsWith("/v1/embeddings");
4257
+ const nativeRoute = parsed.pathname.endsWith("/api/embed");
4258
+ if (!openAIRoute && !nativeRoute) return { url, body, rewritten: false };
4259
+ if (!await originServesOllama(parsed.origin, fetchImpl, probeOptions)) return { url, body, rewritten: false };
4260
+ if (nativeRoute) return { url, body, rewritten: true };
4261
+ parsed.pathname = parsed.pathname.replace(/\/v1\/embeddings$/, "/api/embed");
4262
+ return { url: parsed.toString(), body: withEmbeddingKeepAlive(body), rewritten: true };
4263
+ }
4264
+ async function originServesOllama(origin, fetchImpl = fetch, probeOptions) {
4265
+ const cached = ollamaOrigins.get(origin);
4266
+ if (cached != null) return cached;
4267
+ if (probeOptions?.signal?.aborted) return false;
4268
+ try {
4269
+ const response = await fetchImpl(`${origin}/api/version`, {
4270
+ method: "GET",
4271
+ signal: buildProbeSignal(probeOptions)
4272
+ });
4273
+ if (!response.ok) {
4274
+ ollamaOrigins.set(origin, false);
4275
+ return false;
4276
+ }
4277
+ const detected = isOllamaVersionPayload(await response.json());
4278
+ ollamaOrigins.set(origin, detected);
4279
+ return detected;
4280
+ } catch (err) {
4281
+ if (isAbortError(err) || probeOptions?.signal?.aborted) return false;
4282
+ ollamaOrigins.set(origin, false);
4283
+ return false;
4284
+ }
4285
+ }
4286
+ function mapOllamaEmbeddingResponse(payload) {
4287
+ if (!payload || typeof payload !== "object") return payload;
4288
+ const record80 = payload;
4289
+ if (Array.isArray(record80.data) || !Array.isArray(record80.embeddings)) return payload;
4290
+ const embeddings = record80.embeddings.filter((item) => Array.isArray(item));
4291
+ return {
4292
+ ...record80,
4293
+ object: "list",
4294
+ data: embeddings.map((embedding, index) => ({
4295
+ object: "embedding",
4296
+ index,
4297
+ embedding
4298
+ }))
4299
+ };
4300
+ }
4301
+ function withEmbeddingKeepAlive(body) {
4302
+ if (body.keep_alive != null && body.keep_alive !== "") return body;
4303
+ return { ...body, keep_alive: OLLAMA_EMBED_KEEP_ALIVE };
4304
+ }
4305
+ function isOllamaVersionPayload(payload) {
4306
+ if (!payload || typeof payload !== "object") return false;
4307
+ const version = payload.version;
4308
+ return typeof version === "string" && /^\d+\.\d+\.\d+/.test(version);
4309
+ }
4310
+ function parseUrl(url) {
4311
+ try {
4312
+ return new URL(url);
4313
+ } catch {
4314
+ return null;
4315
+ }
4316
+ }
4317
+ function buildProbeSignal(probeOptions) {
4318
+ const timeoutMs = Math.max(
4319
+ 1,
4320
+ Math.min(
4321
+ typeof probeOptions?.probeTimeoutMs === "number" && Number.isFinite(probeOptions.probeTimeoutMs) ? Math.floor(probeOptions.probeTimeoutMs) : 1e3,
4322
+ 6e4
4323
+ )
4324
+ );
4325
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
4326
+ if (probeOptions?.signal) return AbortSignal.any([probeOptions.signal, timeoutSignal]);
4327
+ return timeoutSignal;
4328
+ }
4329
+ function isAbortError(err) {
4330
+ return err instanceof Error && err.name === "AbortError";
4331
+ }
4332
+ var OLLAMA_EMBED_KEEP_ALIVE, ollamaOrigins;
4333
+ var init_ollama_embed = __esm({
4334
+ "src/embedding/ollama-embed.ts"() {
4335
+ "use strict";
4336
+ init_esm_shims();
4337
+ OLLAMA_EMBED_KEEP_ALIVE = "5m";
4338
+ ollamaOrigins = /* @__PURE__ */ new Map();
4339
+ }
4340
+ });
4341
+
4085
4342
  // src/embedding/api-provider.ts
4086
4343
  var api_provider_exports = {};
4087
4344
  __export(api_provider_exports, {
@@ -4470,8 +4727,8 @@ async function loadCacheJsonl(filePath) {
4470
4727
  loaded = cache3.size;
4471
4728
  } catch {
4472
4729
  }
4473
- if (onDiskCount % 250 === 0) {
4474
- await new Promise((resolve2) => setImmediate(resolve2));
4730
+ if (onDiskCount % CACHE_LOAD_YIELD_EVERY === 0) {
4731
+ await new Promise((resolve2) => setTimeout(resolve2, 0));
4475
4732
  }
4476
4733
  }
4477
4734
  diskCacheEntryCount = onDiskCount;
@@ -4783,8 +5040,18 @@ function parseBatchLimit(error) {
4783
5040
  return null;
4784
5041
  }
4785
5042
  async function fetchWithRetry(url, apiKey, body, options = {}, attempt = 0, nativeGemini = false) {
4786
- const controller = new AbortController();
4787
5043
  const timeoutMs = typeof options.timeoutMs === "number" && Number.isFinite(options.timeoutMs) ? Math.max(100, Math.min(Math.floor(options.timeoutMs), 6e4)) : 1e4;
5044
+ let rewritten = false;
5045
+ if (!nativeGemini) {
5046
+ const routed = await routeOllamaEmbedding(url, body, fetch, {
5047
+ signal: options.signal,
5048
+ probeTimeoutMs: Math.min(1e3, timeoutMs)
5049
+ });
5050
+ url = routed.url;
5051
+ body = routed.body;
5052
+ rewritten = routed.rewritten;
5053
+ }
5054
+ const controller = new AbortController();
4788
5055
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
4789
5056
  const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;
4790
5057
  let response;
@@ -4800,14 +5067,21 @@ async function fetchWithRetry(url, apiKey, body, options = {}, attempt = 0, nati
4800
5067
  if (err instanceof Error && (err.name === "AbortError" || controller.signal.aborted || options.signal?.aborted)) {
4801
5068
  throw new Error(`Embedding API timeout after ${timeoutMs}ms: ${url}`);
4802
5069
  }
5070
+ if (options.retry !== false && attempt < MAX_RETRIES2) {
5071
+ const delay3 = BASE_DELAY_MS * Math.pow(2, attempt);
5072
+ console.error(`[memorix] Embedding transport failure, retry ${attempt + 1}/${MAX_RETRIES2} in ${delay3}ms`);
5073
+ await waitForRetry(delay3, options.signal);
5074
+ return fetchWithRetry(url, apiKey, body, options, attempt + 1, nativeGemini);
5075
+ }
4803
5076
  throw err;
4804
5077
  }
4805
5078
  try {
4806
5079
  if (response.ok) {
4807
- return await raceWithAbort(
5080
+ const payload = await raceWithAbort(
4808
5081
  response.json(),
4809
5082
  signal
4810
5083
  );
5084
+ return rewritten ? mapOllamaEmbeddingResponse(payload) : payload;
4811
5085
  }
4812
5086
  if (options.retry !== false && (response.status === 429 || response.status >= 500) && attempt < MAX_RETRIES2) {
4813
5087
  const delay3 = BASE_DELAY_MS * Math.pow(2, attempt);
@@ -4878,12 +5152,13 @@ async function waitForRetry(waitMs, signal) {
4878
5152
  abortSignal.addEventListener("abort", onAbort, { once: true });
4879
5153
  });
4880
5154
  }
4881
- 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;
5155
+ 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;
4882
5156
  var init_api_provider = __esm({
4883
5157
  "src/embedding/api-provider.ts"() {
4884
5158
  "use strict";
4885
5159
  init_esm_shims();
4886
5160
  init_provider();
5161
+ init_ollama_embed();
4887
5162
  cache3 = /* @__PURE__ */ new Map();
4888
5163
  MAX_CACHE_ENTRIES = 2e5;
4889
5164
  MAX_CACHE_PAYLOAD_BYTES = 256 * 1024 * 1024;
@@ -4906,6 +5181,7 @@ var init_api_provider = __esm({
4906
5181
  DASHSCOPE_MAX_BATCH_SIZE = 10;
4907
5182
  MAX_RETRIES2 = 3;
4908
5183
  BASE_DELAY_MS = 500;
5184
+ CACHE_LOAD_YIELD_EVERY = 32;
4909
5185
  EmbeddingAPIError = class extends Error {
4910
5186
  status;
4911
5187
  constructor(status, detail) {
@@ -4957,7 +5233,7 @@ var init_api_provider = __esm({
4957
5233
  console.error(`[memorix] Dimension shortening: ${config.requestedDimensions}d requested`);
4958
5234
  }
4959
5235
  if (allowNetworkProbe) {
4960
- startDiskCacheLoad();
5236
+ setImmediate(startDiskCacheLoad);
4961
5237
  }
4962
5238
  return new _APIEmbeddingProvider(config, probeDimensions);
4963
5239
  }
@@ -5029,10 +5305,8 @@ var init_api_provider = __esm({
5029
5305
  return this.embedInput({ modality: "text", text: normalized }, { intent: "document", ...options });
5030
5306
  }
5031
5307
  const hash4 = textHash2(normalized, this.cacheKeyNamespace);
5032
- if (diskCacheLoaded) {
5033
- const cached = cache3.get(hash4);
5034
- if (cached) return cached;
5035
- }
5308
+ const cached = cache3.get(hash4);
5309
+ if (cached) return cached;
5036
5310
  const apiCall = async () => {
5037
5311
  const body = {
5038
5312
  model: this.config.model,
@@ -5057,8 +5331,8 @@ var init_api_provider = __esm({
5057
5331
  let embedding;
5058
5332
  if (!diskCacheLoaded && diskCacheLoadPromise) {
5059
5333
  const cacheRace = diskCacheLoadPromise.then(() => {
5060
- const cached = cache3.get(hash4);
5061
- if (cached) return cached;
5334
+ const cached2 = cache3.get(hash4);
5335
+ if (cached2) return cached2;
5062
5336
  return null;
5063
5337
  });
5064
5338
  const result = await Promise.race([
@@ -6764,6 +7038,7 @@ var sqlite_store_exports = {};
6764
7038
  __export(sqlite_store_exports, {
6765
7039
  SqliteBackend: () => SqliteBackend
6766
7040
  });
7041
+ import { randomUUID as randomUUID4 } from "crypto";
6767
7042
  import path7 from "path";
6768
7043
  import fs4 from "fs";
6769
7044
  function obsToRow(obs) {
@@ -7152,6 +7427,32 @@ var init_sqlite_store = __esm({
7152
7427
  }, "Observation atomic write");
7153
7428
  try {
7154
7429
  const tx = {
7430
+ enqueueMaintenanceJob: async (input) => {
7431
+ const payloadJson = JSON.stringify(input.payload ?? {});
7432
+ const existing = this.db.prepare(`
7433
+ SELECT id, status FROM maintenance_jobs
7434
+ WHERE project_id = ? AND kind = ? AND dedupe_key = ?
7435
+ AND status IN ('pending', 'running', 'retry')
7436
+ LIMIT 1
7437
+ `).get(input.projectId, input.kind, input.dedupeKey);
7438
+ if (existing) {
7439
+ if (existing.status === "running") {
7440
+ this.db.prepare(`
7441
+ UPDATE maintenance_jobs
7442
+ SET rerun_requested = 1, payload_json = ?, updated_at = ?
7443
+ WHERE id = ?
7444
+ `).run(payloadJson, Date.now(), existing.id);
7445
+ }
7446
+ return;
7447
+ }
7448
+ const now3 = Date.now();
7449
+ this.db.prepare(`
7450
+ INSERT INTO maintenance_jobs (
7451
+ id, project_id, kind, dedupe_key, payload_json, status, attempts,
7452
+ max_attempts, run_after, created_at, updated_at
7453
+ ) VALUES (?, ?, ?, ?, ?, 'pending', 0, 8, ?, ?, ?)
7454
+ `).run(randomUUID4(), input.projectId, input.kind, input.dedupeKey, payloadJson, now3, now3, now3);
7455
+ },
7155
7456
  loadAll: async () => this.rawLoadAll(),
7156
7457
  getById: async (id) => this.rawGetById(id),
7157
7458
  findByTopicKey: async (projectId, topicKey) => this.rawFindByTopicKey(projectId, topicKey),
@@ -7222,6 +7523,7 @@ __export(obs_store_exports, {
7222
7523
  DegradedBackend: () => DegradedBackend,
7223
7524
  createObservationStore: () => createObservationStore,
7224
7525
  getObservationStore: () => getObservationStore,
7526
+ getObservationStoreDataDir: () => getObservationStoreDataDir,
7225
7527
  initObservationStore: () => initObservationStore,
7226
7528
  resetObservationStore: () => resetObservationStore,
7227
7529
  setObservationStore: () => setObservationStore
@@ -7232,6 +7534,12 @@ function getObservationStore() {
7232
7534
  }
7233
7535
  return _store2;
7234
7536
  }
7537
+ function getObservationStoreDataDir() {
7538
+ if (!_store2 || !_storeDataDir) {
7539
+ throw new Error("[memorix] ObservationStore data directory is not bound");
7540
+ }
7541
+ return _storeDataDir;
7542
+ }
7235
7543
  function setObservationStore(store) {
7236
7544
  _store2 = store;
7237
7545
  }
@@ -7410,6 +7718,9 @@ async function loadLanceDb() {
7410
7718
  return null;
7411
7719
  }
7412
7720
  }
7721
+ async function isSemanticIndexAvailable() {
7722
+ return await loadLanceDb() !== null;
7723
+ }
7413
7724
  function semanticIndexEnabled() {
7414
7725
  return process.env.MEMORIX_SEMANTIC_INDEX !== "off" && process.env.MEMORIX_SEMANTIC_INDEX !== "orama";
7415
7726
  }
@@ -7423,6 +7734,9 @@ async function openState(dataDir, profile) {
7423
7734
  const table = names.includes(name) ? await connection.openTable(name) : null;
7424
7735
  return { key: stateKey(dataDir, profile), dataDir, profile, connection, table };
7425
7736
  }
7737
+ function semanticVectorKey(projectId, observationId2) {
7738
+ return `${projectId}:${Math.trunc(observationId2)}`;
7739
+ }
7426
7740
  function toLanceRow(record80) {
7427
7741
  return {
7428
7742
  observation_id: record80.observationId,
@@ -7493,7 +7807,7 @@ async function mergeVectors(dataDir, profile, records) {
7493
7807
  const state = await getState(dataDir, profile, records);
7494
7808
  if (!state?.table) return;
7495
7809
  const rows = records.map(toLanceRow);
7496
- await state.table.mergeInsert("observation_id").whenMatchedUpdateAll().whenNotMatchedInsertAll().execute(rows);
7810
+ await state.table.mergeInsert(["project_id", "observation_id"]).whenMatchedUpdateAll().whenNotMatchedInsertAll().execute(rows);
7497
7811
  const key = stateKey(dataDir, profile);
7498
7812
  const mutationCount = (mutationCounts.get(key) ?? 0) + 1;
7499
7813
  if (mutationCount >= semanticOptimizeEvery()) {
@@ -7533,11 +7847,34 @@ function upsertSemanticVector(dataDir, profile, record80) {
7533
7847
  function upsertSemanticVectors(dataDir, profile, records) {
7534
7848
  return queueOperation(stateKey(dataDir, profile), () => mergeVectors(dataDir, profile, records));
7535
7849
  }
7536
- async function listSemanticVectorIds(dataDir, profile) {
7850
+ async function listSemanticVectorKeys(dataDir, profile) {
7537
7851
  const state = await getState(dataDir, profile);
7538
7852
  if (!state?.table) return null;
7539
- const rows = await state.table.query().select(["observation_id"]).toArray();
7540
- return new Set(rows.map((row) => Number(row.observation_id)).filter(Number.isSafeInteger));
7853
+ const rows = await state.table.query().select(["observation_id", "project_id"]).toArray();
7854
+ const keys = /* @__PURE__ */ new Set();
7855
+ for (const row of rows) {
7856
+ const observationId2 = Number(row.observation_id);
7857
+ const projectId = String(row.project_id ?? "");
7858
+ if (!Number.isSafeInteger(observationId2) || !projectId) continue;
7859
+ keys.add(semanticVectorKey(projectId, observationId2));
7860
+ }
7861
+ return keys;
7862
+ }
7863
+ async function getSemanticIndexStats(dataDir, profile) {
7864
+ const state = await getState(dataDir, profile);
7865
+ if (!state?.table) return null;
7866
+ return {
7867
+ rowCount: await state.table.countRows(),
7868
+ version: typeof state.table.version === "function" ? await state.table.version() : 0
7869
+ };
7870
+ }
7871
+ function optimizeSemanticIndex(dataDir, profile) {
7872
+ const key = stateKey(dataDir, profile);
7873
+ return queueOperation(key, async () => {
7874
+ const state = await getState(dataDir, profile);
7875
+ if (state) await optimizeState(state);
7876
+ mutationCounts.set(key, 0);
7877
+ });
7541
7878
  }
7542
7879
  function resolveIndexThreshold() {
7543
7880
  const raw = Number.parseInt(process.env.MEMORIX_SEMANTIC_INDEX_THRESHOLD ?? "", 10);
@@ -7590,6 +7927,20 @@ async function searchSemanticVectors(options) {
7590
7927
  distance: Number(row._distance ?? Number.POSITIVE_INFINITY)
7591
7928
  })).filter((row) => Number.isFinite(row.distance));
7592
7929
  }
7930
+ async function closeSemanticIndexProfile(dataDir, profile) {
7931
+ const key = stateKey(dataDir, profile);
7932
+ await flushPendingVectorBatch(key);
7933
+ await writeQueues.get(key);
7934
+ const state = await statePromises.get(key)?.catch(() => null);
7935
+ try {
7936
+ state?.connection?.close?.();
7937
+ } catch {
7938
+ }
7939
+ statePromises.delete(key);
7940
+ writeQueues.delete(key);
7941
+ indexBuilds.delete(key);
7942
+ mutationCounts.delete(key);
7943
+ }
7593
7944
  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;
7594
7945
  var init_semantic_index = __esm({
7595
7946
  "src/search/semantic-index.ts"() {
@@ -7612,6 +7963,59 @@ var init_semantic_index = __esm({
7612
7963
  }
7613
7964
  });
7614
7965
 
7966
+ // src/search/semantic-view.ts
7967
+ function createSemanticDerivedView(dataDir, profile) {
7968
+ return {
7969
+ async status() {
7970
+ if (!await isSemanticIndexAvailable()) return { state: "unavailable" };
7971
+ const stats = await getSemanticIndexStats(dataDir, profile);
7972
+ return stats ? { state: "ready", generation: stats.version, rowCount: stats.rowCount } : { state: "missing" };
7973
+ },
7974
+ async refresh(records) {
7975
+ if (records.length === 1) await upsertSemanticVector(dataDir, profile, records[0]);
7976
+ else await upsertSemanticVectors(dataDir, profile, records);
7977
+ },
7978
+ rebuild: () => ensureSemanticIndex(dataDir, profile),
7979
+ compact: () => optimizeSemanticIndex(dataDir, profile),
7980
+ close: () => closeSemanticIndexProfile(dataDir, profile)
7981
+ };
7982
+ }
7983
+ var init_semantic_view = __esm({
7984
+ "src/search/semantic-view.ts"() {
7985
+ "use strict";
7986
+ init_esm_shims();
7987
+ init_semantic_index();
7988
+ }
7989
+ });
7990
+
7991
+ // src/core/retrieval-contracts.ts
7992
+ function createRetrievalPlan(options) {
7993
+ const requestedLimit = Number.isFinite(options.limit) ? Math.floor(options.limit ?? 20) : 20;
7994
+ const requestedTokens = Number.isFinite(options.maxTokens) ? Math.floor(options.maxTokens ?? 0) : 0;
7995
+ return {
7996
+ query: options.query.trim(),
7997
+ quality: options.quality ?? "balanced",
7998
+ limit: Math.max(1, Math.min(1e4, requestedLimit)),
7999
+ ...options.projectId ? { projectId: options.projectId } : {},
8000
+ status: options.status ?? "active",
8001
+ ...options.source ? { source: options.source } : {},
8002
+ ...options.type ? { type: options.type } : {},
8003
+ ...options.since ? { since: options.since } : {},
8004
+ ...options.until ? { until: options.until } : {},
8005
+ maxTokens: Math.max(0, requestedTokens),
8006
+ trackAccess: options.trackAccess !== false,
8007
+ reader: options.reader,
8008
+ surfacedIds: [...options.surfacedIds ?? []],
8009
+ signal: options.signal
8010
+ };
8011
+ }
8012
+ var init_retrieval_contracts = __esm({
8013
+ "src/core/retrieval-contracts.ts"() {
8014
+ "use strict";
8015
+ init_esm_shims();
8016
+ }
8017
+ });
8018
+
7615
8019
  // src/search/derived-view-receipt.ts
7616
8020
  function sanitizeDerivedViewFailureReason(reason) {
7617
8021
  const safe = sanitizeCredentials(reason).replace(/(?:[A-Za-z]:[\\/]|\\\\[^\\/\s]+[\\/]|\/(?:home|Users|tmp|var|private|mnt|workspace|workspaces)\/)[^\s"'<>|]*/gi, "[path]").replace(/\s+/g, " ").trim();
@@ -7647,6 +8051,37 @@ var init_derived_view_receipt = __esm({
7647
8051
  }
7648
8052
  });
7649
8053
 
8054
+ // src/core/derived-view-registry.ts
8055
+ var DerivedViewRegistry;
8056
+ var init_derived_view_registry = __esm({
8057
+ "src/core/derived-view-registry.ts"() {
8058
+ "use strict";
8059
+ init_esm_shims();
8060
+ DerivedViewRegistry = class {
8061
+ readers = /* @__PURE__ */ new Map();
8062
+ register(name, reader) {
8063
+ const normalized = name.trim();
8064
+ if (!normalized) throw new Error("Derived view name must not be empty");
8065
+ this.readers.set(normalized, reader);
8066
+ return () => {
8067
+ if (this.readers.get(normalized) === reader) this.readers.delete(normalized);
8068
+ };
8069
+ }
8070
+ snapshot() {
8071
+ const result = {};
8072
+ for (const [name, reader] of this.readers) {
8073
+ try {
8074
+ result[name] = reader();
8075
+ } catch {
8076
+ result[name] = { state: "degraded", reason: "derived view reader failed" };
8077
+ }
8078
+ }
8079
+ return result;
8080
+ }
8081
+ };
8082
+ }
8083
+ });
8084
+
7650
8085
  // src/project/aliases.ts
7651
8086
  var aliases_exports = {};
7652
8087
  __export(aliases_exports, {
@@ -8245,6 +8680,7 @@ var orama_store_exports = {};
8245
8680
  __export(orama_store_exports, {
8246
8681
  _classifyQueryTier: () => classifyQueryTier,
8247
8682
  batchGenerateEmbeddings: () => batchGenerateEmbeddings,
8683
+ countIndexedDocuments: () => countIndexedDocuments,
8248
8684
  createSearchTokenizer: () => createSearchTokenizer,
8249
8685
  generateEmbedding: () => generateEmbedding,
8250
8686
  generateEmbeddingInput: () => generateEmbeddingInput,
@@ -8270,6 +8706,7 @@ __export(orama_store_exports, {
8270
8706
  resetDb: () => resetDb,
8271
8707
  resolveSearchFuzzyTolerance: () => resolveSearchFuzzyTolerance,
8272
8708
  searchObservations: () => searchObservations,
8709
+ searchObservationsDetailed: () => searchObservationsDetailed,
8273
8710
  updateObservationMetadata: () => updateObservationMetadata
8274
8711
  });
8275
8712
  import { components, create, insert as insert2, insertMultiple, search, remove as remove2, update, count, getByID } from "@orama/orama";
@@ -8296,15 +8733,17 @@ function getLastSearchDiagnostics(projectId) {
8296
8733
  return diagnostics ? { ...diagnostics } : void 0;
8297
8734
  }
8298
8735
  function getSearchDerivedViews() {
8299
- const views = {};
8736
+ return searchDerivedViewRegistry.snapshot();
8737
+ }
8738
+ function readFtsDerivedViewReceipt() {
8300
8739
  const store = getOptionalObservationStore();
8301
8740
  if (store) {
8302
8741
  try {
8303
8742
  const generation = store.getGeneration();
8304
8743
  if (store.hasLexicalIndex?.()) {
8305
- views.fts = { generation, freshness: "current", rebuildStatus: "idle" };
8744
+ return { generation, freshness: "current", rebuildStatus: "idle" };
8306
8745
  } else {
8307
- views.fts = {
8746
+ return {
8308
8747
  generation,
8309
8748
  freshness: "unknown",
8310
8749
  rebuildStatus: "unavailable",
@@ -8314,32 +8753,34 @@ function getSearchDerivedViews() {
8314
8753
  };
8315
8754
  }
8316
8755
  } catch (error) {
8317
- views.fts = {
8756
+ return {
8318
8757
  freshness: "unknown",
8319
8758
  rebuildStatus: "failed",
8320
8759
  failureReason: sanitizeDerivedViewFailureReason(error instanceof Error ? error.message : String(error))
8321
8760
  };
8322
8761
  }
8323
- } else {
8324
- views.fts = {
8325
- freshness: "unknown",
8326
- rebuildStatus: "unavailable",
8327
- failureReason: "observation store is not initialized"
8328
- };
8329
8762
  }
8330
- views.orama = db ? { generation: dbGeneration, freshness: "current", rebuildStatus: "idle" } : {
8763
+ return {
8764
+ freshness: "unknown",
8765
+ rebuildStatus: "unavailable",
8766
+ failureReason: "observation store is not initialized"
8767
+ };
8768
+ }
8769
+ function readOramaDerivedViewReceipt() {
8770
+ return db ? { generation: dbGeneration, freshness: "current", rebuildStatus: "idle" } : {
8331
8771
  generation: dbGeneration,
8332
8772
  freshness: "unknown",
8333
8773
  rebuildStatus: "unavailable",
8334
8774
  failureReason: "Orama index is not initialized"
8335
8775
  };
8776
+ }
8777
+ function readEmbeddingDerivedViewReceipt() {
8336
8778
  let embeddingHealth;
8337
8779
  try {
8338
8780
  embeddingHealth = getEmbeddingRuntimeHealth?.();
8339
8781
  } catch {
8340
8782
  }
8341
- views.embedding = embeddingHealthReceipt(embeddingHealth, embeddingEnabled);
8342
- return views;
8783
+ return embeddingHealthReceipt(embeddingHealth, embeddingEnabled);
8343
8784
  }
8344
8785
  function rememberSearchDiagnostics(key, value) {
8345
8786
  if (!lastSearchDiagnosticsByProject.has(key) && lastSearchDiagnosticsByProject.size >= MAX_SEARCH_MODE_KEYS) {
@@ -8458,6 +8899,48 @@ async function searchPersistentLexically(options, projectIds, limit2) {
8458
8899
  return null;
8459
8900
  }
8460
8901
  }
8902
+ async function searchLanceInVectorOrder(options, projectIds, limit2, queryVector, provider2) {
8903
+ try {
8904
+ const { getObservationDataDir: getObservationDataDir2 } = await Promise.resolve().then(() => (init_observations(), observations_exports));
8905
+ const dataDir = getObservationDataDir2();
8906
+ if (!dataDir) return null;
8907
+ const vectorHits = await searchSemanticVectors({
8908
+ dataDir,
8909
+ profile: createSemanticIndexProfile(provider2),
8910
+ vector: queryVector,
8911
+ projectId: projectIds ?? options.projectId,
8912
+ status: "all",
8913
+ limit: Math.min(1e4, Math.max(limit2, 1) * 4)
8914
+ });
8915
+ if (!vectorHits || vectorHits.length === 0) return null;
8916
+ const store = getObservationStore();
8917
+ const hits = [];
8918
+ const seen = /* @__PURE__ */ new Set();
8919
+ for (const hit of vectorHits) {
8920
+ if (projectIds ? !projectIds.includes(hit.projectId) : options.projectId && hit.projectId !== options.projectId) continue;
8921
+ const key = semanticVectorKey(hit.projectId, hit.observationId);
8922
+ if (seen.has(key)) continue;
8923
+ seen.add(key);
8924
+ const observation = await store.getById(hit.observationId);
8925
+ if (!observation || observation.projectId !== hit.projectId) continue;
8926
+ if (projectIds && !projectIds.includes(observation.projectId)) continue;
8927
+ if (options.status !== "all" && (observation.status ?? "active") !== (options.status ?? "active")) continue;
8928
+ if (options.type && observation.type !== options.type) continue;
8929
+ if (options.source && observation.source !== options.source) continue;
8930
+ const document2 = observationToSearchDocument(observation);
8931
+ hits.push({
8932
+ id: document2.id,
8933
+ score: 1 / (1 + hits.length),
8934
+ document: document2
8935
+ });
8936
+ if (hits.length >= limit2) break;
8937
+ }
8938
+ if (hits.length === 0) return null;
8939
+ return { count: hits.length, hits };
8940
+ } catch {
8941
+ return null;
8942
+ }
8943
+ }
8461
8944
  async function searchPersistentSemantically(options, projectIds, limit2, queryVector, provider2) {
8462
8945
  try {
8463
8946
  const { getObservationDataDir: getObservationDataDir2 } = await Promise.resolve().then(() => (init_observations(), observations_exports));
@@ -8485,14 +8968,15 @@ async function searchPersistentSemantically(options, projectIds, limit2, queryVe
8485
8968
  documents.set(makeEntryKey(hit.document.projectId, hit.document.observationId), hit.document);
8486
8969
  }
8487
8970
  const vectorObservations = await Promise.all(vectorHits.map(async (hit) => {
8971
+ if (projectIds ? !projectIds.includes(hit.projectId) : options.projectId && hit.projectId !== options.projectId) return null;
8488
8972
  const observation = await store.getById(hit.observationId);
8489
- if (!observation) return null;
8973
+ if (!observation || observation.projectId !== hit.projectId) return null;
8490
8974
  if (projectIds && !projectIds.includes(observation.projectId)) return null;
8491
8975
  if (options.status !== "all" && (observation.status ?? "active") !== (options.status ?? "active")) return null;
8492
8976
  if (options.type && observation.type !== options.type) return null;
8493
8977
  if (options.source && observation.source !== options.source) return null;
8494
8978
  addObservation(observation);
8495
- vectorDocumentKeys.set(hit.observationId, makeEntryKey(observation.projectId, observation.id));
8979
+ vectorDocumentKeys.set(semanticVectorKey(hit.projectId, hit.observationId), makeEntryKey(observation.projectId, observation.id));
8496
8980
  return observation;
8497
8981
  }));
8498
8982
  const RRF_K = 60;
@@ -8502,7 +8986,8 @@ async function searchPersistentSemantically(options, projectIds, limit2, queryVe
8502
8986
  scores.set(key, (scores.get(key) ?? 0) + 0.6 / (RRF_K + index + 1));
8503
8987
  }
8504
8988
  for (const [index, hit] of vectorHits.entries()) {
8505
- const key = vectorDocumentKeys.get(hit.observationId) ?? makeEntryKey(hit.projectId, hit.observationId);
8989
+ const key = vectorDocumentKeys.get(semanticVectorKey(hit.projectId, hit.observationId));
8990
+ if (!key) continue;
8506
8991
  if (!documents.has(key)) continue;
8507
8992
  scores.set(key, (scores.get(key) ?? 0) + 0.4 / (RRF_K + index + 1));
8508
8993
  }
@@ -8515,8 +9000,8 @@ async function searchPersistentSemantically(options, projectIds, limit2, queryVe
8515
9000
  return {
8516
9001
  count: vectorHits.length,
8517
9002
  hits: vectorHits.map((hit, index) => {
8518
- const key = vectorDocumentKeys.get(hit.observationId) ?? makeEntryKey(hit.projectId, hit.observationId);
8519
- const document2 = documents.get(key);
9003
+ const key = vectorDocumentKeys.get(semanticVectorKey(hit.projectId, hit.observationId));
9004
+ const document2 = key ? documents.get(key) : void 0;
8520
9005
  return document2 ? { id: document2.id, score: 0.4 / (RRF_K + index + 1), document: document2 } : null;
8521
9006
  }).filter((hit) => hit !== null).slice(0, limit2)
8522
9007
  };
@@ -8622,6 +9107,9 @@ async function getDb(options = {}) {
8622
9107
  }
8623
9108
  }
8624
9109
  }
9110
+ async function countIndexedDocuments(database) {
9111
+ return count(database ?? await getDb({ allowNetworkProbe: false }));
9112
+ }
8625
9113
  async function resetDb() {
8626
9114
  dbGeneration++;
8627
9115
  db = null;
@@ -8644,14 +9132,14 @@ function getActiveSemanticIndexProfile() {
8644
9132
  }
8645
9133
  async function getPersistentSemanticVectorIds(dataDir) {
8646
9134
  if (!indexEmbeddingProvider) return null;
8647
- return listSemanticVectorIds(dataDir, createSemanticIndexProfile(indexEmbeddingProvider));
9135
+ return listSemanticVectorKeys(dataDir, createSemanticIndexProfile(indexEmbeddingProvider));
8648
9136
  }
8649
9137
  async function queueSemanticVector(dataDir, record80) {
8650
9138
  const provider2 = indexEmbeddingProvider ?? await getEmbeddingProvider();
8651
9139
  const profile = provider2 ? createSemanticIndexProfile(provider2) : null;
8652
9140
  if (!profile) return;
8653
9141
  try {
8654
- await upsertSemanticVector(dataDir, profile, record80);
9142
+ await createSemanticDerivedView(dataDir, profile).refresh([record80]);
8655
9143
  } catch {
8656
9144
  }
8657
9145
  }
@@ -8713,7 +9201,7 @@ function isCompatibleCachedVector(vector) {
8713
9201
  async function attachCachedVectors(database, observations2) {
8714
9202
  const semanticDataDir = (await Promise.resolve().then(() => (init_observations(), observations_exports))).getObservationDataDir();
8715
9203
  const semanticProfile = getActiveSemanticIndexProfile();
8716
- const persistedSemanticIds = semanticDataDir && semanticProfile ? await listSemanticVectorIds(semanticDataDir, semanticProfile).catch(() => null) : null;
9204
+ const persistedSemanticIds = semanticDataDir && semanticProfile ? await listSemanticVectorKeys(semanticDataDir, semanticProfile).catch(() => null) : null;
8717
9205
  const batchSize = 200;
8718
9206
  for (let start = 0; start < observations2.length; start += batchSize) {
8719
9207
  const batch = observations2.slice(start, start + batchSize);
@@ -8724,7 +9212,7 @@ async function attachCachedVectors(database, observations2) {
8724
9212
  const vector = cachedVectors[index];
8725
9213
  if (!isCompatibleCachedVector(vector)) continue;
8726
9214
  const observation = batch[index];
8727
- if (semanticDataDir && semanticProfile && !persistedSemanticIds?.has(observation.id)) {
9215
+ if (semanticDataDir && semanticProfile && !persistedSemanticIds?.has(semanticVectorKey(observation.projectId, observation.id))) {
8728
9216
  semanticRecords.push({
8729
9217
  observationId: observation.id,
8730
9218
  projectId: observation.projectId,
@@ -8742,7 +9230,7 @@ async function attachCachedVectors(database, observations2) {
8742
9230
  }
8743
9231
  }
8744
9232
  if (semanticDataDir && semanticProfile && semanticRecords.length > 0) {
8745
- void upsertSemanticVectors(semanticDataDir, semanticProfile, semanticRecords).catch(() => {
9233
+ void createSemanticDerivedView(semanticDataDir, semanticProfile).refresh(semanticRecords).catch(() => {
8746
9234
  });
8747
9235
  }
8748
9236
  await new Promise((resolve2) => setImmediate(resolve2));
@@ -8853,7 +9341,9 @@ async function removeObservation(oramaId) {
8853
9341
  const database = await getDb();
8854
9342
  await remove2(database, oramaId);
8855
9343
  }
8856
- async function searchObservations(options) {
9344
+ async function searchObservationsDetailed(options) {
9345
+ const retrievalPlan = createRetrievalPlan(options);
9346
+ options = { ...options, ...retrievalPlan };
8857
9347
  const searchStartedAt = Date.now();
8858
9348
  const perf = !!process.env.MEMORIX_PERF;
8859
9349
  const t0 = perf ? performance.now() : 0;
@@ -8867,10 +9357,12 @@ async function searchObservations(options) {
8867
9357
  const modeKey = options.projectId ?? SEARCH_MODE_DEFAULT_KEY;
8868
9358
  const quality = options.quality ?? "balanced";
8869
9359
  const database = await getDb();
8870
- rememberSearchMode(
8871
- modeKey,
8872
- quality === "fast" ? "fulltext (fast profile)" : embeddingEnabled ? "hybrid" : "fulltext"
8873
- );
9360
+ let requestMode = quality === "fast" ? "fulltext (fast profile)" : embeddingEnabled ? "hybrid" : "fulltext";
9361
+ const setMode = (mode) => {
9362
+ requestMode = mode;
9363
+ rememberSearchMode(modeKey, mode);
9364
+ };
9365
+ setMode(requestMode);
8874
9366
  let projectIds = null;
8875
9367
  if (options.projectId) {
8876
9368
  try {
@@ -8891,7 +9383,7 @@ async function searchObservations(options) {
8891
9383
  filters["source"] = options.source;
8892
9384
  }
8893
9385
  const hasQuery = options.query && options.query.trim().length > 0;
8894
- const originalQuery = options.query;
9386
+ const originalQuery = retrievalPlan.query;
8895
9387
  const tier = quality === "fast" ? "fast" : hasQuery ? classifyQueryTier(originalQuery) : "fast";
8896
9388
  mark(`tier=${tier}`);
8897
9389
  if (quality === "thorough" && hasQuery) {
@@ -8945,10 +9437,7 @@ async function searchObservations(options) {
8945
9437
  embeddingUnavailable = true;
8946
9438
  fallbackUsed = true;
8947
9439
  fallbackReason = "embedding dimension mismatch; lexical search used";
8948
- rememberSearchMode(
8949
- modeKey,
8950
- `fulltext (embedding dimension mismatch: provider ${provider2.dimensions}d vs index ${activeVectorDimensions}d)`
8951
- );
9440
+ setMode(`fulltext (embedding dimension mismatch: provider ${provider2.dimensions}d vs index ${activeVectorDimensions}d)`);
8952
9441
  console.error(
8953
9442
  `[memorix] Embedding provider dimension mismatch (${provider2.dimensions}d provider vs ${activeVectorDimensions}d index); using fulltext search`
8954
9443
  );
@@ -8970,7 +9459,7 @@ async function searchObservations(options) {
8970
9459
  mark("embedding");
8971
9460
  const cjkRatio = (originalQuery.match(/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g) || []).length / originalQuery.length;
8972
9461
  const isCJKHeavy = cjkRatio > 0.3;
8973
- rememberSearchMode(modeKey, "hybrid");
9462
+ setMode("hybrid");
8974
9463
  searchParams = {
8975
9464
  ...searchParams,
8976
9465
  mode: "hybrid",
@@ -8993,32 +9482,41 @@ async function searchObservations(options) {
8993
9482
  embeddingUnavailable = true;
8994
9483
  fallbackUsed = true;
8995
9484
  fallbackReason = "embedding failed or timed out; lexical search used";
8996
- rememberSearchMode(modeKey, "fulltext (embedding unavailable)");
9485
+ setMode("fulltext (embedding unavailable)");
8997
9486
  console.error("[memorix] Embedding failed or timed out, falling back to fulltext search");
8998
9487
  }
8999
9488
  }
9000
9489
  mark("preSearch");
9001
9490
  let results;
9491
+ const retrieval = getResolvedConfig().retrieval;
9492
+ const wantLanceOrder = (isCjkHeavyQuery(originalQuery ?? "") ? retrieval.cjk : retrieval.ascii) === "vector";
9493
+ let lanceOrderUsed = false;
9494
+ let persistent = null;
9495
+ if (wantLanceOrder && queryVector && embeddingProviderForSearch) {
9496
+ persistent = await searchLanceInVectorOrder(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch);
9497
+ if (persistent) lanceOrderUsed = true;
9498
+ else {
9499
+ fallbackUsed = true;
9500
+ fallbackReason = fallbackReason ?? "lance vector index empty; hybrid search used";
9501
+ }
9502
+ }
9002
9503
  const persistentCorpusEligible = await shouldUsePersistentSearch(projectIds, options.projectId);
9003
9504
  const canUsePersistentLexical = persistentCorpusEligible && Boolean(hasQuery) && !queryVector && (quality === "fast" || tier === "fast" || !embeddingEnabled || embeddingUnavailable);
9004
- let persistent = persistentCorpusEligible && queryVector && embeddingProviderForSearch ? await searchPersistentSemantically(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch) : canUsePersistentLexical ? await searchPersistentLexically(options, projectIds, requestLimit) : null;
9505
+ if (!persistent) persistent = persistentCorpusEligible && queryVector && embeddingProviderForSearch ? await searchPersistentSemantically(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch) : canUsePersistentLexical ? await searchPersistentLexically(options, projectIds, requestLimit) : null;
9005
9506
  const durableStore = getOptionalObservationStore();
9006
9507
  if (!persistent && queryVector && durableStore?.hasLexicalIndex?.() && count(database) === 0) {
9007
9508
  persistent = await searchPersistentLexically(options, projectIds, requestLimit);
9008
9509
  }
9009
9510
  if (persistent) {
9010
9511
  results = persistent;
9011
- rememberSearchMode(
9012
- modeKey,
9013
- queryVector ? "hybrid" : quality === "fast" ? "fulltext (fast profile)" : "fulltext"
9014
- );
9512
+ setMode(lanceOrderUsed ? "vector" : queryVector ? "hybrid" : quality === "fast" ? "fulltext (fast profile)" : "fulltext");
9015
9513
  mark(queryVector ? "persistentHybridSearch" : "sqliteFtsSearch");
9016
9514
  } else {
9017
9515
  try {
9018
9516
  results = await search(database, searchParams);
9019
9517
  } catch (error) {
9020
9518
  if (queryVector && isVectorDimensionMismatchError(error)) {
9021
- rememberSearchMode(modeKey, "fulltext (embedding dimension mismatch)");
9519
+ setMode("fulltext (embedding dimension mismatch)");
9022
9520
  console.error("[memorix] Vector search dimension mismatch detected, retrying without embeddings");
9023
9521
  results = await search(database, stripVectorSearchParams(searchParams));
9024
9522
  } else {
@@ -9041,7 +9539,7 @@ async function searchObservations(options) {
9041
9539
  },
9042
9540
  similarity: 0.25
9043
9541
  };
9044
- rememberSearchMode(modeKey, "vector-only (hybrid empty fallback)");
9542
+ setMode("vector-only (hybrid empty fallback)");
9045
9543
  fallbackUsed = true;
9046
9544
  fallbackReason = "hybrid search returned no results; vector-only fallback used";
9047
9545
  results = await search(database, vectorOnlyParams);
@@ -9286,7 +9784,7 @@ async function searchObservations(options) {
9286
9784
  const rerankedTop = neural.map((row) => candidateMap.get(row.id)).filter((entry) => entry != null);
9287
9785
  if (rerankedTop.length > 0) {
9288
9786
  intermediate = [...rerankedTop, ...intermediate.slice(RERANK_TOP_K)];
9289
- rememberSearchMode(modeKey, (lastSearchModeByProject.get(modeKey) ?? "fulltext") + " + neural rerank");
9787
+ setMode(requestMode + " + neural rerank");
9290
9788
  mark("rerank(usedNeural=true)");
9291
9789
  }
9292
9790
  }
@@ -9303,7 +9801,7 @@ async function searchObservations(options) {
9303
9801
  );
9304
9802
  mark(`rerank(usedLLM=${usedLLM})`);
9305
9803
  if (usedLLM) {
9306
- rememberSearchMode(modeKey, (lastSearchModeByProject.get(modeKey) ?? "fulltext") + " + LLM rerank");
9804
+ setMode(requestMode + " + LLM rerank");
9307
9805
  const rerankedTop = reranked.map((row) => candidateMap.get(row.id)).filter((entry) => entry != null);
9308
9806
  if (rerankedTop.length > 0) {
9309
9807
  intermediate = [...rerankedTop, ...intermediate.slice(RERANK_TOP_K)];
@@ -9366,9 +9864,9 @@ async function searchObservations(options) {
9366
9864
  if (options.maxTokens && options.maxTokens > 0) {
9367
9865
  entries = applyTokenBudget(entries, options.maxTokens);
9368
9866
  }
9369
- rememberSearchDiagnostics(modeKey, {
9867
+ const diagnostics = {
9370
9868
  version: "1",
9371
- mode: getLastSearchMode(options.projectId),
9869
+ mode: requestMode,
9372
9870
  rawCandidateCount: results.hits.length,
9373
9871
  candidateCount,
9374
9872
  selectedCount: entries.length,
@@ -9377,14 +9875,25 @@ async function searchObservations(options) {
9377
9875
  fallbackUsed,
9378
9876
  ...fallbackReason ? { fallbackReason } : {},
9379
9877
  elapsedMs: Math.max(0, Date.now() - searchStartedAt)
9380
- });
9381
- if (options.trackAccess !== false) {
9382
- const returnedKeys = new Set(entries.map((entry) => makeEntryKey(entry.projectId, entry.id)));
9878
+ };
9879
+ rememberSearchDiagnostics(modeKey, diagnostics);
9880
+ const recordAccess = (selected) => {
9881
+ if (options.trackAccess === false || selected.length === 0) return;
9882
+ const returnedKeys = new Set(selected.map((entry) => makeEntryKey(entry.projectId, entry.id)));
9383
9883
  const hitDocs = results.hits.map((hit) => ({ id: hit.id, doc: hit.document })).filter(({ doc }) => returnedKeys.has(makeEntryKey(doc.projectId, doc.observationId)));
9384
9884
  recordAccessBatch(hitDocs).catch(() => {
9385
9885
  });
9886
+ };
9887
+ const derivedViews = getSearchDerivedViews();
9888
+ if (fallbackUsed && fallbackReason) {
9889
+ derivedViews.embedding = { freshness: "stale", rebuildStatus: "failed", failureReason: fallbackReason };
9386
9890
  }
9387
- return entries;
9891
+ return { entries, diagnostics, derivedViews, recordAccess };
9892
+ }
9893
+ async function searchObservations(options) {
9894
+ const result = await searchObservationsDetailed(options);
9895
+ result.recordAccess?.(result.entries);
9896
+ return result.entries;
9388
9897
  }
9389
9898
  async function getObservationsByIds(ids, projectId) {
9390
9899
  const database = await getDb();
@@ -9493,7 +10002,7 @@ function formatTime(isoDate) {
9493
10002
  return isoDate;
9494
10003
  }
9495
10004
  }
9496
- var db, dbInitPromise, dbGeneration, embeddingEnabled, embeddingDimensions, indexEmbeddingProvider, deferredCachedVectorHydration, NON_CJK_HYBRID_SIMILARITY, CJK_RUN, lastSearchModeByProject, lastSearchDiagnosticsByProject, SEARCH_MODE_DEFAULT_KEY, MAX_SEARCH_MODE_KEYS, COMMAND_LOG_TITLE, COMMAND_STYLE_TITLE, COMMAND_LIKE_QUERY2, COMMAND_INTENT_QUERY, NATURAL_LANGUAGE_MARKERS;
10005
+ var db, dbInitPromise, dbGeneration, embeddingEnabled, embeddingDimensions, indexEmbeddingProvider, deferredCachedVectorHydration, NON_CJK_HYBRID_SIMILARITY, CJK_RUN, lastSearchModeByProject, lastSearchDiagnosticsByProject, searchDerivedViewRegistry, SEARCH_MODE_DEFAULT_KEY, MAX_SEARCH_MODE_KEYS, COMMAND_LOG_TITLE, COMMAND_STYLE_TITLE, COMMAND_LIKE_QUERY2, COMMAND_INTENT_QUERY, NATURAL_LANGUAGE_MARKERS;
9497
10006
  var init_orama_store = __esm({
9498
10007
  "src/store/orama-store.ts"() {
9499
10008
  "use strict";
@@ -9509,8 +10018,13 @@ var init_orama_store = __esm({
9509
10018
  init_policy();
9510
10019
  init_timeout();
9511
10020
  init_obs_store();
10021
+ init_resolved_config();
10022
+ init_retrieval_strategy();
10023
+ init_semantic_view();
10024
+ init_retrieval_contracts();
9512
10025
  init_semantic_index();
9513
10026
  init_derived_view_receipt();
10027
+ init_derived_view_registry();
9514
10028
  db = null;
9515
10029
  dbInitPromise = null;
9516
10030
  dbGeneration = 0;
@@ -9522,8 +10036,12 @@ var init_orama_store = __esm({
9522
10036
  CJK_RUN = /[\u3400-\u4dbf\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]+/gu;
9523
10037
  lastSearchModeByProject = /* @__PURE__ */ new Map();
9524
10038
  lastSearchDiagnosticsByProject = /* @__PURE__ */ new Map();
10039
+ searchDerivedViewRegistry = new DerivedViewRegistry();
9525
10040
  SEARCH_MODE_DEFAULT_KEY = "__global__";
9526
10041
  MAX_SEARCH_MODE_KEYS = 4096;
10042
+ searchDerivedViewRegistry.register("fts", readFtsDerivedViewReceipt);
10043
+ searchDerivedViewRegistry.register("orama", readOramaDerivedViewReceipt);
10044
+ searchDerivedViewRegistry.register("embedding", readEmbeddingDerivedViewReceipt);
9527
10045
  COMMAND_LOG_TITLE = /^(Ran:|Command:|Executed:)\s/i;
9528
10046
  COMMAND_STYLE_TITLE = /(\bfindstr\b|\bSelect-String\b|\bGet-Content\b|\bnpx\s+vitest\b|\bnpx\s+tsc\b|\b2>&1\b)/i;
9529
10047
  COMMAND_LIKE_QUERY2 = /\b(git|npm|npx|pnpm|yarn|node|bash|powershell|curl|memorix)\b/i;
@@ -9703,7 +10221,12 @@ var init_lifecycle = __esm({
9703
10221
  });
9704
10222
 
9705
10223
  // src/store/evidence-store.ts
9706
- import { createHash as createHash5, randomUUID as randomUUID4 } from "crypto";
10224
+ var evidence_store_exports = {};
10225
+ __export(evidence_store_exports, {
10226
+ EvidenceCardStore: () => EvidenceCardStore,
10227
+ buildEvidenceCardId: () => buildEvidenceCardId
10228
+ });
10229
+ import { createHash as createHash5, randomUUID as randomUUID5 } from "crypto";
9707
10230
  function safeJson(value, fallback) {
9708
10231
  if (typeof value !== "string" || value.length === 0) return fallback;
9709
10232
  try {
@@ -9752,6 +10275,9 @@ function sourceKind(observation) {
9752
10275
  if (observation.sourceDetail === "hook") return "hook";
9753
10276
  return observation.source ?? "agent";
9754
10277
  }
10278
+ function buildEvidenceCardId(projectId, candidateKind, candidateId) {
10279
+ return `evidence:${candidateKind}:${projectId}:${candidateId}`;
10280
+ }
9755
10281
  var EvidenceCardStore;
9756
10282
  var init_evidence_store = __esm({
9757
10283
  "src/store/evidence-store.ts"() {
@@ -9892,7 +10418,7 @@ var init_evidence_store = __esm({
9892
10418
  }
9893
10419
  recordEvent(projectId, cardId, kind, detail) {
9894
10420
  const event = {
9895
- id: randomUUID4(),
10421
+ id: randomUUID5(),
9896
10422
  projectId,
9897
10423
  cardId,
9898
10424
  kind,
@@ -9973,7 +10499,7 @@ var init_maintenance_targets = __esm({
9973
10499
  });
9974
10500
 
9975
10501
  // src/knowledge/workspace-store.ts
9976
- import { randomUUID as randomUUID5 } from "crypto";
10502
+ import { randomUUID as randomUUID6 } from "crypto";
9977
10503
  function arrayValue(raw) {
9978
10504
  if (typeof raw !== "string" || !raw) return [];
9979
10505
  try {
@@ -10114,7 +10640,7 @@ var init_workspace_store = __esm({
10114
10640
  }
10115
10641
  createProposal(input) {
10116
10642
  const proposal = {
10117
- id: input.id ?? randomUUID5(),
10643
+ id: input.id ?? randomUUID6(),
10118
10644
  ...input,
10119
10645
  status: input.status ?? "pending",
10120
10646
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
@@ -10400,11 +10926,11 @@ __export(consolidation_exports, {
10400
10926
  });
10401
10927
  function tokenize(text2) {
10402
10928
  return new Set(
10403
- text2.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff\s-]/g, " ").split(/\s+/).filter((t2) => t2.length > 1)
10929
+ text2.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, " ").split(/\s+/).filter((t2) => t2.length > 1)
10404
10930
  );
10405
10931
  }
10406
10932
  function jaccardSimilarity(a, b) {
10407
- if (a.size === 0 && b.size === 0) return 1;
10933
+ if (a.size === 0 && b.size === 0) return 0;
10408
10934
  let intersection = 0;
10409
10935
  for (const token of a) {
10410
10936
  if (b.has(token)) intersection++;
@@ -10781,7 +11307,7 @@ var init_types2 = __esm({
10781
11307
  });
10782
11308
 
10783
11309
  // src/media/asset-store.ts
10784
- import { createHash as createHash7, randomUUID as randomUUID6 } from "crypto";
11310
+ import { createHash as createHash7, randomUUID as randomUUID7 } from "crypto";
10785
11311
  import { copyFile, lstat, mkdir as mkdir3, open, readFile as readFile3, readdir, rename as rename2, rm, stat as stat2, writeFile as writeFile3 } from "fs/promises";
10786
11312
  import path11 from "path";
10787
11313
  function mediaRoot(dataDir) {
@@ -10852,7 +11378,7 @@ async function destinationExists(destination) {
10852
11378
  async function persistBuffer(bytes, destination) {
10853
11379
  await mkdir3(path11.dirname(destination), { recursive: true });
10854
11380
  if (await destinationExists(destination)) return false;
10855
- const temporary = `${destination}.${randomUUID6()}.tmp`;
11381
+ const temporary = `${destination}.${randomUUID7()}.tmp`;
10856
11382
  try {
10857
11383
  await writeFile3(temporary, bytes, { flag: "wx" });
10858
11384
  await rename2(temporary, destination);
@@ -19157,7 +19683,7 @@ var init_uuid = __esm({
19157
19683
  });
19158
19684
 
19159
19685
  // node_modules/openai/internal/errors.mjs
19160
- function isAbortError(err) {
19686
+ function isAbortError2(err) {
19161
19687
  return typeof err === "object" && err !== null && // Spec-compliant fetch implementations
19162
19688
  ("name" in err && err.name === "AbortError" || // Expo fetch
19163
19689
  "message" in err && String(err.message).includes("FetchRequestCanceledException"));
@@ -20337,7 +20863,7 @@ var init_streaming = __esm({
20337
20863
  }
20338
20864
  done = true;
20339
20865
  } catch (e2) {
20340
- if (isAbortError(e2))
20866
+ if (isAbortError2(e2))
20341
20867
  return;
20342
20868
  throw e2;
20343
20869
  } finally {
@@ -20380,7 +20906,7 @@ var init_streaming = __esm({
20380
20906
  }
20381
20907
  done = true;
20382
20908
  } catch (e2) {
20383
- if (isAbortError(e2))
20909
+ if (isAbortError2(e2))
20384
20910
  return;
20385
20911
  throw e2;
20386
20912
  } finally {
@@ -26929,7 +27455,7 @@ var init_client = __esm({
26929
27455
  if (options.signal?.aborted) {
26930
27456
  throw new APIUserAbortError();
26931
27457
  }
26932
- const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
27458
+ const isTimeout = isAbortError2(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
26933
27459
  if (retriesRemaining) {
26934
27460
  loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
26935
27461
  loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({
@@ -46018,7 +46544,7 @@ var init_uuid2 = __esm({
46018
46544
  });
46019
46545
 
46020
46546
  // node_modules/@anthropic-ai/sdk/internal/errors.mjs
46021
- function isAbortError2(err) {
46547
+ function isAbortError3(err) {
46022
46548
  return typeof err === "object" && err !== null && // Spec-compliant fetch implementations
46023
46549
  ("name" in err && err.name === "AbortError" || // Expo fetch
46024
46550
  "message" in err && String(err.message).includes("FetchRequestCanceledException"));
@@ -46789,7 +47315,7 @@ var init_streaming3 = __esm({
46789
47315
  }
46790
47316
  done = true;
46791
47317
  } catch (e2) {
46792
- if (isAbortError2(e2))
47318
+ if (isAbortError3(e2))
46793
47319
  return;
46794
47320
  throw e2;
46795
47321
  } finally {
@@ -46832,7 +47358,7 @@ var init_streaming3 = __esm({
46832
47358
  }
46833
47359
  done = true;
46834
47360
  } catch (e2) {
46835
- if (isAbortError2(e2))
47361
+ if (isAbortError3(e2))
46836
47362
  return;
46837
47363
  throw e2;
46838
47364
  } finally {
@@ -48954,7 +49480,7 @@ var init_BetaMessageStream = __esm({
48954
49480
  _BetaMessageStream_logger.set(this, void 0);
48955
49481
  _BetaMessageStream_handleError.set(this, (error) => {
48956
49482
  __classPrivateFieldSet2(this, _BetaMessageStream_errored, true, "f");
48957
- if (isAbortError2(error)) {
49483
+ if (isAbortError3(error)) {
48958
49484
  error = new APIUserAbortError2();
48959
49485
  }
48960
49486
  if (error instanceof APIUserAbortError2) {
@@ -51415,7 +51941,7 @@ var init_MessageStream = __esm({
51415
51941
  _MessageStream_logger.set(this, void 0);
51416
51942
  _MessageStream_handleError.set(this, (error) => {
51417
51943
  __classPrivateFieldSet2(this, _MessageStream_errored, true, "f");
51418
- if (isAbortError2(error)) {
51944
+ if (isAbortError3(error)) {
51419
51945
  error = new APIUserAbortError2();
51420
51946
  }
51421
51947
  if (error instanceof APIUserAbortError2) {
@@ -52545,7 +53071,7 @@ var init_client2 = __esm({
52545
53071
  if (options.signal?.aborted) {
52546
53072
  throw new APIUserAbortError2();
52547
53073
  }
52548
- const isTimeout = isAbortError2(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
53074
+ const isTimeout = isAbortError3(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
52549
53075
  if (retriesRemaining) {
52550
53076
  loggerFor2(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
52551
53077
  loggerFor2(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails2({
@@ -63754,7 +64280,7 @@ var require_gaxios = __commonJS({
63754
64280
  var retry_js_1 = require_retry3();
63755
64281
  var stream_1 = __require("stream");
63756
64282
  var interceptor_js_1 = require_interceptor();
63757
- var randomUUID16 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
64283
+ var randomUUID17 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
63758
64284
  var HTTP_STATUS_NO_CONTENT = 204;
63759
64285
  var Gaxios = class {
63760
64286
  agentCache = /* @__PURE__ */ new Map();
@@ -64027,7 +64553,7 @@ var require_gaxios = __commonJS({
64027
64553
  */
64028
64554
  ["Blob", "File", "FormData"].includes(opts.data?.constructor?.name || "");
64029
64555
  if (opts.multipart?.length) {
64030
- const boundary = await randomUUID16();
64556
+ const boundary = await randomUUID17();
64031
64557
  preparedHeaders.set("content-type", `multipart/related; boundary=${boundary}`);
64032
64558
  opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary));
64033
64559
  } else if (shouldDirectlyPassData) {
@@ -87053,7 +87579,7 @@ function listDocumentsResponseFromMldev(fromObject) {
87053
87579
  }
87054
87580
  return toObject;
87055
87581
  }
87056
- function isAbortError3(err) {
87582
+ function isAbortError4(err) {
87057
87583
  return typeof err === "object" && err !== null && // Spec-compliant fetch implementations
87058
87584
  ("name" in err && err.name === "AbortError" || // Expo fetch
87059
87585
  "message" in err && String(err.message).includes("FetchRequestCanceledException"));
@@ -94267,7 +94793,7 @@ ${underline}`);
94267
94793
  }
94268
94794
  done = true;
94269
94795
  } catch (e2) {
94270
- if (isAbortError3(e2))
94796
+ if (isAbortError4(e2))
94271
94797
  return yield __await(void 0);
94272
94798
  throw e2;
94273
94799
  } finally {
@@ -94342,7 +94868,7 @@ ${underline}`);
94342
94868
  }
94343
94869
  done = true;
94344
94870
  } catch (e2) {
94345
- if (isAbortError3(e2))
94871
+ if (isAbortError4(e2))
94346
94872
  return yield __await(void 0);
94347
94873
  throw e2;
94348
94874
  } finally {
@@ -94718,7 +95244,7 @@ ${underline}`);
94718
95244
  if ((_d = options.signal) === null || _d === void 0 ? void 0 : _d.aborted) {
94719
95245
  throw new APIUserAbortError3();
94720
95246
  }
94721
- const isTimeout = isAbortError3(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
95247
+ const isTimeout = isAbortError4(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
94722
95248
  if (retriesRemaining) {
94723
95249
  loggerFor3(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
94724
95250
  loggerFor3(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails3({
@@ -96942,7 +97468,7 @@ function isTimeoutError(err) {
96942
97468
  const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnaborted";
96943
97469
  return isNative || isLegacyNative || isGenericErr;
96944
97470
  }
96945
- function isAbortError4(err) {
97471
+ function isAbortError5(err) {
96946
97472
  if (typeof err !== "object" || err == null) {
96947
97473
  return false;
96948
97474
  }
@@ -97954,7 +98480,7 @@ var init_sdks = __esm({
97954
98480
  return response;
97955
98481
  }, { config: options.retryConfig, statusCodes: options.retryCodes }).then((r2) => OK(r2), (err) => {
97956
98482
  switch (true) {
97957
- case isAbortError4(err):
98483
+ case isAbortError5(err):
97958
98484
  return ERR(new RequestAbortedError("Request aborted by client", {
97959
98485
  cause: err
97960
98486
  }));
@@ -144488,14 +145014,23 @@ var init_video_jobs = __esm({
144488
145014
  }
144489
145015
  });
144490
145016
 
144491
- // src/memory/feedback-model.ts
145017
+ // src/core/retrieval-policy.ts
144492
145018
  function feedbackWeightMultiplier(weight) {
144493
145019
  return Math.max(0.35, Math.min(1.4, 0.35 + Math.max(0, Math.min(2, weight)) * 0.525));
144494
145020
  }
145021
+ var init_retrieval_policy = __esm({
145022
+ "src/core/retrieval-policy.ts"() {
145023
+ "use strict";
145024
+ init_esm_shims();
145025
+ }
145026
+ });
145027
+
145028
+ // src/memory/feedback-model.ts
144495
145029
  var init_feedback_model = __esm({
144496
145030
  "src/memory/feedback-model.ts"() {
144497
145031
  "use strict";
144498
145032
  init_esm_shims();
145033
+ init_retrieval_policy();
144499
145034
  }
144500
145035
  });
144501
145036
 
@@ -144507,7 +145042,7 @@ __export(feedback_exports, {
144507
145042
  applyMemoryFeedback: () => applyMemoryFeedback,
144508
145043
  feedbackWeightMultiplier: () => feedbackWeightMultiplier
144509
145044
  });
144510
- import { randomUUID as randomUUID7 } from "crypto";
145045
+ import { randomUUID as randomUUID8 } from "crypto";
144511
145046
  function applyMemoryFeedback(current, event) {
144512
145047
  const delta = event.signal === "revoke" ? 0 : FEEDBACK_DELTAS[event.signal];
144513
145048
  const weight = Math.max(0, Math.min(2, current.weight + delta));
@@ -144625,7 +145160,7 @@ var init_feedback = __esm({
144625
145160
  if (!target) throw new Error("The feedback event to revoke was not found in the same candidate scope.");
144626
145161
  }
144627
145162
  const event = {
144628
- id: randomUUID7(),
145163
+ id: randomUUID8(),
144629
145164
  projectId: input.projectId,
144630
145165
  candidateKind: input.candidateKind,
144631
145166
  candidateId: input.candidateId,
@@ -145013,7 +145548,7 @@ var init_retention = __esm({
145013
145548
  });
145014
145549
 
145015
145550
  // src/memory/owner.ts
145016
- import { randomUUID as randomUUID8 } from "crypto";
145551
+ import { randomUUID as randomUUID9 } from "crypto";
145017
145552
  import { promises as fs9 } from "fs";
145018
145553
  import path16 from "path";
145019
145554
  function ownerPath(dataDir) {
@@ -145043,7 +145578,7 @@ async function resolveLocalMemoryOwner(dataDir, options = {}) {
145043
145578
  await fs9.mkdir(path16.dirname(filePath), { recursive: true });
145044
145579
  const created = {
145045
145580
  version: 1,
145046
- id: "local-" + randomUUID8(),
145581
+ id: "local-" + randomUUID9(),
145047
145582
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
145048
145583
  };
145049
145584
  try {
@@ -145066,7 +145601,7 @@ var init_owner = __esm({
145066
145601
  });
145067
145602
 
145068
145603
  // src/memory/long-term-store.ts
145069
- import { randomUUID as randomUUID9 } from "crypto";
145604
+ import { randomUUID as randomUUID10 } from "crypto";
145070
145605
  function optionalText2(value) {
145071
145606
  return typeof value === "string" && value.trim() ? value : void 0;
145072
145607
  }
@@ -145226,7 +145761,7 @@ var init_long_term_store = __esm({
145226
145761
  }
145227
145762
  insertEvidence(input) {
145228
145763
  const evidence = {
145229
- id: randomUUID9(),
145764
+ id: randomUUID10(),
145230
145765
  ...input,
145231
145766
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
145232
145767
  };
@@ -145253,7 +145788,7 @@ var init_long_term_store = __esm({
145253
145788
  }
145254
145789
  recordEvent(input) {
145255
145790
  const event = {
145256
- id: randomUUID9(),
145791
+ id: randomUUID10(),
145257
145792
  ...input,
145258
145793
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
145259
145794
  };
@@ -145343,7 +145878,7 @@ __export(long_term_exports, {
145343
145878
  selectLongTermMemoriesForTask: () => selectLongTermMemoriesForTask,
145344
145879
  supersedeLongTermMemory: () => supersedeLongTermMemory
145345
145880
  });
145346
- import { randomUUID as randomUUID10 } from "crypto";
145881
+ import { randomUUID as randomUUID11 } from "crypto";
145347
145882
  function isOneOf(value, values) {
145348
145883
  return typeof value === "string" && values.includes(value);
145349
145884
  }
@@ -145525,7 +146060,7 @@ async function createManualLongTermMemory(input) {
145525
146060
  const owner = await resolveLocalMemoryOwner(input.dataDir, { create: true });
145526
146061
  if (!owner) throw new Error("Memorix could not resolve a local memory owner.");
145527
146062
  assertScope(input.scope);
145528
- const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID10(), relation: "supports" }];
146063
+ const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID11(), relation: "supports" }];
145529
146064
  return createLongTermMemoryWithDataDir({
145530
146065
  dataDir: input.dataDir,
145531
146066
  originProjectId: input.projectId,
@@ -145580,7 +146115,7 @@ async function createLongTermMemoryWithDataDir(input) {
145580
146115
  assertPortableEvidence(input.scope, portability, evidenceInputs);
145581
146116
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
145582
146117
  const memory = {
145583
- id: randomUUID10(),
146118
+ id: randomUUID11(),
145584
146119
  originProjectId: compactText(input.originProjectId, "origin project id", 1e3),
145585
146120
  ownerId: compactText(input.ownerId, "owner id", 160),
145586
146121
  scope: input.scope,
@@ -145935,7 +146470,7 @@ var store_exports = {};
145935
146470
  __export(store_exports, {
145936
146471
  CodeGraphStore: () => CodeGraphStore
145937
146472
  });
145938
- import { randomUUID as randomUUID11 } from "crypto";
146473
+ import { randomUUID as randomUUID12 } from "crypto";
145939
146474
  import { posix as pathPosix } from "path";
145940
146475
  function rowToFile(row) {
145941
146476
  return {
@@ -146864,7 +147399,7 @@ var init_store = __esm({
146864
147399
  * so an interrupted scan cannot be advertised as complete.
146865
147400
  */
146866
147401
  recordCodeStateSnapshot(input) {
146867
- const id = randomUUID11();
147402
+ const id = randomUUID12();
146868
147403
  let snapshot;
146869
147404
  let compactNeeded = false;
146870
147405
  const tx = this.db.transaction(() => {
@@ -148097,7 +148632,7 @@ var claim_store_exports = {};
148097
148632
  __export(claim_store_exports, {
148098
148633
  ClaimStore: () => ClaimStore
148099
148634
  });
148100
- import { createHash as createHash12, randomUUID as randomUUID12 } from "crypto";
148635
+ import { createHash as createHash12, randomUUID as randomUUID13 } from "crypto";
148101
148636
  function optionalText3(value) {
148102
148637
  return typeof value === "string" && value ? value : void 0;
148103
148638
  }
@@ -148281,7 +148816,7 @@ var init_claim_store = __esm({
148281
148816
  locator, capturedHash, evidenceKey, createdAt
148282
148817
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
148283
148818
  `).run(
148284
- randomUUID12(),
148819
+ randomUUID13(),
148285
148820
  input.claimId,
148286
148821
  input.evidenceKind,
148287
148822
  input.evidenceId,
@@ -148303,7 +148838,7 @@ var init_claim_store = __esm({
148303
148838
  }
148304
148839
  recordEvent(input) {
148305
148840
  const event = {
148306
- id: randomUUID12(),
148841
+ id: randomUUID13(),
148307
148842
  ...input,
148308
148843
  ...input.detail ? { detail: sanitizeCredentials(input.detail) } : {},
148309
148844
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
@@ -148348,7 +148883,7 @@ __export(claims_exports, {
148348
148883
  supersedeClaim: () => supersedeClaim,
148349
148884
  writeClaim: () => writeClaim
148350
148885
  });
148351
- import { createHash as createHash13, randomUUID as randomUUID13 } from "crypto";
148886
+ import { createHash as createHash13, randomUUID as randomUUID14 } from "crypto";
148352
148887
  function compactText2(value, field) {
148353
148888
  if (typeof value !== "string") throw new Error("Claim " + field + " must be text");
148354
148889
  const sanitized = sanitizeCredentials(value).trim().replace(/\s+/g, " ");
@@ -148434,7 +148969,7 @@ function normalizeClaimInput(input) {
148434
148969
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
148435
148970
  return {
148436
148971
  claim: {
148437
- id: randomUUID13(),
148972
+ id: randomUUID14(),
148438
148973
  projectId,
148439
148974
  subject,
148440
148975
  predicate,
@@ -149519,7 +150054,7 @@ var init_workflow_sync = __esm({
149519
150054
  });
149520
150055
 
149521
150056
  // src/knowledge/workflow-store.ts
149522
- import { randomUUID as randomUUID14 } from "crypto";
150057
+ import { randomUUID as randomUUID15 } from "crypto";
149523
150058
  function parseJson(value, fallback) {
149524
150059
  if (typeof value !== "string" || !value) return fallback;
149525
150060
  try {
@@ -149619,7 +150154,7 @@ var init_workflow_store = __esm({
149619
150154
  }
149620
150155
  recordRun(input) {
149621
150156
  const run = {
149622
- id: randomUUID14(),
150157
+ id: randomUUID15(),
149623
150158
  workflowId: input.workflowId,
149624
150159
  projectId: input.projectId,
149625
150160
  task: input.task.trim(),
@@ -149687,7 +150222,7 @@ var init_outcome_types = __esm({
149687
150222
  });
149688
150223
 
149689
150224
  // src/knowledge/outcome-store.ts
149690
- import { randomUUID as randomUUID15 } from "crypto";
150225
+ import { randomUUID as randomUUID16 } from "crypto";
149691
150226
  function optionalText5(value) {
149692
150227
  return typeof value === "string" && value.trim() ? value : void 0;
149693
150228
  }
@@ -149731,7 +150266,7 @@ var init_outcome_store = __esm({
149731
150266
  }
149732
150267
  record(input) {
149733
150268
  const signal = {
149734
- id: randomUUID15(),
150269
+ id: randomUUID16(),
149735
150270
  projectId: text(input.projectId, "project id"),
149736
150271
  candidateKind: oneOf(input.candidateKind, MEMORY_OUTCOME_CANDIDATE_KINDS, "candidate kind"),
149737
150272
  candidateId: text(input.candidateId, "candidate id"),
@@ -150565,6 +151100,15 @@ function observationId(payload) {
150565
151100
  const value = payload.observationId;
150566
151101
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
150567
151102
  }
151103
+ async function automaticCleanupEnabled(projectRoot) {
151104
+ if (!projectRoot) return true;
151105
+ try {
151106
+ const { getResolvedConfig: getResolvedConfig2 } = await Promise.resolve().then(() => (init_resolved_config(), resolved_config_exports));
151107
+ return getResolvedConfig2({ projectRoot }).memory.autoCleanup !== false;
151108
+ } catch {
151109
+ return true;
151110
+ }
151111
+ }
150568
151112
  function workspaceMode(payload) {
150569
151113
  return payload.workspaceMode === "local" || payload.workspaceMode === "versioned" ? payload.workspaceMode : void 0;
150570
151114
  }
@@ -150653,6 +151197,9 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
150653
151197
  if (job.projectId !== projectId) {
150654
151198
  return { action: "reschedule", delayMs: VECTOR_RETRY_DELAY_MS };
150655
151199
  }
151200
+ if ((job.kind === "retention-archive" || job.kind === "consolidation" || job.kind === "long-term-maintenance") && !await automaticCleanupEnabled(projectRoot)) {
151201
+ return { action: "complete" };
151202
+ }
150656
151203
  if (job.kind === "media-video-generation") {
150657
151204
  const { runMiniMaxVideoGenerationJob: runMiniMaxVideoGenerationJob2 } = await Promise.resolve().then(() => (init_video_jobs(), video_jobs_exports));
150658
151205
  return runMiniMaxVideoGenerationJob2(job, { dataDir: projectDir2, projectId });
@@ -150745,6 +151292,33 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
150745
151292
  });
150746
151293
  return { action: "complete" };
150747
151294
  }
151295
+ if (job.kind === "observation-project") {
151296
+ if (!projectRoot) {
151297
+ throw new Error(`Observation projection requires a project root for ${projectId}`);
151298
+ }
151299
+ const id = observationId(job.payload);
151300
+ if (!id) return { action: "complete" };
151301
+ const [
151302
+ { CodeGraphStore: CodeGraphStore2 },
151303
+ { bindObservationToCode: bindObservationToCode2 },
151304
+ { EvidenceCardStore: EvidenceCardStore2 },
151305
+ { getObservationStore: getObservationStore2 }
151306
+ ] = await Promise.all([
151307
+ Promise.resolve().then(() => (init_store(), store_exports)),
151308
+ Promise.resolve().then(() => (init_binder(), binder_exports)),
151309
+ Promise.resolve().then(() => (init_evidence_store(), evidence_store_exports)),
151310
+ Promise.resolve().then(() => (init_obs_store(), obs_store_exports))
151311
+ ]);
151312
+ const observation = await getObservationStore2().getById(id);
151313
+ if (!observation || observation.projectId !== projectId) return { action: "complete" };
151314
+ const codeStore = new CodeGraphStore2();
151315
+ await codeStore.init(projectDir2);
151316
+ await bindObservationToCode2(codeStore, observation);
151317
+ const evidence = new EvidenceCardStore2();
151318
+ await evidence.init(projectDir2);
151319
+ evidence.upsertObservation(observation);
151320
+ return { action: "complete" };
151321
+ }
150748
151322
  if (job.kind === "observation-qualify") {
150749
151323
  const [
150750
151324
  { CodeGraphStore: CodeGraphStore2 },
@@ -150952,7 +151526,15 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
150952
151526
  const after = getVectorStatus2(projectId);
150953
151527
  if (after.missing === 0) {
150954
151528
  resolveSupersededVectorFailures(projectDir2, projectId);
150955
- return { action: "complete" };
151529
+ return {
151530
+ action: "complete",
151531
+ progress: {
151532
+ attempted: result.attempted,
151533
+ succeeded: result.succeeded,
151534
+ failed: result.failed,
151535
+ remaining: 0
151536
+ }
151537
+ };
150956
151538
  }
150957
151539
  if (result.failed > 0 && result.succeeded === 0) {
150958
151540
  const streak = vectorBackfillFailureStreak(job.payload) + 1;
@@ -150967,6 +151549,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
150967
151549
  ...job.payload,
150968
151550
  vectorBackfillFailureStreak: streak
150969
151551
  },
151552
+ progress: {
151553
+ attempted: result.attempted,
151554
+ succeeded: result.succeeded,
151555
+ failed: result.failed,
151556
+ remaining: after.missing
151557
+ },
150970
151558
  lastError: result.lastError ?? `vector backfill made no progress (${result.failed}/${result.attempted} failed)`
150971
151559
  };
150972
151560
  }
@@ -150976,6 +151564,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
150976
151564
  action: "reschedule",
150977
151565
  delayMs: result.attempted === 0 ? VECTOR_RETRY_DELAY_MS : 0,
150978
151566
  resetAttempts: result.succeeded > 0,
151567
+ progress: {
151568
+ attempted: result.attempted,
151569
+ succeeded: result.succeeded,
151570
+ failed: result.failed,
151571
+ remaining: after.missing
151572
+ },
150979
151573
  ...result.succeeded > 0 ? {
150980
151574
  ...priorFailureStreak > 0 ? { payload } : {},
150981
151575
  ...result.failed > 0 && result.lastError ? { lastError: result.lastError } : priorFailureStreak > 0 ? { clearLastError: true } : {}
@@ -151384,24 +151978,40 @@ function queueVectorBackfill(projectId, options = {}) {
151384
151978
  });
151385
151979
  }
151386
151980
  async function bindObservationCodeRefsBestEffort(observation) {
151387
- if (!projectDir) return;
151981
+ if (!projectDir) return true;
151388
151982
  try {
151389
151983
  const { CodeGraphStore: CodeGraphStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
151390
151984
  const { bindObservationToCode: bindObservationToCode2 } = await Promise.resolve().then(() => (init_binder(), binder_exports));
151391
151985
  const codeStore = new CodeGraphStore2();
151392
151986
  await codeStore.init(projectDir);
151393
151987
  await bindObservationToCode2(codeStore, observation);
151988
+ return true;
151394
151989
  } catch {
151990
+ return false;
151395
151991
  }
151396
151992
  }
151397
151993
  async function persistEvidenceCard(observation) {
151398
- if (!projectDir) return;
151994
+ if (!projectDir) return true;
151399
151995
  try {
151400
151996
  const evidence = new EvidenceCardStore();
151401
151997
  await evidence.init(projectDir);
151402
151998
  evidence.upsertObservation(observation);
151999
+ return true;
151403
152000
  } catch (error) {
151404
152001
  console.error(`[memorix] Evidence card projection failed for obs-${observation.id}: ${error instanceof Error ? error.message : String(error)}`);
152002
+ return false;
152003
+ }
152004
+ }
152005
+ async function acknowledgeObservationProjection(observation) {
152006
+ if (!projectDir) return;
152007
+ try {
152008
+ const { MaintenanceJobStore: MaintenanceJobStore2 } = await Promise.resolve().then(() => (init_maintenance_jobs(), maintenance_jobs_exports));
152009
+ new MaintenanceJobStore2(projectDir).acknowledgePending(
152010
+ observation.projectId,
152011
+ "observation-project",
152012
+ "observation-project:" + observation.id
152013
+ );
152014
+ } catch {
151405
152015
  }
151406
152016
  }
151407
152017
  function queueClaimDerivation(observation) {
@@ -151430,6 +152040,45 @@ function queueObservationQualification(observation) {
151430
152040
  } catch {
151431
152041
  }
151432
152042
  }
152043
+ async function enqueueObservationDerivedWork(tx, observation) {
152044
+ if (!tx.enqueueMaintenanceJob) return false;
152045
+ if (!isEmbeddingExplicitlyDisabled()) {
152046
+ await tx.enqueueMaintenanceJob({
152047
+ projectId: observation.projectId,
152048
+ kind: "vector-backfill",
152049
+ dedupeKey: "vector-backfill",
152050
+ payload: { limit: 12 }
152051
+ });
152052
+ }
152053
+ if (observation.admissionState === "candidate") {
152054
+ await tx.enqueueMaintenanceJob({
152055
+ projectId: observation.projectId,
152056
+ kind: "observation-qualify",
152057
+ dedupeKey: "observation-qualify",
152058
+ payload: { source: "automatic-capture:" + observation.id, limit: 100 }
152059
+ });
152060
+ }
152061
+ const claimSource = observation.sourceDetail === "explicit" || observation.source === "git" || observation.sourceDetail === "git-ingest";
152062
+ if (claimSource && resolveObservationVisibility(observation) === "project") {
152063
+ await tx.enqueueMaintenanceJob({
152064
+ projectId: observation.projectId,
152065
+ kind: "claim-derive",
152066
+ dedupeKey: "claim-derive:" + observation.id,
152067
+ payload: { observationId: observation.id }
152068
+ });
152069
+ }
152070
+ await enqueueObservationProjectionWork(tx, observation);
152071
+ return true;
152072
+ }
152073
+ async function enqueueObservationProjectionWork(tx, observation) {
152074
+ if (!tx.enqueueMaintenanceJob) return;
152075
+ await tx.enqueueMaintenanceJob({
152076
+ projectId: observation.projectId,
152077
+ kind: "observation-project",
152078
+ dedupeKey: "observation-project:" + observation.id,
152079
+ payload: { observationId: observation.id }
152080
+ });
152081
+ }
151433
152082
  function isVectorCompatibleWithCurrentIndex(embedding) {
151434
152083
  if (!embedding) return false;
151435
152084
  const vectorDimensions = getVectorDimensions();
@@ -151608,7 +152257,6 @@ async function storeObservation(input) {
151608
152257
  throw new Error("Cannot update a memory outside this session's write scope.");
151609
152258
  }
151610
152259
  const observation2 = await upsertObservation(existing, input, now3);
151611
- await input.onPersisted?.(observation2);
151612
152260
  return { observation: observation2, upserted: true };
151613
152261
  }
151614
152262
  }
@@ -151635,6 +152283,7 @@ async function storeObservation(input) {
151635
152283
  let upsertedInsideLock = false;
151636
152284
  let reloadCacheAfterCommit = false;
151637
152285
  let persistedCallbackInvoked = false;
152286
+ let derivedJobsCommitted = false;
151638
152287
  const assignAndPersist = async () => {
151639
152288
  if (projectDir) {
151640
152289
  const store = getObservationStore();
@@ -151690,6 +152339,7 @@ async function storeObservation(input) {
151690
152339
  writeGeneration: transactionGeneration + 1
151691
152340
  };
151692
152341
  await tx.insert(observation);
152342
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, observation);
151693
152343
  await input.onPersisted?.(observation);
151694
152344
  persistedCallbackInvoked = true;
151695
152345
  await tx.saveIdCounter(id + 1);
@@ -151788,15 +152438,17 @@ async function storeObservation(input) {
151788
152438
  await assignAndPersist();
151789
152439
  if (upsertedInsideLock) {
151790
152440
  const updated = await upsertObservation(observation, input, now3);
151791
- await input.onPersisted?.(updated);
151792
152441
  return { observation: updated, upserted: true };
151793
152442
  }
151794
152443
  if (!persistedCallbackInvoked) await input.onPersisted?.(observation);
151795
- await bindObservationCodeRefsBestEffort(observation);
151796
- await persistEvidenceCard(observation);
151797
- queueObservationQualification(observation);
151798
- if (resolveObservationVisibility(observation) === "project") {
151799
- queueClaimDerivation(observation);
152444
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(observation);
152445
+ const evidenceProjected = await persistEvidenceCard(observation);
152446
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(observation);
152447
+ if (!derivedJobsCommitted) {
152448
+ queueObservationQualification(observation);
152449
+ if (resolveObservationVisibility(observation) === "project") {
152450
+ queueClaimDerivation(observation);
152451
+ }
151800
152452
  }
151801
152453
  scheduleObservationEmbedding({
151802
152454
  observationId: observation.id,
@@ -151818,86 +152470,115 @@ async function upsertObservation(existing, input, now3) {
151818
152470
  }
151819
152471
  const fullText = [input.title, input.narrative, ...input.facts ?? [], ...enrichedFiles, ...enrichedConcepts].join(" ");
151820
152472
  const tokens = countTextTokens(fullText);
151821
- existing.entityName = input.entityName;
151822
- existing.type = input.type;
151823
- existing.title = input.title;
151824
- existing.narrative = input.narrative;
151825
- existing.facts = input.facts ?? [];
151826
- existing.attachments = input.attachments;
151827
- existing.filesModified = enrichedFiles;
151828
- existing.concepts = enrichedConcepts;
151829
- existing.tokens = tokens;
151830
- existing.updatedAt = now3;
151831
- existing.hasCausalLanguage = extracted.hasCausalLanguage;
151832
- existing.revisionCount = (existing.revisionCount ?? 1) + 1;
151833
- existing.status = "active";
151834
- if (input.sessionId) existing.sessionId = input.sessionId;
151835
- if (input.progress) existing.progress = input.progress;
151836
- if (input.sourceDetail !== void 0) existing.sourceDetail = input.sourceDetail;
151837
- if (input.valueCategory !== void 0) existing.valueCategory = input.valueCategory;
151838
- if (input.admissionState !== void 0) existing.admissionState = input.admissionState;
151839
- if (input.admissionReason !== void 0) existing.admissionReason = sanitizeCredentials(input.admissionReason);
151840
- if (input.visibility !== void 0) existing.visibility = input.visibility;
151841
- if (input.sharedWithAgentIds !== void 0) existing.sharedWithAgentIds = input.sharedWithAgentIds;
152473
+ const applyUpdate = (current) => ({
152474
+ ...current,
152475
+ entityName: input.entityName,
152476
+ type: input.type,
152477
+ title: input.title,
152478
+ narrative: input.narrative,
152479
+ facts: input.facts ?? [],
152480
+ attachments: input.attachments,
152481
+ filesModified: enrichedFiles,
152482
+ concepts: enrichedConcepts,
152483
+ tokens,
152484
+ updatedAt: now3,
152485
+ hasCausalLanguage: extracted.hasCausalLanguage,
152486
+ revisionCount: (current.revisionCount ?? 1) + 1,
152487
+ status: "active",
152488
+ ...input.sessionId ? { sessionId: input.sessionId } : {},
152489
+ ...input.progress ? { progress: input.progress } : {},
152490
+ ...input.sourceDetail !== void 0 ? { sourceDetail: input.sourceDetail } : {},
152491
+ ...input.valueCategory !== void 0 ? { valueCategory: input.valueCategory } : {},
152492
+ ...input.admissionState !== void 0 ? { admissionState: input.admissionState } : {},
152493
+ ...input.admissionReason !== void 0 ? { admissionReason: sanitizeCredentials(input.admissionReason) } : {},
152494
+ ...input.visibility !== void 0 ? { visibility: input.visibility } : {},
152495
+ ...input.sharedWithAgentIds !== void 0 ? { sharedWithAgentIds: input.sharedWithAgentIds } : {}
152496
+ });
152497
+ let updated = applyUpdate(existing);
152498
+ let derivedJobsCommitted = false;
152499
+ if (projectDir) {
152500
+ const store = getObservationStore();
152501
+ await store.atomic(async (tx) => {
152502
+ const current = await tx.getById(existing.id);
152503
+ if (!current || current.projectId !== existing.projectId) {
152504
+ throw new Error("Topic observation changed before update");
152505
+ }
152506
+ updated = applyUpdate(current);
152507
+ updated.writeGeneration = await tx.getGeneration() + 1;
152508
+ await tx.update(updated);
152509
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, updated);
152510
+ await input.onPersisted?.(updated);
152511
+ });
152512
+ updated.writeGeneration = store.getGeneration();
152513
+ } else {
152514
+ await input.onPersisted?.(updated);
152515
+ }
152516
+ if (corpusLoaded) {
152517
+ const cacheIndex = observations.findIndex((observation) => observation.id === updated.id);
152518
+ if (cacheIndex >= 0) observations[cacheIndex] = updated;
152519
+ }
151842
152520
  const doc = {
151843
- id: makeOramaObservationId(existing.projectId, existing.id),
151844
- observationId: existing.id,
151845
- entityName: existing.entityName,
151846
- type: existing.type,
151847
- title: existing.title,
151848
- narrative: existing.narrative,
151849
- facts: existing.facts.join("\n"),
152521
+ id: makeOramaObservationId(updated.projectId, updated.id),
152522
+ observationId: updated.id,
152523
+ entityName: updated.entityName,
152524
+ type: updated.type,
152525
+ title: updated.title,
152526
+ narrative: updated.narrative,
152527
+ facts: updated.facts.join("\n"),
151850
152528
  filesModified: enrichedFiles.join("\n"),
151851
152529
  concepts: enrichedConcepts.map((c) => c.replace(/-/g, " ")).join(", "),
151852
- attachments: formatAttachmentProvenance(existing.attachments),
152530
+ attachments: formatAttachmentProvenance(updated.attachments),
151853
152531
  tokens,
151854
- createdAt: existing.createdAt,
151855
- projectId: existing.projectId,
152532
+ createdAt: updated.createdAt,
152533
+ projectId: updated.projectId,
151856
152534
  accessCount: 0,
151857
152535
  lastAccessedAt: "",
151858
152536
  status: "active",
151859
- source: existing.source ?? "agent",
151860
- sourceDetail: existing.sourceDetail ?? "",
151861
- valueCategory: existing.valueCategory ?? "",
151862
- admissionState: existing.admissionState ?? "",
151863
- admissionReason: existing.admissionReason ?? "",
151864
- visibility: existing.visibility ?? "project",
151865
- createdByAgentId: existing.createdByAgentId ?? "",
151866
- sharedWithAgentIds: JSON.stringify(existing.sharedWithAgentIds ?? [])
151867
- };
151868
- const oramaId = makeOramaObservationId(existing.projectId, existing.id);
151869
- try {
151870
- const { removeObservation: removeObservation2 } = await Promise.resolve().then(() => (init_orama_store(), orama_store_exports));
151871
- await removeObservation2(oramaId);
151872
- } catch {
151873
- }
151874
- try {
151875
- await insertObservation(doc);
151876
- } catch {
152537
+ source: updated.source ?? "agent",
152538
+ sourceDetail: updated.sourceDetail ?? "",
152539
+ valueCategory: updated.valueCategory ?? "",
152540
+ admissionState: updated.admissionState ?? "",
152541
+ admissionReason: updated.admissionReason ?? "",
152542
+ visibility: updated.visibility ?? "project",
152543
+ createdByAgentId: updated.createdByAgentId ?? "",
152544
+ sharedWithAgentIds: JSON.stringify(updated.sharedWithAgentIds ?? [])
152545
+ };
152546
+ if (corpusLoaded) {
152547
+ const oramaId = makeOramaObservationId(updated.projectId, updated.id);
151877
152548
  try {
151878
- const { removeObservation: removeObs } = await Promise.resolve().then(() => (init_orama_store(), orama_store_exports));
151879
- await removeObs(oramaId);
152549
+ try {
152550
+ await removeObservation(oramaId);
152551
+ } catch {
152552
+ }
151880
152553
  await insertObservation(doc);
151881
152554
  } catch {
152555
+ try {
152556
+ try {
152557
+ await removeObservation(oramaId);
152558
+ } catch {
152559
+ }
152560
+ await insertObservation(doc);
152561
+ } catch (error) {
152562
+ console.error(`[memorix] Observation index projection failed for obs-${updated.id}: ${sanitizeCredentials(error instanceof Error ? error.message : String(error))}`);
152563
+ }
151882
152564
  }
151883
152565
  }
151884
- if (projectDir) {
151885
- const store = getObservationStore();
151886
- await store.update(existing);
151887
- }
151888
- await bindObservationCodeRefsBestEffort(existing);
151889
- await persistEvidenceCard(existing);
151890
- queueObservationQualification(existing);
151891
- if (resolveObservationVisibility(existing) === "project") {
151892
- queueClaimDerivation(existing);
152566
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(updated);
152567
+ const evidenceProjected = await persistEvidenceCard(updated);
152568
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(updated);
152569
+ if (!derivedJobsCommitted) {
152570
+ queueObservationQualification(updated);
152571
+ if (resolveObservationVisibility(updated) === "project") {
152572
+ queueClaimDerivation(updated);
152573
+ }
151893
152574
  }
151894
152575
  scheduleObservationEmbedding({
151895
- observationId: existing.id,
151896
- projectId: existing.projectId,
152576
+ observationId: updated.id,
152577
+ projectId: updated.projectId,
151897
152578
  searchableText: [input.title, input.narrative, ...input.facts ?? []].join(" "),
151898
152579
  doc
151899
152580
  });
151900
- return existing;
152581
+ return updated;
151901
152582
  }
151902
152583
  function getObservation(id, projectId) {
151903
152584
  return observations.find((o) => o.id === id && (projectId ? o.projectId === projectId : true));
@@ -151930,6 +152611,7 @@ async function updateObservationAdmission(input) {
151930
152611
  const next = apply(current);
151931
152612
  if (!next) return;
151932
152613
  await tx.update(next);
152614
+ await enqueueObservationProjectionWork(tx, next);
151933
152615
  updated = next;
151934
152616
  });
151935
152617
  } else {
@@ -151947,6 +152629,9 @@ async function updateObservationAdmission(input) {
151947
152629
  });
151948
152630
  } catch {
151949
152631
  }
152632
+ if (await persistEvidenceCard(updated)) {
152633
+ await acknowledgeObservationProjection(updated);
152634
+ }
151950
152635
  if (updated.admissionState === "qualified" && resolveObservationVisibility(updated) === "project") {
151951
152636
  queueClaimDerivation(updated);
151952
152637
  }
@@ -152017,10 +152702,17 @@ async function resolveObservations(ids, status = "resolved") {
152017
152702
  if (projectDir && resolved.length > 0) {
152018
152703
  const store = getObservationStore();
152019
152704
  await store.atomic(async (tx) => {
152020
- await Promise.all(changed.map((observation) => tx.update(observation)));
152705
+ await Promise.all(changed.map(async (observation) => {
152706
+ await tx.update(observation);
152707
+ await enqueueObservationProjectionWork(tx, observation);
152708
+ }));
152021
152709
  });
152022
152710
  }
152023
- for (const observation of changed) await persistEvidenceCard(observation);
152711
+ for (const observation of changed) {
152712
+ if (await persistEvidenceCard(observation)) {
152713
+ await acknowledgeObservationProjection(observation);
152714
+ }
152715
+ }
152024
152716
  return { resolved, notFound };
152025
152717
  }
152026
152718
  function getProjectObservations(projectId) {
@@ -152173,9 +152865,9 @@ async function prepareSearchIndex(options = {}) {
152173
152865
  for (const projectId of projects) {
152174
152866
  const projectObservations = await store.loadByProject(projectId);
152175
152867
  for (const observation of projectObservations) {
152176
- if (!persistedIds?.has(observation.id)) markVectorMissing(observation.id, observation.projectId);
152868
+ if (!persistedIds?.has(semanticVectorKey(observation.projectId, observation.id))) markVectorMissing(observation.id, observation.projectId);
152177
152869
  }
152178
- if (projectObservations.some((observation) => !persistedIds?.has(observation.id))) {
152870
+ if (projectObservations.some((observation) => !persistedIds?.has(semanticVectorKey(observation.projectId, observation.id)))) {
152179
152871
  queueVectorBackfill(projectId);
152180
152872
  }
152181
152873
  }
@@ -152197,7 +152889,7 @@ async function prepareSearchIndex(options = {}) {
152197
152889
  const persistedSemanticIds = await getPersistentSemanticVectorIds(hydratedProjectDir).catch(() => null);
152198
152890
  const projectsWithMissingVectors = /* @__PURE__ */ new Set();
152199
152891
  for (const obs of observations) {
152200
- if (!hasObservationVector(obs.projectId, obs.id) && !persistedSemanticIds?.has(obs.id)) {
152892
+ if (!hasObservationVector(obs.projectId, obs.id) && !persistedSemanticIds?.has(semanticVectorKey(obs.projectId, obs.id))) {
152201
152893
  markVectorMissing(obs.id, obs.projectId);
152202
152894
  projectsWithMissingVectors.add(obs.projectId);
152203
152895
  }
@@ -152241,7 +152933,7 @@ function getSearchIndexStatus(projectId) {
152241
152933
  };
152242
152934
  }
152243
152935
  async function probeSearchIndex(projectId) {
152244
- await searchObservations({
152936
+ const result = await searchObservationsDetailed({
152245
152937
  query: "semantic memory retrieval status",
152246
152938
  projectId,
152247
152939
  reader: { projectId },
@@ -152249,7 +152941,7 @@ async function probeSearchIndex(projectId) {
152249
152941
  status: "all",
152250
152942
  trackAccess: false
152251
152943
  });
152252
- return getLastSearchMode(projectId);
152944
+ return result.diagnostics.mode;
152253
152945
  }
152254
152946
  async function backfillVectorEmbeddings(options = {}) {
152255
152947
  if (vectorBackfillRunning) {
@@ -152401,6 +153093,7 @@ var init_observations = __esm({
152401
153093
  init_token_budget();
152402
153094
  init_entity_extractor();
152403
153095
  init_provider();
153096
+ init_semantic_index();
152404
153097
  init_secret_filter();
152405
153098
  init_lifecycle();
152406
153099
  init_visibility();