memorix 1.10.3 → 1.10.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +62 -1
  2. package/dist/cli/index.js +1886 -1273
  3. package/dist/index.js +1724 -1088
  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 +694 -172
  7. package/dist/media-audio-runner.js +685 -164
  8. package/dist/media-video-runner.js +693 -172
  9. package/dist/memcode-runtime/CHANGELOG.md +44 -1
  10. package/dist/sdk.js +13952 -13345
  11. package/dist/vector-backfill-runner.d.ts +1 -1
  12. package/dist/vector-backfill-runner.js +693 -172
  13. package/docs/ARCHITECTURE.md +219 -0
  14. package/docs/CONFIGURATION.md +15 -0
  15. package/docs/DESIGN_DECISIONS.md +37 -0
  16. package/docs/DEVELOPMENT.md +1 -1
  17. package/docs/MODULES.md +7 -1
  18. package/docs/PERFORMANCE.md +14 -0
  19. package/docs/README.md +1 -1
  20. package/docs/ROADMAP-1.9.12-2.0.md +18 -2
  21. package/package.json +1 -1
  22. package/plugins/antigravity/memorix/plugin.json +1 -1
  23. package/plugins/claude/memorix/.claude-plugin/plugin.json +1 -1
  24. package/plugins/codebuddy/memorix/.codebuddy-plugin/plugin.json +1 -1
  25. package/plugins/codex/memorix/.codex-plugin/plugin.json +1 -1
  26. package/plugins/copilot/memorix/plugin.json +1 -1
  27. package/plugins/gemini/memorix/gemini-extension.json +1 -1
  28. package/plugins/hermes/memorix/plugin.yaml +1 -1
  29. package/plugins/omp/memorix/package.json +1 -1
  30. package/plugins/openclaw/memorix/.codex-plugin/plugin.json +1 -1
  31. package/plugins/pi/memorix/package.json +1 -1
  32. package/server.json +2 -2
  33. package/src/cli/tui/chat-service.ts +6 -9
  34. package/src/cli/tui/data.ts +2 -2
  35. package/src/codegraph/auto-context.ts +9 -2
  36. package/src/codegraph/derived-view.ts +63 -0
  37. package/src/compact/engine.ts +10 -33
  38. package/src/config/resolved-config.ts +11 -0
  39. package/src/config/retrieval-strategy.ts +22 -0
  40. package/src/config/toml-loader.ts +5 -0
  41. package/src/config/yaml-loader.ts +7 -0
  42. package/src/core/derived-view.ts +15 -0
  43. package/src/core/maintenance-result.ts +33 -0
  44. package/src/core/retrieval-contracts.ts +57 -0
  45. package/src/core/retrieval-facade.ts +18 -0
  46. package/src/core/retrieval-policy.ts +44 -0
  47. package/src/core/runtime-context.ts +42 -0
  48. package/src/embedding/api-provider.ts +18 -8
  49. package/src/knowledge/workset.ts +0 -2
  50. package/src/memory/consolidation.ts +3 -2
  51. package/src/memory/feedback-model.ts +1 -4
  52. package/src/memory/observations.ts +165 -87
  53. package/src/runtime/control-plane-maintenance.ts +1 -0
  54. package/src/runtime/isolated-maintenance.ts +1 -0
  55. package/src/runtime/maintenance-jobs.ts +123 -32
  56. package/src/runtime/project-maintenance.ts +69 -1
  57. package/src/sdk.ts +3 -2
  58. package/src/search/fts-view.ts +53 -0
  59. package/src/search/orama-view.ts +40 -0
  60. package/src/search/retrieval-facade.ts +38 -0
  61. package/src/search/semantic-index.ts +13 -0
  62. package/src/search/semantic-view.ts +34 -0
  63. package/src/server.ts +19 -7
  64. package/src/store/obs-store.ts +15 -0
  65. package/src/store/orama-store.ts +116 -42
  66. package/src/store/sqlite-db.ts +22 -0
  67. 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
 
@@ -4470,8 +4637,8 @@ async function loadCacheJsonl(filePath) {
4470
4637
  loaded = cache3.size;
4471
4638
  } catch {
4472
4639
  }
4473
- if (onDiskCount % 250 === 0) {
4474
- await new Promise((resolve2) => setImmediate(resolve2));
4640
+ if (onDiskCount % CACHE_LOAD_YIELD_EVERY === 0) {
4641
+ await new Promise((resolve2) => setTimeout(resolve2, 0));
4475
4642
  }
4476
4643
  }
4477
4644
  diskCacheEntryCount = onDiskCount;
@@ -4800,6 +4967,12 @@ async function fetchWithRetry(url, apiKey, body, options = {}, attempt = 0, nati
4800
4967
  if (err instanceof Error && (err.name === "AbortError" || controller.signal.aborted || options.signal?.aborted)) {
4801
4968
  throw new Error(`Embedding API timeout after ${timeoutMs}ms: ${url}`);
4802
4969
  }
4970
+ if (options.retry !== false && attempt < MAX_RETRIES2) {
4971
+ const delay3 = BASE_DELAY_MS * Math.pow(2, attempt);
4972
+ console.error(`[memorix] Embedding transport failure, retry ${attempt + 1}/${MAX_RETRIES2} in ${delay3}ms`);
4973
+ await waitForRetry(delay3, options.signal);
4974
+ return fetchWithRetry(url, apiKey, body, options, attempt + 1, nativeGemini);
4975
+ }
4803
4976
  throw err;
4804
4977
  }
4805
4978
  try {
@@ -4878,7 +5051,7 @@ async function waitForRetry(waitMs, signal) {
4878
5051
  abortSignal.addEventListener("abort", onAbort, { once: true });
4879
5052
  });
4880
5053
  }
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;
5054
+ var cache3, MAX_CACHE_ENTRIES, MAX_CACHE_PAYLOAD_BYTES, BYTES_PER_DIM, DEFAULT_ASSUMED_DIMENSIONS, MAX_MIGRATION_VALUE_BYTES, cachePayloadBytes3, cacheDimensions, diskCacheEntryCount, diskCacheDirty2, diskSaveTimer, diskCacheLoaded, diskCacheLoadPromise, diskCacheLoadCount, jsonlLineCountCalls, MAX_INPUT_CHARS, MAX_CONCURRENCY, DISK_SAVE_DEBOUNCE_MS, DEFAULT_MAX_BATCH_SIZE, DASHSCOPE_MAX_BATCH_SIZE, MAX_RETRIES2, BASE_DELAY_MS, CACHE_LOAD_YIELD_EVERY, EmbeddingAPIError, APIEmbeddingProvider;
4882
5055
  var init_api_provider = __esm({
4883
5056
  "src/embedding/api-provider.ts"() {
4884
5057
  "use strict";
@@ -4906,6 +5079,7 @@ var init_api_provider = __esm({
4906
5079
  DASHSCOPE_MAX_BATCH_SIZE = 10;
4907
5080
  MAX_RETRIES2 = 3;
4908
5081
  BASE_DELAY_MS = 500;
5082
+ CACHE_LOAD_YIELD_EVERY = 32;
4909
5083
  EmbeddingAPIError = class extends Error {
4910
5084
  status;
4911
5085
  constructor(status, detail) {
@@ -4957,7 +5131,7 @@ var init_api_provider = __esm({
4957
5131
  console.error(`[memorix] Dimension shortening: ${config.requestedDimensions}d requested`);
4958
5132
  }
4959
5133
  if (allowNetworkProbe) {
4960
- startDiskCacheLoad();
5134
+ setImmediate(startDiskCacheLoad);
4961
5135
  }
4962
5136
  return new _APIEmbeddingProvider(config, probeDimensions);
4963
5137
  }
@@ -5029,10 +5203,8 @@ var init_api_provider = __esm({
5029
5203
  return this.embedInput({ modality: "text", text: normalized }, { intent: "document", ...options });
5030
5204
  }
5031
5205
  const hash4 = textHash2(normalized, this.cacheKeyNamespace);
5032
- if (diskCacheLoaded) {
5033
- const cached = cache3.get(hash4);
5034
- if (cached) return cached;
5035
- }
5206
+ const cached = cache3.get(hash4);
5207
+ if (cached) return cached;
5036
5208
  const apiCall = async () => {
5037
5209
  const body = {
5038
5210
  model: this.config.model,
@@ -5057,8 +5229,8 @@ var init_api_provider = __esm({
5057
5229
  let embedding;
5058
5230
  if (!diskCacheLoaded && diskCacheLoadPromise) {
5059
5231
  const cacheRace = diskCacheLoadPromise.then(() => {
5060
- const cached = cache3.get(hash4);
5061
- if (cached) return cached;
5232
+ const cached2 = cache3.get(hash4);
5233
+ if (cached2) return cached2;
5062
5234
  return null;
5063
5235
  });
5064
5236
  const result = await Promise.race([
@@ -6764,6 +6936,7 @@ var sqlite_store_exports = {};
6764
6936
  __export(sqlite_store_exports, {
6765
6937
  SqliteBackend: () => SqliteBackend
6766
6938
  });
6939
+ import { randomUUID as randomUUID4 } from "crypto";
6767
6940
  import path7 from "path";
6768
6941
  import fs4 from "fs";
6769
6942
  function obsToRow(obs) {
@@ -7152,6 +7325,32 @@ var init_sqlite_store = __esm({
7152
7325
  }, "Observation atomic write");
7153
7326
  try {
7154
7327
  const tx = {
7328
+ enqueueMaintenanceJob: async (input) => {
7329
+ const payloadJson = JSON.stringify(input.payload ?? {});
7330
+ const existing = this.db.prepare(`
7331
+ SELECT id, status FROM maintenance_jobs
7332
+ WHERE project_id = ? AND kind = ? AND dedupe_key = ?
7333
+ AND status IN ('pending', 'running', 'retry')
7334
+ LIMIT 1
7335
+ `).get(input.projectId, input.kind, input.dedupeKey);
7336
+ if (existing) {
7337
+ if (existing.status === "running") {
7338
+ this.db.prepare(`
7339
+ UPDATE maintenance_jobs
7340
+ SET rerun_requested = 1, payload_json = ?, updated_at = ?
7341
+ WHERE id = ?
7342
+ `).run(payloadJson, Date.now(), existing.id);
7343
+ }
7344
+ return;
7345
+ }
7346
+ const now3 = Date.now();
7347
+ this.db.prepare(`
7348
+ INSERT INTO maintenance_jobs (
7349
+ id, project_id, kind, dedupe_key, payload_json, status, attempts,
7350
+ max_attempts, run_after, created_at, updated_at
7351
+ ) VALUES (?, ?, ?, ?, ?, 'pending', 0, 8, ?, ?, ?)
7352
+ `).run(randomUUID4(), input.projectId, input.kind, input.dedupeKey, payloadJson, now3, now3, now3);
7353
+ },
7155
7354
  loadAll: async () => this.rawLoadAll(),
7156
7355
  getById: async (id) => this.rawGetById(id),
7157
7356
  findByTopicKey: async (projectId, topicKey) => this.rawFindByTopicKey(projectId, topicKey),
@@ -7222,6 +7421,7 @@ __export(obs_store_exports, {
7222
7421
  DegradedBackend: () => DegradedBackend,
7223
7422
  createObservationStore: () => createObservationStore,
7224
7423
  getObservationStore: () => getObservationStore,
7424
+ getObservationStoreDataDir: () => getObservationStoreDataDir,
7225
7425
  initObservationStore: () => initObservationStore,
7226
7426
  resetObservationStore: () => resetObservationStore,
7227
7427
  setObservationStore: () => setObservationStore
@@ -7232,6 +7432,12 @@ function getObservationStore() {
7232
7432
  }
7233
7433
  return _store2;
7234
7434
  }
7435
+ function getObservationStoreDataDir() {
7436
+ if (!_store2 || !_storeDataDir) {
7437
+ throw new Error("[memorix] ObservationStore data directory is not bound");
7438
+ }
7439
+ return _storeDataDir;
7440
+ }
7235
7441
  function setObservationStore(store) {
7236
7442
  _store2 = store;
7237
7443
  }
@@ -7410,6 +7616,9 @@ async function loadLanceDb() {
7410
7616
  return null;
7411
7617
  }
7412
7618
  }
7619
+ async function isSemanticIndexAvailable() {
7620
+ return await loadLanceDb() !== null;
7621
+ }
7413
7622
  function semanticIndexEnabled() {
7414
7623
  return process.env.MEMORIX_SEMANTIC_INDEX !== "off" && process.env.MEMORIX_SEMANTIC_INDEX !== "orama";
7415
7624
  }
@@ -7539,6 +7748,22 @@ async function listSemanticVectorIds(dataDir, profile) {
7539
7748
  const rows = await state.table.query().select(["observation_id"]).toArray();
7540
7749
  return new Set(rows.map((row) => Number(row.observation_id)).filter(Number.isSafeInteger));
7541
7750
  }
7751
+ async function getSemanticIndexStats(dataDir, profile) {
7752
+ const state = await getState(dataDir, profile);
7753
+ if (!state?.table) return null;
7754
+ return {
7755
+ rowCount: await state.table.countRows(),
7756
+ version: typeof state.table.version === "function" ? await state.table.version() : 0
7757
+ };
7758
+ }
7759
+ function optimizeSemanticIndex(dataDir, profile) {
7760
+ const key = stateKey(dataDir, profile);
7761
+ return queueOperation(key, async () => {
7762
+ const state = await getState(dataDir, profile);
7763
+ if (state) await optimizeState(state);
7764
+ mutationCounts.set(key, 0);
7765
+ });
7766
+ }
7542
7767
  function resolveIndexThreshold() {
7543
7768
  const raw = Number.parseInt(process.env.MEMORIX_SEMANTIC_INDEX_THRESHOLD ?? "", 10);
7544
7769
  return Number.isSafeInteger(raw) && raw > 0 ? raw : DEFAULT_INDEX_THRESHOLD;
@@ -7590,6 +7815,20 @@ async function searchSemanticVectors(options) {
7590
7815
  distance: Number(row._distance ?? Number.POSITIVE_INFINITY)
7591
7816
  })).filter((row) => Number.isFinite(row.distance));
7592
7817
  }
7818
+ async function closeSemanticIndexProfile(dataDir, profile) {
7819
+ const key = stateKey(dataDir, profile);
7820
+ await flushPendingVectorBatch(key);
7821
+ await writeQueues.get(key);
7822
+ const state = await statePromises.get(key)?.catch(() => null);
7823
+ try {
7824
+ state?.connection?.close?.();
7825
+ } catch {
7826
+ }
7827
+ statePromises.delete(key);
7828
+ writeQueues.delete(key);
7829
+ indexBuilds.delete(key);
7830
+ mutationCounts.delete(key);
7831
+ }
7593
7832
  var SEMANTIC_INDEX_DIR, TABLE_PREFIX, DEFAULT_INDEX_THRESHOLD, MAX_INDEX_PARTITIONS, DEFAULT_WRITE_BATCH_SIZE, DEFAULT_WRITE_FLUSH_MS, DEFAULT_OPTIMIZE_EVERY, DEFAULT_VERSION_RETENTION_MS, statePromises, writeQueues, indexBuilds, mutationCounts, pendingVectorBatches, availability, requireFromHere2;
7594
7833
  var init_semantic_index = __esm({
7595
7834
  "src/search/semantic-index.ts"() {
@@ -7612,6 +7851,59 @@ var init_semantic_index = __esm({
7612
7851
  }
7613
7852
  });
7614
7853
 
7854
+ // src/search/semantic-view.ts
7855
+ function createSemanticDerivedView(dataDir, profile) {
7856
+ return {
7857
+ async status() {
7858
+ if (!await isSemanticIndexAvailable()) return { state: "unavailable" };
7859
+ const stats = await getSemanticIndexStats(dataDir, profile);
7860
+ return stats ? { state: "ready", generation: stats.version, rowCount: stats.rowCount } : { state: "missing" };
7861
+ },
7862
+ async refresh(records) {
7863
+ if (records.length === 1) await upsertSemanticVector(dataDir, profile, records[0]);
7864
+ else await upsertSemanticVectors(dataDir, profile, records);
7865
+ },
7866
+ rebuild: () => ensureSemanticIndex(dataDir, profile),
7867
+ compact: () => optimizeSemanticIndex(dataDir, profile),
7868
+ close: () => closeSemanticIndexProfile(dataDir, profile)
7869
+ };
7870
+ }
7871
+ var init_semantic_view = __esm({
7872
+ "src/search/semantic-view.ts"() {
7873
+ "use strict";
7874
+ init_esm_shims();
7875
+ init_semantic_index();
7876
+ }
7877
+ });
7878
+
7879
+ // src/core/retrieval-contracts.ts
7880
+ function createRetrievalPlan(options) {
7881
+ const requestedLimit = Number.isFinite(options.limit) ? Math.floor(options.limit ?? 20) : 20;
7882
+ const requestedTokens = Number.isFinite(options.maxTokens) ? Math.floor(options.maxTokens ?? 0) : 0;
7883
+ return {
7884
+ query: options.query.trim(),
7885
+ quality: options.quality ?? "balanced",
7886
+ limit: Math.max(1, Math.min(1e4, requestedLimit)),
7887
+ ...options.projectId ? { projectId: options.projectId } : {},
7888
+ status: options.status ?? "active",
7889
+ ...options.source ? { source: options.source } : {},
7890
+ ...options.type ? { type: options.type } : {},
7891
+ ...options.since ? { since: options.since } : {},
7892
+ ...options.until ? { until: options.until } : {},
7893
+ maxTokens: Math.max(0, requestedTokens),
7894
+ trackAccess: options.trackAccess !== false,
7895
+ reader: options.reader,
7896
+ surfacedIds: [...options.surfacedIds ?? []],
7897
+ signal: options.signal
7898
+ };
7899
+ }
7900
+ var init_retrieval_contracts = __esm({
7901
+ "src/core/retrieval-contracts.ts"() {
7902
+ "use strict";
7903
+ init_esm_shims();
7904
+ }
7905
+ });
7906
+
7615
7907
  // src/search/derived-view-receipt.ts
7616
7908
  function sanitizeDerivedViewFailureReason(reason) {
7617
7909
  const safe = sanitizeCredentials(reason).replace(/(?:[A-Za-z]:[\\/]|\\\\[^\\/\s]+[\\/]|\/(?:home|Users|tmp|var|private|mnt|workspace|workspaces)\/)[^\s"'<>|]*/gi, "[path]").replace(/\s+/g, " ").trim();
@@ -8245,6 +8537,7 @@ var orama_store_exports = {};
8245
8537
  __export(orama_store_exports, {
8246
8538
  _classifyQueryTier: () => classifyQueryTier,
8247
8539
  batchGenerateEmbeddings: () => batchGenerateEmbeddings,
8540
+ countIndexedDocuments: () => countIndexedDocuments,
8248
8541
  createSearchTokenizer: () => createSearchTokenizer,
8249
8542
  generateEmbedding: () => generateEmbedding,
8250
8543
  generateEmbeddingInput: () => generateEmbeddingInput,
@@ -8270,6 +8563,7 @@ __export(orama_store_exports, {
8270
8563
  resetDb: () => resetDb,
8271
8564
  resolveSearchFuzzyTolerance: () => resolveSearchFuzzyTolerance,
8272
8565
  searchObservations: () => searchObservations,
8566
+ searchObservationsDetailed: () => searchObservationsDetailed,
8273
8567
  updateObservationMetadata: () => updateObservationMetadata
8274
8568
  });
8275
8569
  import { components, create, insert as insert2, insertMultiple, search, remove as remove2, update, count, getByID } from "@orama/orama";
@@ -8458,6 +8752,46 @@ async function searchPersistentLexically(options, projectIds, limit2) {
8458
8752
  return null;
8459
8753
  }
8460
8754
  }
8755
+ async function searchLanceInVectorOrder(options, projectIds, limit2, queryVector, provider2) {
8756
+ try {
8757
+ const { getObservationDataDir: getObservationDataDir2 } = await Promise.resolve().then(() => (init_observations(), observations_exports));
8758
+ const dataDir = getObservationDataDir2();
8759
+ if (!dataDir) return null;
8760
+ const vectorHits = await searchSemanticVectors({
8761
+ dataDir,
8762
+ profile: createSemanticIndexProfile(provider2),
8763
+ vector: queryVector,
8764
+ projectId: projectIds ?? options.projectId,
8765
+ status: "all",
8766
+ limit: Math.min(1e4, Math.max(limit2, 1) * 4)
8767
+ });
8768
+ if (!vectorHits || vectorHits.length === 0) return null;
8769
+ const store = getObservationStore();
8770
+ const hits = [];
8771
+ const seen = /* @__PURE__ */ new Set();
8772
+ for (const hit of vectorHits) {
8773
+ if (seen.has(hit.observationId)) continue;
8774
+ seen.add(hit.observationId);
8775
+ const observation = await store.getById(hit.observationId);
8776
+ if (!observation) continue;
8777
+ if (projectIds && !projectIds.includes(observation.projectId)) continue;
8778
+ if (options.status !== "all" && (observation.status ?? "active") !== (options.status ?? "active")) continue;
8779
+ if (options.type && observation.type !== options.type) continue;
8780
+ if (options.source && observation.source !== options.source) continue;
8781
+ const document2 = observationToSearchDocument(observation);
8782
+ hits.push({
8783
+ id: document2.id,
8784
+ score: 1 / (1 + hits.length),
8785
+ document: document2
8786
+ });
8787
+ if (hits.length >= limit2) break;
8788
+ }
8789
+ if (hits.length === 0) return null;
8790
+ return { count: hits.length, hits };
8791
+ } catch {
8792
+ return null;
8793
+ }
8794
+ }
8461
8795
  async function searchPersistentSemantically(options, projectIds, limit2, queryVector, provider2) {
8462
8796
  try {
8463
8797
  const { getObservationDataDir: getObservationDataDir2 } = await Promise.resolve().then(() => (init_observations(), observations_exports));
@@ -8622,6 +8956,9 @@ async function getDb(options = {}) {
8622
8956
  }
8623
8957
  }
8624
8958
  }
8959
+ async function countIndexedDocuments(database) {
8960
+ return count(database ?? await getDb({ allowNetworkProbe: false }));
8961
+ }
8625
8962
  async function resetDb() {
8626
8963
  dbGeneration++;
8627
8964
  db = null;
@@ -8651,7 +8988,7 @@ async function queueSemanticVector(dataDir, record80) {
8651
8988
  const profile = provider2 ? createSemanticIndexProfile(provider2) : null;
8652
8989
  if (!profile) return;
8653
8990
  try {
8654
- await upsertSemanticVector(dataDir, profile, record80);
8991
+ await createSemanticDerivedView(dataDir, profile).refresh([record80]);
8655
8992
  } catch {
8656
8993
  }
8657
8994
  }
@@ -8742,7 +9079,7 @@ async function attachCachedVectors(database, observations2) {
8742
9079
  }
8743
9080
  }
8744
9081
  if (semanticDataDir && semanticProfile && semanticRecords.length > 0) {
8745
- void upsertSemanticVectors(semanticDataDir, semanticProfile, semanticRecords).catch(() => {
9082
+ void createSemanticDerivedView(semanticDataDir, semanticProfile).refresh(semanticRecords).catch(() => {
8746
9083
  });
8747
9084
  }
8748
9085
  await new Promise((resolve2) => setImmediate(resolve2));
@@ -8853,7 +9190,9 @@ async function removeObservation(oramaId) {
8853
9190
  const database = await getDb();
8854
9191
  await remove2(database, oramaId);
8855
9192
  }
8856
- async function searchObservations(options) {
9193
+ async function searchObservationsDetailed(options) {
9194
+ const retrievalPlan = createRetrievalPlan(options);
9195
+ options = { ...options, ...retrievalPlan };
8857
9196
  const searchStartedAt = Date.now();
8858
9197
  const perf = !!process.env.MEMORIX_PERF;
8859
9198
  const t0 = perf ? performance.now() : 0;
@@ -8867,10 +9206,12 @@ async function searchObservations(options) {
8867
9206
  const modeKey = options.projectId ?? SEARCH_MODE_DEFAULT_KEY;
8868
9207
  const quality = options.quality ?? "balanced";
8869
9208
  const database = await getDb();
8870
- rememberSearchMode(
8871
- modeKey,
8872
- quality === "fast" ? "fulltext (fast profile)" : embeddingEnabled ? "hybrid" : "fulltext"
8873
- );
9209
+ let requestMode = quality === "fast" ? "fulltext (fast profile)" : embeddingEnabled ? "hybrid" : "fulltext";
9210
+ const setMode = (mode) => {
9211
+ requestMode = mode;
9212
+ rememberSearchMode(modeKey, mode);
9213
+ };
9214
+ setMode(requestMode);
8874
9215
  let projectIds = null;
8875
9216
  if (options.projectId) {
8876
9217
  try {
@@ -8891,7 +9232,7 @@ async function searchObservations(options) {
8891
9232
  filters["source"] = options.source;
8892
9233
  }
8893
9234
  const hasQuery = options.query && options.query.trim().length > 0;
8894
- const originalQuery = options.query;
9235
+ const originalQuery = retrievalPlan.query;
8895
9236
  const tier = quality === "fast" ? "fast" : hasQuery ? classifyQueryTier(originalQuery) : "fast";
8896
9237
  mark(`tier=${tier}`);
8897
9238
  if (quality === "thorough" && hasQuery) {
@@ -8945,10 +9286,7 @@ async function searchObservations(options) {
8945
9286
  embeddingUnavailable = true;
8946
9287
  fallbackUsed = true;
8947
9288
  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
- );
9289
+ setMode(`fulltext (embedding dimension mismatch: provider ${provider2.dimensions}d vs index ${activeVectorDimensions}d)`);
8952
9290
  console.error(
8953
9291
  `[memorix] Embedding provider dimension mismatch (${provider2.dimensions}d provider vs ${activeVectorDimensions}d index); using fulltext search`
8954
9292
  );
@@ -8970,7 +9308,7 @@ async function searchObservations(options) {
8970
9308
  mark("embedding");
8971
9309
  const cjkRatio = (originalQuery.match(/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g) || []).length / originalQuery.length;
8972
9310
  const isCJKHeavy = cjkRatio > 0.3;
8973
- rememberSearchMode(modeKey, "hybrid");
9311
+ setMode("hybrid");
8974
9312
  searchParams = {
8975
9313
  ...searchParams,
8976
9314
  mode: "hybrid",
@@ -8993,32 +9331,41 @@ async function searchObservations(options) {
8993
9331
  embeddingUnavailable = true;
8994
9332
  fallbackUsed = true;
8995
9333
  fallbackReason = "embedding failed or timed out; lexical search used";
8996
- rememberSearchMode(modeKey, "fulltext (embedding unavailable)");
9334
+ setMode("fulltext (embedding unavailable)");
8997
9335
  console.error("[memorix] Embedding failed or timed out, falling back to fulltext search");
8998
9336
  }
8999
9337
  }
9000
9338
  mark("preSearch");
9001
9339
  let results;
9340
+ const retrieval = getResolvedConfig().retrieval;
9341
+ const wantLanceOrder = (isCjkHeavyQuery(originalQuery ?? "") ? retrieval.cjk : retrieval.ascii) === "vector";
9342
+ let lanceOrderUsed = false;
9343
+ let persistent = null;
9344
+ if (wantLanceOrder && queryVector && embeddingProviderForSearch) {
9345
+ persistent = await searchLanceInVectorOrder(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch);
9346
+ if (persistent) lanceOrderUsed = true;
9347
+ else {
9348
+ fallbackUsed = true;
9349
+ fallbackReason = fallbackReason ?? "lance vector index empty; hybrid search used";
9350
+ }
9351
+ }
9002
9352
  const persistentCorpusEligible = await shouldUsePersistentSearch(projectIds, options.projectId);
9003
9353
  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;
9354
+ if (!persistent) persistent = persistentCorpusEligible && queryVector && embeddingProviderForSearch ? await searchPersistentSemantically(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch) : canUsePersistentLexical ? await searchPersistentLexically(options, projectIds, requestLimit) : null;
9005
9355
  const durableStore = getOptionalObservationStore();
9006
9356
  if (!persistent && queryVector && durableStore?.hasLexicalIndex?.() && count(database) === 0) {
9007
9357
  persistent = await searchPersistentLexically(options, projectIds, requestLimit);
9008
9358
  }
9009
9359
  if (persistent) {
9010
9360
  results = persistent;
9011
- rememberSearchMode(
9012
- modeKey,
9013
- queryVector ? "hybrid" : quality === "fast" ? "fulltext (fast profile)" : "fulltext"
9014
- );
9361
+ setMode(lanceOrderUsed ? "vector" : queryVector ? "hybrid" : quality === "fast" ? "fulltext (fast profile)" : "fulltext");
9015
9362
  mark(queryVector ? "persistentHybridSearch" : "sqliteFtsSearch");
9016
9363
  } else {
9017
9364
  try {
9018
9365
  results = await search(database, searchParams);
9019
9366
  } catch (error) {
9020
9367
  if (queryVector && isVectorDimensionMismatchError(error)) {
9021
- rememberSearchMode(modeKey, "fulltext (embedding dimension mismatch)");
9368
+ setMode("fulltext (embedding dimension mismatch)");
9022
9369
  console.error("[memorix] Vector search dimension mismatch detected, retrying without embeddings");
9023
9370
  results = await search(database, stripVectorSearchParams(searchParams));
9024
9371
  } else {
@@ -9041,7 +9388,7 @@ async function searchObservations(options) {
9041
9388
  },
9042
9389
  similarity: 0.25
9043
9390
  };
9044
- rememberSearchMode(modeKey, "vector-only (hybrid empty fallback)");
9391
+ setMode("vector-only (hybrid empty fallback)");
9045
9392
  fallbackUsed = true;
9046
9393
  fallbackReason = "hybrid search returned no results; vector-only fallback used";
9047
9394
  results = await search(database, vectorOnlyParams);
@@ -9286,7 +9633,7 @@ async function searchObservations(options) {
9286
9633
  const rerankedTop = neural.map((row) => candidateMap.get(row.id)).filter((entry) => entry != null);
9287
9634
  if (rerankedTop.length > 0) {
9288
9635
  intermediate = [...rerankedTop, ...intermediate.slice(RERANK_TOP_K)];
9289
- rememberSearchMode(modeKey, (lastSearchModeByProject.get(modeKey) ?? "fulltext") + " + neural rerank");
9636
+ setMode(requestMode + " + neural rerank");
9290
9637
  mark("rerank(usedNeural=true)");
9291
9638
  }
9292
9639
  }
@@ -9303,7 +9650,7 @@ async function searchObservations(options) {
9303
9650
  );
9304
9651
  mark(`rerank(usedLLM=${usedLLM})`);
9305
9652
  if (usedLLM) {
9306
- rememberSearchMode(modeKey, (lastSearchModeByProject.get(modeKey) ?? "fulltext") + " + LLM rerank");
9653
+ setMode(requestMode + " + LLM rerank");
9307
9654
  const rerankedTop = reranked.map((row) => candidateMap.get(row.id)).filter((entry) => entry != null);
9308
9655
  if (rerankedTop.length > 0) {
9309
9656
  intermediate = [...rerankedTop, ...intermediate.slice(RERANK_TOP_K)];
@@ -9366,9 +9713,9 @@ async function searchObservations(options) {
9366
9713
  if (options.maxTokens && options.maxTokens > 0) {
9367
9714
  entries = applyTokenBudget(entries, options.maxTokens);
9368
9715
  }
9369
- rememberSearchDiagnostics(modeKey, {
9716
+ const diagnostics = {
9370
9717
  version: "1",
9371
- mode: getLastSearchMode(options.projectId),
9718
+ mode: requestMode,
9372
9719
  rawCandidateCount: results.hits.length,
9373
9720
  candidateCount,
9374
9721
  selectedCount: entries.length,
@@ -9377,14 +9724,25 @@ async function searchObservations(options) {
9377
9724
  fallbackUsed,
9378
9725
  ...fallbackReason ? { fallbackReason } : {},
9379
9726
  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)));
9727
+ };
9728
+ rememberSearchDiagnostics(modeKey, diagnostics);
9729
+ const recordAccess = (selected) => {
9730
+ if (options.trackAccess === false || selected.length === 0) return;
9731
+ const returnedKeys = new Set(selected.map((entry) => makeEntryKey(entry.projectId, entry.id)));
9383
9732
  const hitDocs = results.hits.map((hit) => ({ id: hit.id, doc: hit.document })).filter(({ doc }) => returnedKeys.has(makeEntryKey(doc.projectId, doc.observationId)));
9384
9733
  recordAccessBatch(hitDocs).catch(() => {
9385
9734
  });
9735
+ };
9736
+ const derivedViews = getSearchDerivedViews();
9737
+ if (fallbackUsed && fallbackReason) {
9738
+ derivedViews.embedding = { freshness: "stale", rebuildStatus: "failed", failureReason: fallbackReason };
9386
9739
  }
9387
- return entries;
9740
+ return { entries, diagnostics, derivedViews, recordAccess };
9741
+ }
9742
+ async function searchObservations(options) {
9743
+ const result = await searchObservationsDetailed(options);
9744
+ result.recordAccess?.(result.entries);
9745
+ return result.entries;
9388
9746
  }
9389
9747
  async function getObservationsByIds(ids, projectId) {
9390
9748
  const database = await getDb();
@@ -9509,6 +9867,10 @@ var init_orama_store = __esm({
9509
9867
  init_policy();
9510
9868
  init_timeout();
9511
9869
  init_obs_store();
9870
+ init_resolved_config();
9871
+ init_retrieval_strategy();
9872
+ init_semantic_view();
9873
+ init_retrieval_contracts();
9512
9874
  init_semantic_index();
9513
9875
  init_derived_view_receipt();
9514
9876
  db = null;
@@ -9703,7 +10065,12 @@ var init_lifecycle = __esm({
9703
10065
  });
9704
10066
 
9705
10067
  // src/store/evidence-store.ts
9706
- import { createHash as createHash5, randomUUID as randomUUID4 } from "crypto";
10068
+ var evidence_store_exports = {};
10069
+ __export(evidence_store_exports, {
10070
+ EvidenceCardStore: () => EvidenceCardStore,
10071
+ buildEvidenceCardId: () => buildEvidenceCardId
10072
+ });
10073
+ import { createHash as createHash5, randomUUID as randomUUID5 } from "crypto";
9707
10074
  function safeJson(value, fallback) {
9708
10075
  if (typeof value !== "string" || value.length === 0) return fallback;
9709
10076
  try {
@@ -9752,6 +10119,9 @@ function sourceKind(observation) {
9752
10119
  if (observation.sourceDetail === "hook") return "hook";
9753
10120
  return observation.source ?? "agent";
9754
10121
  }
10122
+ function buildEvidenceCardId(projectId, candidateKind, candidateId) {
10123
+ return `evidence:${candidateKind}:${projectId}:${candidateId}`;
10124
+ }
9755
10125
  var EvidenceCardStore;
9756
10126
  var init_evidence_store = __esm({
9757
10127
  "src/store/evidence-store.ts"() {
@@ -9892,7 +10262,7 @@ var init_evidence_store = __esm({
9892
10262
  }
9893
10263
  recordEvent(projectId, cardId, kind, detail) {
9894
10264
  const event = {
9895
- id: randomUUID4(),
10265
+ id: randomUUID5(),
9896
10266
  projectId,
9897
10267
  cardId,
9898
10268
  kind,
@@ -9973,7 +10343,7 @@ var init_maintenance_targets = __esm({
9973
10343
  });
9974
10344
 
9975
10345
  // src/knowledge/workspace-store.ts
9976
- import { randomUUID as randomUUID5 } from "crypto";
10346
+ import { randomUUID as randomUUID6 } from "crypto";
9977
10347
  function arrayValue(raw) {
9978
10348
  if (typeof raw !== "string" || !raw) return [];
9979
10349
  try {
@@ -10114,7 +10484,7 @@ var init_workspace_store = __esm({
10114
10484
  }
10115
10485
  createProposal(input) {
10116
10486
  const proposal = {
10117
- id: input.id ?? randomUUID5(),
10487
+ id: input.id ?? randomUUID6(),
10118
10488
  ...input,
10119
10489
  status: input.status ?? "pending",
10120
10490
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
@@ -10400,11 +10770,11 @@ __export(consolidation_exports, {
10400
10770
  });
10401
10771
  function tokenize(text2) {
10402
10772
  return new Set(
10403
- text2.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff\s-]/g, " ").split(/\s+/).filter((t2) => t2.length > 1)
10773
+ text2.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, " ").split(/\s+/).filter((t2) => t2.length > 1)
10404
10774
  );
10405
10775
  }
10406
10776
  function jaccardSimilarity(a, b) {
10407
- if (a.size === 0 && b.size === 0) return 1;
10777
+ if (a.size === 0 && b.size === 0) return 0;
10408
10778
  let intersection = 0;
10409
10779
  for (const token of a) {
10410
10780
  if (b.has(token)) intersection++;
@@ -10781,7 +11151,7 @@ var init_types2 = __esm({
10781
11151
  });
10782
11152
 
10783
11153
  // src/media/asset-store.ts
10784
- import { createHash as createHash7, randomUUID as randomUUID6 } from "crypto";
11154
+ import { createHash as createHash7, randomUUID as randomUUID7 } from "crypto";
10785
11155
  import { copyFile, lstat, mkdir as mkdir3, open, readFile as readFile3, readdir, rename as rename2, rm, stat as stat2, writeFile as writeFile3 } from "fs/promises";
10786
11156
  import path11 from "path";
10787
11157
  function mediaRoot(dataDir) {
@@ -10852,7 +11222,7 @@ async function destinationExists(destination) {
10852
11222
  async function persistBuffer(bytes, destination) {
10853
11223
  await mkdir3(path11.dirname(destination), { recursive: true });
10854
11224
  if (await destinationExists(destination)) return false;
10855
- const temporary = `${destination}.${randomUUID6()}.tmp`;
11225
+ const temporary = `${destination}.${randomUUID7()}.tmp`;
10856
11226
  try {
10857
11227
  await writeFile3(temporary, bytes, { flag: "wx" });
10858
11228
  await rename2(temporary, destination);
@@ -63754,7 +64124,7 @@ var require_gaxios = __commonJS({
63754
64124
  var retry_js_1 = require_retry3();
63755
64125
  var stream_1 = __require("stream");
63756
64126
  var interceptor_js_1 = require_interceptor();
63757
- var randomUUID16 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
64127
+ var randomUUID17 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
63758
64128
  var HTTP_STATUS_NO_CONTENT = 204;
63759
64129
  var Gaxios = class {
63760
64130
  agentCache = /* @__PURE__ */ new Map();
@@ -64027,7 +64397,7 @@ var require_gaxios = __commonJS({
64027
64397
  */
64028
64398
  ["Blob", "File", "FormData"].includes(opts.data?.constructor?.name || "");
64029
64399
  if (opts.multipart?.length) {
64030
- const boundary = await randomUUID16();
64400
+ const boundary = await randomUUID17();
64031
64401
  preparedHeaders.set("content-type", `multipart/related; boundary=${boundary}`);
64032
64402
  opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary));
64033
64403
  } else if (shouldDirectlyPassData) {
@@ -144488,14 +144858,23 @@ var init_video_jobs = __esm({
144488
144858
  }
144489
144859
  });
144490
144860
 
144491
- // src/memory/feedback-model.ts
144861
+ // src/core/retrieval-policy.ts
144492
144862
  function feedbackWeightMultiplier(weight) {
144493
144863
  return Math.max(0.35, Math.min(1.4, 0.35 + Math.max(0, Math.min(2, weight)) * 0.525));
144494
144864
  }
144865
+ var init_retrieval_policy = __esm({
144866
+ "src/core/retrieval-policy.ts"() {
144867
+ "use strict";
144868
+ init_esm_shims();
144869
+ }
144870
+ });
144871
+
144872
+ // src/memory/feedback-model.ts
144495
144873
  var init_feedback_model = __esm({
144496
144874
  "src/memory/feedback-model.ts"() {
144497
144875
  "use strict";
144498
144876
  init_esm_shims();
144877
+ init_retrieval_policy();
144499
144878
  }
144500
144879
  });
144501
144880
 
@@ -144507,7 +144886,7 @@ __export(feedback_exports, {
144507
144886
  applyMemoryFeedback: () => applyMemoryFeedback,
144508
144887
  feedbackWeightMultiplier: () => feedbackWeightMultiplier
144509
144888
  });
144510
- import { randomUUID as randomUUID7 } from "crypto";
144889
+ import { randomUUID as randomUUID8 } from "crypto";
144511
144890
  function applyMemoryFeedback(current, event) {
144512
144891
  const delta = event.signal === "revoke" ? 0 : FEEDBACK_DELTAS[event.signal];
144513
144892
  const weight = Math.max(0, Math.min(2, current.weight + delta));
@@ -144625,7 +145004,7 @@ var init_feedback = __esm({
144625
145004
  if (!target) throw new Error("The feedback event to revoke was not found in the same candidate scope.");
144626
145005
  }
144627
145006
  const event = {
144628
- id: randomUUID7(),
145007
+ id: randomUUID8(),
144629
145008
  projectId: input.projectId,
144630
145009
  candidateKind: input.candidateKind,
144631
145010
  candidateId: input.candidateId,
@@ -145013,7 +145392,7 @@ var init_retention = __esm({
145013
145392
  });
145014
145393
 
145015
145394
  // src/memory/owner.ts
145016
- import { randomUUID as randomUUID8 } from "crypto";
145395
+ import { randomUUID as randomUUID9 } from "crypto";
145017
145396
  import { promises as fs9 } from "fs";
145018
145397
  import path16 from "path";
145019
145398
  function ownerPath(dataDir) {
@@ -145043,7 +145422,7 @@ async function resolveLocalMemoryOwner(dataDir, options = {}) {
145043
145422
  await fs9.mkdir(path16.dirname(filePath), { recursive: true });
145044
145423
  const created = {
145045
145424
  version: 1,
145046
- id: "local-" + randomUUID8(),
145425
+ id: "local-" + randomUUID9(),
145047
145426
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
145048
145427
  };
145049
145428
  try {
@@ -145066,7 +145445,7 @@ var init_owner = __esm({
145066
145445
  });
145067
145446
 
145068
145447
  // src/memory/long-term-store.ts
145069
- import { randomUUID as randomUUID9 } from "crypto";
145448
+ import { randomUUID as randomUUID10 } from "crypto";
145070
145449
  function optionalText2(value) {
145071
145450
  return typeof value === "string" && value.trim() ? value : void 0;
145072
145451
  }
@@ -145226,7 +145605,7 @@ var init_long_term_store = __esm({
145226
145605
  }
145227
145606
  insertEvidence(input) {
145228
145607
  const evidence = {
145229
- id: randomUUID9(),
145608
+ id: randomUUID10(),
145230
145609
  ...input,
145231
145610
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
145232
145611
  };
@@ -145253,7 +145632,7 @@ var init_long_term_store = __esm({
145253
145632
  }
145254
145633
  recordEvent(input) {
145255
145634
  const event = {
145256
- id: randomUUID9(),
145635
+ id: randomUUID10(),
145257
145636
  ...input,
145258
145637
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
145259
145638
  };
@@ -145343,7 +145722,7 @@ __export(long_term_exports, {
145343
145722
  selectLongTermMemoriesForTask: () => selectLongTermMemoriesForTask,
145344
145723
  supersedeLongTermMemory: () => supersedeLongTermMemory
145345
145724
  });
145346
- import { randomUUID as randomUUID10 } from "crypto";
145725
+ import { randomUUID as randomUUID11 } from "crypto";
145347
145726
  function isOneOf(value, values) {
145348
145727
  return typeof value === "string" && values.includes(value);
145349
145728
  }
@@ -145525,7 +145904,7 @@ async function createManualLongTermMemory(input) {
145525
145904
  const owner = await resolveLocalMemoryOwner(input.dataDir, { create: true });
145526
145905
  if (!owner) throw new Error("Memorix could not resolve a local memory owner.");
145527
145906
  assertScope(input.scope);
145528
- const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID10(), relation: "supports" }];
145907
+ const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID11(), relation: "supports" }];
145529
145908
  return createLongTermMemoryWithDataDir({
145530
145909
  dataDir: input.dataDir,
145531
145910
  originProjectId: input.projectId,
@@ -145580,7 +145959,7 @@ async function createLongTermMemoryWithDataDir(input) {
145580
145959
  assertPortableEvidence(input.scope, portability, evidenceInputs);
145581
145960
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
145582
145961
  const memory = {
145583
- id: randomUUID10(),
145962
+ id: randomUUID11(),
145584
145963
  originProjectId: compactText(input.originProjectId, "origin project id", 1e3),
145585
145964
  ownerId: compactText(input.ownerId, "owner id", 160),
145586
145965
  scope: input.scope,
@@ -145935,7 +146314,7 @@ var store_exports = {};
145935
146314
  __export(store_exports, {
145936
146315
  CodeGraphStore: () => CodeGraphStore
145937
146316
  });
145938
- import { randomUUID as randomUUID11 } from "crypto";
146317
+ import { randomUUID as randomUUID12 } from "crypto";
145939
146318
  import { posix as pathPosix } from "path";
145940
146319
  function rowToFile(row) {
145941
146320
  return {
@@ -146864,7 +147243,7 @@ var init_store = __esm({
146864
147243
  * so an interrupted scan cannot be advertised as complete.
146865
147244
  */
146866
147245
  recordCodeStateSnapshot(input) {
146867
- const id = randomUUID11();
147246
+ const id = randomUUID12();
146868
147247
  let snapshot;
146869
147248
  let compactNeeded = false;
146870
147249
  const tx = this.db.transaction(() => {
@@ -148097,7 +148476,7 @@ var claim_store_exports = {};
148097
148476
  __export(claim_store_exports, {
148098
148477
  ClaimStore: () => ClaimStore
148099
148478
  });
148100
- import { createHash as createHash12, randomUUID as randomUUID12 } from "crypto";
148479
+ import { createHash as createHash12, randomUUID as randomUUID13 } from "crypto";
148101
148480
  function optionalText3(value) {
148102
148481
  return typeof value === "string" && value ? value : void 0;
148103
148482
  }
@@ -148281,7 +148660,7 @@ var init_claim_store = __esm({
148281
148660
  locator, capturedHash, evidenceKey, createdAt
148282
148661
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
148283
148662
  `).run(
148284
- randomUUID12(),
148663
+ randomUUID13(),
148285
148664
  input.claimId,
148286
148665
  input.evidenceKind,
148287
148666
  input.evidenceId,
@@ -148303,7 +148682,7 @@ var init_claim_store = __esm({
148303
148682
  }
148304
148683
  recordEvent(input) {
148305
148684
  const event = {
148306
- id: randomUUID12(),
148685
+ id: randomUUID13(),
148307
148686
  ...input,
148308
148687
  ...input.detail ? { detail: sanitizeCredentials(input.detail) } : {},
148309
148688
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
@@ -148348,7 +148727,7 @@ __export(claims_exports, {
148348
148727
  supersedeClaim: () => supersedeClaim,
148349
148728
  writeClaim: () => writeClaim
148350
148729
  });
148351
- import { createHash as createHash13, randomUUID as randomUUID13 } from "crypto";
148730
+ import { createHash as createHash13, randomUUID as randomUUID14 } from "crypto";
148352
148731
  function compactText2(value, field) {
148353
148732
  if (typeof value !== "string") throw new Error("Claim " + field + " must be text");
148354
148733
  const sanitized = sanitizeCredentials(value).trim().replace(/\s+/g, " ");
@@ -148434,7 +148813,7 @@ function normalizeClaimInput(input) {
148434
148813
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
148435
148814
  return {
148436
148815
  claim: {
148437
- id: randomUUID13(),
148816
+ id: randomUUID14(),
148438
148817
  projectId,
148439
148818
  subject,
148440
148819
  predicate,
@@ -149519,7 +149898,7 @@ var init_workflow_sync = __esm({
149519
149898
  });
149520
149899
 
149521
149900
  // src/knowledge/workflow-store.ts
149522
- import { randomUUID as randomUUID14 } from "crypto";
149901
+ import { randomUUID as randomUUID15 } from "crypto";
149523
149902
  function parseJson(value, fallback) {
149524
149903
  if (typeof value !== "string" || !value) return fallback;
149525
149904
  try {
@@ -149619,7 +149998,7 @@ var init_workflow_store = __esm({
149619
149998
  }
149620
149999
  recordRun(input) {
149621
150000
  const run = {
149622
- id: randomUUID14(),
150001
+ id: randomUUID15(),
149623
150002
  workflowId: input.workflowId,
149624
150003
  projectId: input.projectId,
149625
150004
  task: input.task.trim(),
@@ -149687,7 +150066,7 @@ var init_outcome_types = __esm({
149687
150066
  });
149688
150067
 
149689
150068
  // src/knowledge/outcome-store.ts
149690
- import { randomUUID as randomUUID15 } from "crypto";
150069
+ import { randomUUID as randomUUID16 } from "crypto";
149691
150070
  function optionalText5(value) {
149692
150071
  return typeof value === "string" && value.trim() ? value : void 0;
149693
150072
  }
@@ -149731,7 +150110,7 @@ var init_outcome_store = __esm({
149731
150110
  }
149732
150111
  record(input) {
149733
150112
  const signal = {
149734
- id: randomUUID15(),
150113
+ id: randomUUID16(),
149735
150114
  projectId: text(input.projectId, "project id"),
149736
150115
  candidateKind: oneOf(input.candidateKind, MEMORY_OUTCOME_CANDIDATE_KINDS, "candidate kind"),
149737
150116
  candidateId: text(input.candidateId, "candidate id"),
@@ -150565,6 +150944,15 @@ function observationId(payload) {
150565
150944
  const value = payload.observationId;
150566
150945
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
150567
150946
  }
150947
+ async function automaticCleanupEnabled(projectRoot) {
150948
+ if (!projectRoot) return true;
150949
+ try {
150950
+ const { getResolvedConfig: getResolvedConfig2 } = await Promise.resolve().then(() => (init_resolved_config(), resolved_config_exports));
150951
+ return getResolvedConfig2({ projectRoot }).memory.autoCleanup !== false;
150952
+ } catch {
150953
+ return true;
150954
+ }
150955
+ }
150568
150956
  function workspaceMode(payload) {
150569
150957
  return payload.workspaceMode === "local" || payload.workspaceMode === "versioned" ? payload.workspaceMode : void 0;
150570
150958
  }
@@ -150653,6 +151041,9 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
150653
151041
  if (job.projectId !== projectId) {
150654
151042
  return { action: "reschedule", delayMs: VECTOR_RETRY_DELAY_MS };
150655
151043
  }
151044
+ if ((job.kind === "retention-archive" || job.kind === "consolidation" || job.kind === "long-term-maintenance") && !await automaticCleanupEnabled(projectRoot)) {
151045
+ return { action: "complete" };
151046
+ }
150656
151047
  if (job.kind === "media-video-generation") {
150657
151048
  const { runMiniMaxVideoGenerationJob: runMiniMaxVideoGenerationJob2 } = await Promise.resolve().then(() => (init_video_jobs(), video_jobs_exports));
150658
151049
  return runMiniMaxVideoGenerationJob2(job, { dataDir: projectDir2, projectId });
@@ -150745,6 +151136,33 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
150745
151136
  });
150746
151137
  return { action: "complete" };
150747
151138
  }
151139
+ if (job.kind === "observation-project") {
151140
+ if (!projectRoot) {
151141
+ throw new Error(`Observation projection requires a project root for ${projectId}`);
151142
+ }
151143
+ const id = observationId(job.payload);
151144
+ if (!id) return { action: "complete" };
151145
+ const [
151146
+ { CodeGraphStore: CodeGraphStore2 },
151147
+ { bindObservationToCode: bindObservationToCode2 },
151148
+ { EvidenceCardStore: EvidenceCardStore2 },
151149
+ { getObservationStore: getObservationStore2 }
151150
+ ] = await Promise.all([
151151
+ Promise.resolve().then(() => (init_store(), store_exports)),
151152
+ Promise.resolve().then(() => (init_binder(), binder_exports)),
151153
+ Promise.resolve().then(() => (init_evidence_store(), evidence_store_exports)),
151154
+ Promise.resolve().then(() => (init_obs_store(), obs_store_exports))
151155
+ ]);
151156
+ const observation = await getObservationStore2().getById(id);
151157
+ if (!observation || observation.projectId !== projectId) return { action: "complete" };
151158
+ const codeStore = new CodeGraphStore2();
151159
+ await codeStore.init(projectDir2);
151160
+ await bindObservationToCode2(codeStore, observation);
151161
+ const evidence = new EvidenceCardStore2();
151162
+ await evidence.init(projectDir2);
151163
+ evidence.upsertObservation(observation);
151164
+ return { action: "complete" };
151165
+ }
150748
151166
  if (job.kind === "observation-qualify") {
150749
151167
  const [
150750
151168
  { CodeGraphStore: CodeGraphStore2 },
@@ -150952,7 +151370,15 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
150952
151370
  const after = getVectorStatus2(projectId);
150953
151371
  if (after.missing === 0) {
150954
151372
  resolveSupersededVectorFailures(projectDir2, projectId);
150955
- return { action: "complete" };
151373
+ return {
151374
+ action: "complete",
151375
+ progress: {
151376
+ attempted: result.attempted,
151377
+ succeeded: result.succeeded,
151378
+ failed: result.failed,
151379
+ remaining: 0
151380
+ }
151381
+ };
150956
151382
  }
150957
151383
  if (result.failed > 0 && result.succeeded === 0) {
150958
151384
  const streak = vectorBackfillFailureStreak(job.payload) + 1;
@@ -150967,6 +151393,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
150967
151393
  ...job.payload,
150968
151394
  vectorBackfillFailureStreak: streak
150969
151395
  },
151396
+ progress: {
151397
+ attempted: result.attempted,
151398
+ succeeded: result.succeeded,
151399
+ failed: result.failed,
151400
+ remaining: after.missing
151401
+ },
150970
151402
  lastError: result.lastError ?? `vector backfill made no progress (${result.failed}/${result.attempted} failed)`
150971
151403
  };
150972
151404
  }
@@ -150976,6 +151408,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
150976
151408
  action: "reschedule",
150977
151409
  delayMs: result.attempted === 0 ? VECTOR_RETRY_DELAY_MS : 0,
150978
151410
  resetAttempts: result.succeeded > 0,
151411
+ progress: {
151412
+ attempted: result.attempted,
151413
+ succeeded: result.succeeded,
151414
+ failed: result.failed,
151415
+ remaining: after.missing
151416
+ },
150979
151417
  ...result.succeeded > 0 ? {
150980
151418
  ...priorFailureStreak > 0 ? { payload } : {},
150981
151419
  ...result.failed > 0 && result.lastError ? { lastError: result.lastError } : priorFailureStreak > 0 ? { clearLastError: true } : {}
@@ -151384,24 +151822,40 @@ function queueVectorBackfill(projectId, options = {}) {
151384
151822
  });
151385
151823
  }
151386
151824
  async function bindObservationCodeRefsBestEffort(observation) {
151387
- if (!projectDir) return;
151825
+ if (!projectDir) return true;
151388
151826
  try {
151389
151827
  const { CodeGraphStore: CodeGraphStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
151390
151828
  const { bindObservationToCode: bindObservationToCode2 } = await Promise.resolve().then(() => (init_binder(), binder_exports));
151391
151829
  const codeStore = new CodeGraphStore2();
151392
151830
  await codeStore.init(projectDir);
151393
151831
  await bindObservationToCode2(codeStore, observation);
151832
+ return true;
151394
151833
  } catch {
151834
+ return false;
151395
151835
  }
151396
151836
  }
151397
151837
  async function persistEvidenceCard(observation) {
151398
- if (!projectDir) return;
151838
+ if (!projectDir) return true;
151399
151839
  try {
151400
151840
  const evidence = new EvidenceCardStore();
151401
151841
  await evidence.init(projectDir);
151402
151842
  evidence.upsertObservation(observation);
151843
+ return true;
151403
151844
  } catch (error) {
151404
151845
  console.error(`[memorix] Evidence card projection failed for obs-${observation.id}: ${error instanceof Error ? error.message : String(error)}`);
151846
+ return false;
151847
+ }
151848
+ }
151849
+ async function acknowledgeObservationProjection(observation) {
151850
+ if (!projectDir) return;
151851
+ try {
151852
+ const { MaintenanceJobStore: MaintenanceJobStore2 } = await Promise.resolve().then(() => (init_maintenance_jobs(), maintenance_jobs_exports));
151853
+ new MaintenanceJobStore2(projectDir).acknowledgePending(
151854
+ observation.projectId,
151855
+ "observation-project",
151856
+ "observation-project:" + observation.id
151857
+ );
151858
+ } catch {
151405
151859
  }
151406
151860
  }
151407
151861
  function queueClaimDerivation(observation) {
@@ -151430,6 +151884,41 @@ function queueObservationQualification(observation) {
151430
151884
  } catch {
151431
151885
  }
151432
151886
  }
151887
+ async function enqueueObservationDerivedWork(tx, observation) {
151888
+ if (!tx.enqueueMaintenanceJob) return false;
151889
+ if (!isEmbeddingExplicitlyDisabled()) {
151890
+ await tx.enqueueMaintenanceJob({
151891
+ projectId: observation.projectId,
151892
+ kind: "vector-backfill",
151893
+ dedupeKey: "vector-backfill",
151894
+ payload: { limit: 12 }
151895
+ });
151896
+ }
151897
+ if (observation.admissionState === "candidate") {
151898
+ await tx.enqueueMaintenanceJob({
151899
+ projectId: observation.projectId,
151900
+ kind: "observation-qualify",
151901
+ dedupeKey: "observation-qualify",
151902
+ payload: { source: "automatic-capture:" + observation.id, limit: 100 }
151903
+ });
151904
+ }
151905
+ const claimSource = observation.sourceDetail === "explicit" || observation.source === "git" || observation.sourceDetail === "git-ingest";
151906
+ if (claimSource && resolveObservationVisibility(observation) === "project") {
151907
+ await tx.enqueueMaintenanceJob({
151908
+ projectId: observation.projectId,
151909
+ kind: "claim-derive",
151910
+ dedupeKey: "claim-derive:" + observation.id,
151911
+ payload: { observationId: observation.id }
151912
+ });
151913
+ }
151914
+ await tx.enqueueMaintenanceJob({
151915
+ projectId: observation.projectId,
151916
+ kind: "observation-project",
151917
+ dedupeKey: "observation-project:" + observation.id,
151918
+ payload: { observationId: observation.id }
151919
+ });
151920
+ return true;
151921
+ }
151433
151922
  function isVectorCompatibleWithCurrentIndex(embedding) {
151434
151923
  if (!embedding) return false;
151435
151924
  const vectorDimensions = getVectorDimensions();
@@ -151608,7 +152097,6 @@ async function storeObservation(input) {
151608
152097
  throw new Error("Cannot update a memory outside this session's write scope.");
151609
152098
  }
151610
152099
  const observation2 = await upsertObservation(existing, input, now3);
151611
- await input.onPersisted?.(observation2);
151612
152100
  return { observation: observation2, upserted: true };
151613
152101
  }
151614
152102
  }
@@ -151635,6 +152123,7 @@ async function storeObservation(input) {
151635
152123
  let upsertedInsideLock = false;
151636
152124
  let reloadCacheAfterCommit = false;
151637
152125
  let persistedCallbackInvoked = false;
152126
+ let derivedJobsCommitted = false;
151638
152127
  const assignAndPersist = async () => {
151639
152128
  if (projectDir) {
151640
152129
  const store = getObservationStore();
@@ -151690,6 +152179,7 @@ async function storeObservation(input) {
151690
152179
  writeGeneration: transactionGeneration + 1
151691
152180
  };
151692
152181
  await tx.insert(observation);
152182
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, observation);
151693
152183
  await input.onPersisted?.(observation);
151694
152184
  persistedCallbackInvoked = true;
151695
152185
  await tx.saveIdCounter(id + 1);
@@ -151788,15 +152278,17 @@ async function storeObservation(input) {
151788
152278
  await assignAndPersist();
151789
152279
  if (upsertedInsideLock) {
151790
152280
  const updated = await upsertObservation(observation, input, now3);
151791
- await input.onPersisted?.(updated);
151792
152281
  return { observation: updated, upserted: true };
151793
152282
  }
151794
152283
  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);
152284
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(observation);
152285
+ const evidenceProjected = await persistEvidenceCard(observation);
152286
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(observation);
152287
+ if (!derivedJobsCommitted) {
152288
+ queueObservationQualification(observation);
152289
+ if (resolveObservationVisibility(observation) === "project") {
152290
+ queueClaimDerivation(observation);
152291
+ }
151800
152292
  }
151801
152293
  scheduleObservationEmbedding({
151802
152294
  observationId: observation.id,
@@ -151818,86 +152310,115 @@ async function upsertObservation(existing, input, now3) {
151818
152310
  }
151819
152311
  const fullText = [input.title, input.narrative, ...input.facts ?? [], ...enrichedFiles, ...enrichedConcepts].join(" ");
151820
152312
  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;
152313
+ const applyUpdate = (current) => ({
152314
+ ...current,
152315
+ entityName: input.entityName,
152316
+ type: input.type,
152317
+ title: input.title,
152318
+ narrative: input.narrative,
152319
+ facts: input.facts ?? [],
152320
+ attachments: input.attachments,
152321
+ filesModified: enrichedFiles,
152322
+ concepts: enrichedConcepts,
152323
+ tokens,
152324
+ updatedAt: now3,
152325
+ hasCausalLanguage: extracted.hasCausalLanguage,
152326
+ revisionCount: (current.revisionCount ?? 1) + 1,
152327
+ status: "active",
152328
+ ...input.sessionId ? { sessionId: input.sessionId } : {},
152329
+ ...input.progress ? { progress: input.progress } : {},
152330
+ ...input.sourceDetail !== void 0 ? { sourceDetail: input.sourceDetail } : {},
152331
+ ...input.valueCategory !== void 0 ? { valueCategory: input.valueCategory } : {},
152332
+ ...input.admissionState !== void 0 ? { admissionState: input.admissionState } : {},
152333
+ ...input.admissionReason !== void 0 ? { admissionReason: sanitizeCredentials(input.admissionReason) } : {},
152334
+ ...input.visibility !== void 0 ? { visibility: input.visibility } : {},
152335
+ ...input.sharedWithAgentIds !== void 0 ? { sharedWithAgentIds: input.sharedWithAgentIds } : {}
152336
+ });
152337
+ let updated = applyUpdate(existing);
152338
+ let derivedJobsCommitted = false;
152339
+ if (projectDir) {
152340
+ const store = getObservationStore();
152341
+ await store.atomic(async (tx) => {
152342
+ const current = await tx.getById(existing.id);
152343
+ if (!current || current.projectId !== existing.projectId) {
152344
+ throw new Error("Topic observation changed before update");
152345
+ }
152346
+ updated = applyUpdate(current);
152347
+ updated.writeGeneration = await tx.getGeneration() + 1;
152348
+ await tx.update(updated);
152349
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, updated);
152350
+ await input.onPersisted?.(updated);
152351
+ });
152352
+ updated.writeGeneration = store.getGeneration();
152353
+ } else {
152354
+ await input.onPersisted?.(updated);
152355
+ }
152356
+ if (corpusLoaded) {
152357
+ const cacheIndex = observations.findIndex((observation) => observation.id === updated.id);
152358
+ if (cacheIndex >= 0) observations[cacheIndex] = updated;
152359
+ }
151842
152360
  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"),
152361
+ id: makeOramaObservationId(updated.projectId, updated.id),
152362
+ observationId: updated.id,
152363
+ entityName: updated.entityName,
152364
+ type: updated.type,
152365
+ title: updated.title,
152366
+ narrative: updated.narrative,
152367
+ facts: updated.facts.join("\n"),
151850
152368
  filesModified: enrichedFiles.join("\n"),
151851
152369
  concepts: enrichedConcepts.map((c) => c.replace(/-/g, " ")).join(", "),
151852
- attachments: formatAttachmentProvenance(existing.attachments),
152370
+ attachments: formatAttachmentProvenance(updated.attachments),
151853
152371
  tokens,
151854
- createdAt: existing.createdAt,
151855
- projectId: existing.projectId,
152372
+ createdAt: updated.createdAt,
152373
+ projectId: updated.projectId,
151856
152374
  accessCount: 0,
151857
152375
  lastAccessedAt: "",
151858
152376
  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 {
152377
+ source: updated.source ?? "agent",
152378
+ sourceDetail: updated.sourceDetail ?? "",
152379
+ valueCategory: updated.valueCategory ?? "",
152380
+ admissionState: updated.admissionState ?? "",
152381
+ admissionReason: updated.admissionReason ?? "",
152382
+ visibility: updated.visibility ?? "project",
152383
+ createdByAgentId: updated.createdByAgentId ?? "",
152384
+ sharedWithAgentIds: JSON.stringify(updated.sharedWithAgentIds ?? [])
152385
+ };
152386
+ if (corpusLoaded) {
152387
+ const oramaId = makeOramaObservationId(updated.projectId, updated.id);
151877
152388
  try {
151878
- const { removeObservation: removeObs } = await Promise.resolve().then(() => (init_orama_store(), orama_store_exports));
151879
- await removeObs(oramaId);
152389
+ try {
152390
+ await removeObservation(oramaId);
152391
+ } catch {
152392
+ }
151880
152393
  await insertObservation(doc);
151881
152394
  } catch {
152395
+ try {
152396
+ try {
152397
+ await removeObservation(oramaId);
152398
+ } catch {
152399
+ }
152400
+ await insertObservation(doc);
152401
+ } catch (error) {
152402
+ console.error(`[memorix] Observation index projection failed for obs-${updated.id}: ${sanitizeCredentials(error instanceof Error ? error.message : String(error))}`);
152403
+ }
151882
152404
  }
151883
152405
  }
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);
152406
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(updated);
152407
+ const evidenceProjected = await persistEvidenceCard(updated);
152408
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(updated);
152409
+ if (!derivedJobsCommitted) {
152410
+ queueObservationQualification(updated);
152411
+ if (resolveObservationVisibility(updated) === "project") {
152412
+ queueClaimDerivation(updated);
152413
+ }
151893
152414
  }
151894
152415
  scheduleObservationEmbedding({
151895
- observationId: existing.id,
151896
- projectId: existing.projectId,
152416
+ observationId: updated.id,
152417
+ projectId: updated.projectId,
151897
152418
  searchableText: [input.title, input.narrative, ...input.facts ?? []].join(" "),
151898
152419
  doc
151899
152420
  });
151900
- return existing;
152421
+ return updated;
151901
152422
  }
151902
152423
  function getObservation(id, projectId) {
151903
152424
  return observations.find((o) => o.id === id && (projectId ? o.projectId === projectId : true));
@@ -152241,7 +152762,7 @@ function getSearchIndexStatus(projectId) {
152241
152762
  };
152242
152763
  }
152243
152764
  async function probeSearchIndex(projectId) {
152244
- await searchObservations({
152765
+ const result = await searchObservationsDetailed({
152245
152766
  query: "semantic memory retrieval status",
152246
152767
  projectId,
152247
152768
  reader: { projectId },
@@ -152249,7 +152770,7 @@ async function probeSearchIndex(projectId) {
152249
152770
  status: "all",
152250
152771
  trackAccess: false
152251
152772
  });
152252
- return getLastSearchMode(projectId);
152773
+ return result.diagnostics.mode;
152253
152774
  }
152254
152775
  async function backfillVectorEmbeddings(options = {}) {
152255
152776
  if (vectorBackfillRunning) {