memorix 1.10.2 → 1.10.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/CHANGELOG.md +82 -1
  2. package/README.md +3 -1
  3. package/README.zh-CN.md +3 -1
  4. package/dist/cli/index.js +2281 -1486
  5. package/dist/cli/memcode.js +0 -0
  6. package/dist/index.js +1874 -1126
  7. package/dist/{maintenance-jobs-DVRF-46r.d.ts → maintenance-jobs-DweoCoTT.d.ts} +25 -15
  8. package/dist/maintenance-runner.d.ts +1 -1
  9. package/dist/maintenance-runner.js +802 -194
  10. package/dist/media-audio-runner.js +793 -186
  11. package/dist/media-video-runner.js +801 -194
  12. package/dist/memcode-runtime/CHANGELOG.md +64 -1
  13. package/dist/sdk.js +14036 -13317
  14. package/dist/types.d.ts +1 -1
  15. package/dist/vector-backfill-runner.d.ts +1 -1
  16. package/dist/vector-backfill-runner.js +801 -194
  17. package/docs/ARCHITECTURE.md +219 -0
  18. package/docs/CONFIGURATION.md +49 -0
  19. package/docs/DESIGN_DECISIONS.md +37 -0
  20. package/docs/DEVELOPMENT.md +1 -1
  21. package/docs/INTEGRATIONS.md +1 -1
  22. package/docs/MODULES.md +7 -1
  23. package/docs/PERFORMANCE.md +14 -0
  24. package/docs/README.md +2 -1
  25. package/docs/ROADMAP-1.9.12-2.0.md +18 -2
  26. package/docs/SETUP.md +19 -4
  27. package/package.json +1 -1
  28. package/plugins/antigravity/memorix/plugin.json +1 -1
  29. package/plugins/claude/memorix/.claude-plugin/plugin.json +1 -1
  30. package/plugins/codebuddy/memorix/.codebuddy-plugin/plugin.json +1 -1
  31. package/plugins/codex/memorix/.codex-plugin/plugin.json +1 -1
  32. package/plugins/copilot/memorix/plugin.json +1 -1
  33. package/plugins/gemini/memorix/gemini-extension.json +1 -1
  34. package/plugins/hermes/memorix/plugin.yaml +1 -1
  35. package/plugins/omp/memorix/package.json +1 -1
  36. package/plugins/openclaw/memorix/.codex-plugin/plugin.json +1 -1
  37. package/plugins/pi/memorix/package.json +1 -1
  38. package/server.json +2 -2
  39. package/src/cli/commands/agent-integrations.ts +1 -1
  40. package/src/cli/commands/background.ts +1 -1
  41. package/src/cli/commands/context.ts +3 -2
  42. package/src/cli/commands/doctor.ts +9 -0
  43. package/src/cli/commands/explain.ts +3 -2
  44. package/src/cli/commands/init.ts +6 -2
  45. package/src/cli/commands/setup.ts +9 -6
  46. package/src/cli/commands/uninstall.ts +15 -0
  47. package/src/cli/tui/App.tsx +9 -16
  48. package/src/cli/tui/ConfigureView.tsx +2 -0
  49. package/src/cli/tui/chat-service.ts +6 -9
  50. package/src/cli/tui/data.ts +2 -2
  51. package/src/codegraph/auto-context.ts +10 -3
  52. package/src/codegraph/derived-view.ts +63 -0
  53. package/src/codegraph/store.ts +37 -0
  54. package/src/codegraph/types.ts +3 -0
  55. package/src/compact/engine.ts +10 -33
  56. package/src/config/dotenv-loader.ts +1 -0
  57. package/src/config/resolved-config.ts +18 -2
  58. package/src/config/retrieval-strategy.ts +22 -0
  59. package/src/config/toml-loader.ts +6 -0
  60. package/src/config/yaml-loader.ts +11 -2
  61. package/src/core/derived-view.ts +15 -0
  62. package/src/core/maintenance-result.ts +33 -0
  63. package/src/core/retrieval-contracts.ts +57 -0
  64. package/src/core/retrieval-facade.ts +18 -0
  65. package/src/core/retrieval-policy.ts +44 -0
  66. package/src/core/runtime-context.ts +42 -0
  67. package/src/dashboard/server.ts +5 -6
  68. package/src/embedding/api-provider.ts +18 -8
  69. package/src/hooks/handler.ts +0 -1
  70. package/src/integrations/registry.ts +2 -1
  71. package/src/knowledge/workset.ts +0 -2
  72. package/src/llm/provider.ts +2 -1
  73. package/src/memory/consolidation.ts +3 -2
  74. package/src/memory/feedback-model.ts +1 -4
  75. package/src/memory/observations.ts +226 -104
  76. package/src/multimodal/image-loader.ts +2 -2
  77. package/src/runtime/control-plane-maintenance.ts +1 -0
  78. package/src/runtime/isolated-maintenance.ts +1 -0
  79. package/src/runtime/maintenance-jobs.ts +123 -32
  80. package/src/runtime/open-browser.ts +25 -0
  81. package/src/runtime/project-maintenance.ts +69 -1
  82. package/src/sdk.ts +3 -2
  83. package/src/search/fts-view.ts +53 -0
  84. package/src/search/orama-view.ts +40 -0
  85. package/src/search/retrieval-facade.ts +38 -0
  86. package/src/search/semantic-index.ts +13 -0
  87. package/src/search/semantic-view.ts +34 -0
  88. package/src/server.ts +21 -9
  89. package/src/store/obs-store.ts +15 -0
  90. package/src/store/orama-store.ts +143 -45
  91. package/src/store/sqlite-db.ts +22 -0
  92. package/src/store/sqlite-store.ts +27 -0
  93. package/src/types.ts +1 -1
  94. package/src/workspace/mcp-adapters/pi.ts +58 -0
  95. package/plugins/pi/memorix/skills/memorix-git-memory/SKILL.md +0 -26
  96. package/plugins/pi/memorix/skills/memorix-memory/SKILL.md +0 -51
  97. package/plugins/pi/memorix/skills/memorix-mini-skills/SKILL.md +0 -31
  98. package/plugins/pi/memorix/skills/memorix-orchestrate/SKILL.md +0 -28
  99. package/plugins/pi/memorix/skills/memorix-reasoning/SKILL.md +0 -30
  100. package/plugins/pi/memorix/skills/memorix-sessions/SKILL.md +0 -25
  101. package/plugins/pi/memorix/skills/memorix-troubleshooting/SKILL.md +0 -27
@@ -193,6 +193,7 @@ function loadYamlConfig(projectRoot, options = {}) {
193
193
  llm: { ...userConfig.llm, ...projectConfig.llm },
194
194
  agent: { ...userConfig.agent, ...projectConfig.agent },
195
195
  embedding: { ...userConfig.embedding, ...projectConfig.embedding },
196
+ retrieval: { ...userConfig.retrieval, ...projectConfig.retrieval },
196
197
  rerank: { ...userConfig.rerank, ...projectConfig.rerank },
197
198
  git: { ...userConfig.git, ...projectConfig.git },
198
199
  codegraph: { ...userConfig.codegraph, ...projectConfig.codegraph },
@@ -1374,6 +1375,12 @@ CREATE TABLE IF NOT EXISTS maintenance_jobs (
1374
1375
  lease_owner TEXT,
1375
1376
  lease_expires_at INTEGER,
1376
1377
  last_error TEXT,
1378
+ attempted INTEGER NOT NULL DEFAULT 0,
1379
+ succeeded INTEGER NOT NULL DEFAULT 0,
1380
+ failed INTEGER NOT NULL DEFAULT 0,
1381
+ remaining INTEGER NOT NULL DEFAULT 0,
1382
+ progress_recorded INTEGER NOT NULL DEFAULT 0,
1383
+ rerun_requested INTEGER NOT NULL DEFAULT 0,
1377
1384
  created_at INTEGER NOT NULL,
1378
1385
  updated_at INTEGER NOT NULL,
1379
1386
  completed_at INTEGER
@@ -1794,6 +1801,22 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_maintenance_jobs_active_dedupe
1794
1801
  ON task_continuity_events(project_id, task_id, event_key)
1795
1802
  WHERE event_key IS NOT NULL`);
1796
1803
  }
1804
+ },
1805
+ {
1806
+ id: "1.11-maintenance-progress",
1807
+ apply: (db2) => {
1808
+ addColumnIfMissing(db2, "maintenance_jobs", "attempted", "attempted INTEGER NOT NULL DEFAULT 0");
1809
+ addColumnIfMissing(db2, "maintenance_jobs", "succeeded", "succeeded INTEGER NOT NULL DEFAULT 0");
1810
+ addColumnIfMissing(db2, "maintenance_jobs", "failed", "failed INTEGER NOT NULL DEFAULT 0");
1811
+ addColumnIfMissing(db2, "maintenance_jobs", "remaining", "remaining INTEGER NOT NULL DEFAULT 0");
1812
+ addColumnIfMissing(db2, "maintenance_jobs", "progress_recorded", "progress_recorded INTEGER NOT NULL DEFAULT 0");
1813
+ }
1814
+ },
1815
+ {
1816
+ id: "1.11-maintenance-rerun",
1817
+ apply: (db2) => {
1818
+ addColumnIfMissing(db2, "maintenance_jobs", "rerun_requested", "rerun_requested INTEGER NOT NULL DEFAULT 0");
1819
+ }
1797
1820
  }
1798
1821
  ];
1799
1822
  _dbCache = /* @__PURE__ */ new Map();
@@ -2273,6 +2296,7 @@ function mergeTomlConfig(base, override) {
2273
2296
  llm: { ...base.memory?.llm, ...override.memory?.llm }
2274
2297
  },
2275
2298
  embedding: { ...base.embedding, ...override.embedding },
2299
+ retrieval: { ...base.retrieval, ...override.retrieval },
2276
2300
  rerank: { ...base.rerank, ...override.rerank },
2277
2301
  hooks: { ...base.hooks, ...override.hooks },
2278
2302
  git: { ...base.git, ...override.git },
@@ -2362,6 +2386,32 @@ var init_toml_loader = __esm({
2362
2386
  }
2363
2387
  });
2364
2388
 
2389
+ // src/config/retrieval-strategy.ts
2390
+ function isCjkHeavyQuery(query) {
2391
+ if (!query) return false;
2392
+ const matches = query.match(CJK);
2393
+ return (matches?.length ?? 0) / query.length > 0.3;
2394
+ }
2395
+ function normalizeRetrievalStrategy(value) {
2396
+ if (value === "vector" || value === "hybrid") return value;
2397
+ return void 0;
2398
+ }
2399
+ function firstRetrievalStrategy(fallback, ...values) {
2400
+ for (const value of values) {
2401
+ const normalized = normalizeRetrievalStrategy(value);
2402
+ if (normalized) return normalized;
2403
+ }
2404
+ return fallback;
2405
+ }
2406
+ var CJK;
2407
+ var init_retrieval_strategy = __esm({
2408
+ "src/config/retrieval-strategy.ts"() {
2409
+ "use strict";
2410
+ init_esm_shims();
2411
+ CJK = /[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g;
2412
+ }
2413
+ });
2414
+
2365
2415
  // src/config/resolved-config.ts
2366
2416
  var resolved_config_exports = {};
2367
2417
  __export(resolved_config_exports, {
@@ -2408,7 +2458,8 @@ function getResolvedConfig(options = {}) {
2408
2458
  const isRequesty = memoryLlmProvider === "requesty";
2409
2459
  const isApiRoute = memoryLlmProvider === "apiroute";
2410
2460
  const isCheaperInference = memoryLlmProvider === "cheaperinference";
2411
- const usesPresetKeyOnly = isAtlasCloud || isRequesty || isApiRoute || isCheaperInference;
2461
+ const isRuncrate = memoryLlmProvider === "runcrate";
2462
+ const usesPresetKeyOnly = isAtlasCloud || isRequesty || isApiRoute || isCheaperInference || isRuncrate;
2412
2463
  const memoryLlmApiKey = first(
2413
2464
  process.env.MEMORIX_LLM_API_KEY,
2414
2465
  process.env.MEMORIX_API_KEY,
@@ -2416,7 +2467,7 @@ function getResolvedConfig(options = {}) {
2416
2467
  yaml.llm?.apiKey,
2417
2468
  legacy.llm?.apiKey,
2418
2469
  // Never borrow another provider's credentials for these gateway presets.
2419
- isAtlasCloud ? process.env.ATLASCLOUD_API_KEY : isRequesty ? process.env.REQUESTY_API_KEY : isApiRoute ? process.env.API_ROUTE_API_KEY : isCheaperInference ? process.env.CHEAPER_INFERENCE_API_KEY : process.env.OPENAI_API_KEY,
2470
+ isAtlasCloud ? process.env.ATLASCLOUD_API_KEY : isRequesty ? process.env.REQUESTY_API_KEY : isApiRoute ? process.env.API_ROUTE_API_KEY : isCheaperInference ? process.env.CHEAPER_INFERENCE_API_KEY : isRuncrate ? process.env.RUNCRATE_API_KEY : process.env.OPENAI_API_KEY,
2420
2471
  usesPresetKeyOnly ? void 0 : process.env.ANTHROPIC_API_KEY,
2421
2472
  usesPresetKeyOnly ? void 0 : openRouterMemoryLlmApiKey
2422
2473
  );
@@ -2470,6 +2521,10 @@ function getResolvedConfig(options = {}) {
2470
2521
  apiKey: first(process.env.MEMORIX_EMBEDDING_API_KEY, toml.embedding?.api_key, yaml.embedding?.apiKey, legacy.embeddingApi?.apiKey, openRouterEmbeddingApiKey, requestyEmbeddingApiKey),
2471
2522
  dimensions: firstNumber(parseNumber(process.env.MEMORIX_EMBEDDING_DIMENSIONS), toml.embedding?.dimensions, yaml.embedding?.dimensions, legacy.embeddingApi?.dimensions)
2472
2523
  },
2524
+ retrieval: {
2525
+ cjk: firstRetrievalStrategy("vector", process.env.MEMORIX_RETRIEVAL_CJK, toml.retrieval?.cjk, yaml.retrieval?.cjk),
2526
+ ascii: firstRetrievalStrategy("hybrid", process.env.MEMORIX_RETRIEVAL_ASCII, toml.retrieval?.ascii, yaml.retrieval?.ascii)
2527
+ },
2473
2528
  rerank: resolveRerankLane({
2474
2529
  toml,
2475
2530
  yaml,
@@ -2487,6 +2542,7 @@ function getResolvedConfig(options = {}) {
2487
2542
  codegraph: {
2488
2543
  excludePatterns: firstArray(toml.codegraph?.exclude_patterns, yaml.codegraph?.excludePatterns),
2489
2544
  maxFileBytes: firstNumber(toml.codegraph?.max_file_bytes, yaml.codegraph?.maxFileBytes),
2545
+ autoRefresh: first(toml.codegraph?.auto_refresh, yaml.codegraph?.autoRefresh, "auto"),
2490
2546
  externalContext: first(
2491
2547
  normalizeExternalContext(process.env.MEMORIX_CODEGRAPH_EXTERNAL_CONTEXT),
2492
2548
  toml.codegraph?.external_context,
@@ -2590,6 +2646,8 @@ function getEnvSourceNames() {
2590
2646
  "MEMORIX_EMBEDDING_BASE_URL",
2591
2647
  "MEMORIX_EMBEDDING_MODEL",
2592
2648
  "MEMORIX_EMBEDDING_DIMENSIONS",
2649
+ "MEMORIX_RETRIEVAL_CJK",
2650
+ "MEMORIX_RETRIEVAL_ASCII",
2593
2651
  "MEMORIX_RERANK_PROVIDER",
2594
2652
  "MEMORIX_RERANK_MODEL",
2595
2653
  "MEMORIX_RERANK_BASE_URL",
@@ -2601,6 +2659,7 @@ function getEnvSourceNames() {
2601
2659
  "REQUESTY_API_KEY",
2602
2660
  "API_ROUTE_API_KEY",
2603
2661
  "CHEAPER_INFERENCE_API_KEY",
2662
+ "RUNCRATE_API_KEY",
2604
2663
  "ATLASCLOUD_API_KEY"
2605
2664
  ].filter((name) => process.env[name]);
2606
2665
  }
@@ -2697,6 +2756,7 @@ var init_resolved_config = __esm({
2697
2756
  init_toml_loader();
2698
2757
  init_yaml_loader();
2699
2758
  init_dotenv_loader();
2759
+ init_retrieval_strategy();
2700
2760
  }
2701
2761
  });
2702
2762
 
@@ -3479,8 +3539,8 @@ async function loadCacheJsonl(filePath) {
3479
3539
  loaded = cache3.size;
3480
3540
  } catch {
3481
3541
  }
3482
- if (onDiskCount % 250 === 0) {
3483
- await new Promise((resolve2) => setImmediate(resolve2));
3542
+ if (onDiskCount % CACHE_LOAD_YIELD_EVERY === 0) {
3543
+ await new Promise((resolve2) => setTimeout(resolve2, 0));
3484
3544
  }
3485
3545
  }
3486
3546
  diskCacheEntryCount = onDiskCount;
@@ -3809,6 +3869,12 @@ async function fetchWithRetry(url, apiKey, body, options = {}, attempt = 0, nati
3809
3869
  if (err instanceof Error && (err.name === "AbortError" || controller.signal.aborted || options.signal?.aborted)) {
3810
3870
  throw new Error(`Embedding API timeout after ${timeoutMs}ms: ${url}`);
3811
3871
  }
3872
+ if (options.retry !== false && attempt < MAX_RETRIES2) {
3873
+ const delay3 = BASE_DELAY_MS * Math.pow(2, attempt);
3874
+ console.error(`[memorix] Embedding transport failure, retry ${attempt + 1}/${MAX_RETRIES2} in ${delay3}ms`);
3875
+ await waitForRetry(delay3, options.signal);
3876
+ return fetchWithRetry(url, apiKey, body, options, attempt + 1, nativeGemini);
3877
+ }
3812
3878
  throw err;
3813
3879
  }
3814
3880
  try {
@@ -3887,7 +3953,7 @@ async function waitForRetry(waitMs, signal) {
3887
3953
  abortSignal.addEventListener("abort", onAbort, { once: true });
3888
3954
  });
3889
3955
  }
3890
- 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;
3956
+ 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;
3891
3957
  var init_api_provider = __esm({
3892
3958
  "src/embedding/api-provider.ts"() {
3893
3959
  "use strict";
@@ -3915,6 +3981,7 @@ var init_api_provider = __esm({
3915
3981
  DASHSCOPE_MAX_BATCH_SIZE = 10;
3916
3982
  MAX_RETRIES2 = 3;
3917
3983
  BASE_DELAY_MS = 500;
3984
+ CACHE_LOAD_YIELD_EVERY = 32;
3918
3985
  EmbeddingAPIError = class extends Error {
3919
3986
  status;
3920
3987
  constructor(status, detail) {
@@ -3966,7 +4033,7 @@ var init_api_provider = __esm({
3966
4033
  console.error(`[memorix] Dimension shortening: ${config.requestedDimensions}d requested`);
3967
4034
  }
3968
4035
  if (allowNetworkProbe) {
3969
- startDiskCacheLoad();
4036
+ setImmediate(startDiskCacheLoad);
3970
4037
  }
3971
4038
  return new _APIEmbeddingProvider(config, probeDimensions);
3972
4039
  }
@@ -4038,10 +4105,8 @@ var init_api_provider = __esm({
4038
4105
  return this.embedInput({ modality: "text", text: normalized }, { intent: "document", ...options });
4039
4106
  }
4040
4107
  const hash4 = textHash2(normalized, this.cacheKeyNamespace);
4041
- if (diskCacheLoaded) {
4042
- const cached = cache3.get(hash4);
4043
- if (cached) return cached;
4044
- }
4108
+ const cached = cache3.get(hash4);
4109
+ if (cached) return cached;
4045
4110
  const apiCall = async () => {
4046
4111
  const body = {
4047
4112
  model: this.config.model,
@@ -4066,8 +4131,8 @@ var init_api_provider = __esm({
4066
4131
  let embedding;
4067
4132
  if (!diskCacheLoaded && diskCacheLoadPromise) {
4068
4133
  const cacheRace = diskCacheLoadPromise.then(() => {
4069
- const cached = cache3.get(hash4);
4070
- if (cached) return cached;
4134
+ const cached2 = cache3.get(hash4);
4135
+ if (cached2) return cached2;
4071
4136
  return null;
4072
4137
  });
4073
4138
  const result = await Promise.race([
@@ -5596,6 +5661,7 @@ var init_provider2 = __esm({
5596
5661
  requesty: { baseUrl: "https://router.requesty.ai/v1", model: "openai/gpt-4.1-nano" },
5597
5662
  apiroute: { baseUrl: "https://global.api-route.com/v1", model: "deepseek-v4.1-flash" },
5598
5663
  cheaperinference: { baseUrl: "https://api.cheaperinference.com/v1", model: "gpt-5.4-mini" },
5664
+ runcrate: { baseUrl: "https://api.runcrate.ai/v1", model: "deepseek-ai/DeepSeek-V4.1-Flash" },
5599
5665
  atlascloud: { baseUrl: "https://api.atlascloud.ai/v1", model: "deepseek-ai/deepseek-v3.2" },
5600
5666
  custom: { baseUrl: "http://localhost:11434/v1", model: "llama3" }
5601
5667
  };
@@ -5772,6 +5838,7 @@ var sqlite_store_exports = {};
5772
5838
  __export(sqlite_store_exports, {
5773
5839
  SqliteBackend: () => SqliteBackend
5774
5840
  });
5841
+ import { randomUUID as randomUUID2 } from "crypto";
5775
5842
  import path7 from "path";
5776
5843
  import fs4 from "fs";
5777
5844
  function obsToRow(obs) {
@@ -6160,6 +6227,32 @@ var init_sqlite_store = __esm({
6160
6227
  }, "Observation atomic write");
6161
6228
  try {
6162
6229
  const tx = {
6230
+ enqueueMaintenanceJob: async (input) => {
6231
+ const payloadJson = JSON.stringify(input.payload ?? {});
6232
+ const existing = this.db.prepare(`
6233
+ SELECT id, status FROM maintenance_jobs
6234
+ WHERE project_id = ? AND kind = ? AND dedupe_key = ?
6235
+ AND status IN ('pending', 'running', 'retry')
6236
+ LIMIT 1
6237
+ `).get(input.projectId, input.kind, input.dedupeKey);
6238
+ if (existing) {
6239
+ if (existing.status === "running") {
6240
+ this.db.prepare(`
6241
+ UPDATE maintenance_jobs
6242
+ SET rerun_requested = 1, payload_json = ?, updated_at = ?
6243
+ WHERE id = ?
6244
+ `).run(payloadJson, Date.now(), existing.id);
6245
+ }
6246
+ return;
6247
+ }
6248
+ const now3 = Date.now();
6249
+ this.db.prepare(`
6250
+ INSERT INTO maintenance_jobs (
6251
+ id, project_id, kind, dedupe_key, payload_json, status, attempts,
6252
+ max_attempts, run_after, created_at, updated_at
6253
+ ) VALUES (?, ?, ?, ?, ?, 'pending', 0, 8, ?, ?, ?)
6254
+ `).run(randomUUID2(), input.projectId, input.kind, input.dedupeKey, payloadJson, now3, now3, now3);
6255
+ },
6163
6256
  loadAll: async () => this.rawLoadAll(),
6164
6257
  getById: async (id) => this.rawGetById(id),
6165
6258
  findByTopicKey: async (projectId, topicKey) => this.rawFindByTopicKey(projectId, topicKey),
@@ -6230,6 +6323,7 @@ __export(obs_store_exports, {
6230
6323
  DegradedBackend: () => DegradedBackend,
6231
6324
  createObservationStore: () => createObservationStore,
6232
6325
  getObservationStore: () => getObservationStore,
6326
+ getObservationStoreDataDir: () => getObservationStoreDataDir,
6233
6327
  initObservationStore: () => initObservationStore,
6234
6328
  resetObservationStore: () => resetObservationStore,
6235
6329
  setObservationStore: () => setObservationStore
@@ -6240,6 +6334,12 @@ function getObservationStore() {
6240
6334
  }
6241
6335
  return _store2;
6242
6336
  }
6337
+ function getObservationStoreDataDir() {
6338
+ if (!_store2 || !_storeDataDir) {
6339
+ throw new Error("[memorix] ObservationStore data directory is not bound");
6340
+ }
6341
+ return _storeDataDir;
6342
+ }
6243
6343
  function setObservationStore(store) {
6244
6344
  _store2 = store;
6245
6345
  }
@@ -6418,6 +6518,9 @@ async function loadLanceDb() {
6418
6518
  return null;
6419
6519
  }
6420
6520
  }
6521
+ async function isSemanticIndexAvailable() {
6522
+ return await loadLanceDb() !== null;
6523
+ }
6421
6524
  function semanticIndexEnabled() {
6422
6525
  return process.env.MEMORIX_SEMANTIC_INDEX !== "off" && process.env.MEMORIX_SEMANTIC_INDEX !== "orama";
6423
6526
  }
@@ -6547,6 +6650,22 @@ async function listSemanticVectorIds(dataDir, profile) {
6547
6650
  const rows = await state.table.query().select(["observation_id"]).toArray();
6548
6651
  return new Set(rows.map((row) => Number(row.observation_id)).filter(Number.isSafeInteger));
6549
6652
  }
6653
+ async function getSemanticIndexStats(dataDir, profile) {
6654
+ const state = await getState(dataDir, profile);
6655
+ if (!state?.table) return null;
6656
+ return {
6657
+ rowCount: await state.table.countRows(),
6658
+ version: typeof state.table.version === "function" ? await state.table.version() : 0
6659
+ };
6660
+ }
6661
+ function optimizeSemanticIndex(dataDir, profile) {
6662
+ const key = stateKey(dataDir, profile);
6663
+ return queueOperation(key, async () => {
6664
+ const state = await getState(dataDir, profile);
6665
+ if (state) await optimizeState(state);
6666
+ mutationCounts.set(key, 0);
6667
+ });
6668
+ }
6550
6669
  function resolveIndexThreshold() {
6551
6670
  const raw = Number.parseInt(process.env.MEMORIX_SEMANTIC_INDEX_THRESHOLD ?? "", 10);
6552
6671
  return Number.isSafeInteger(raw) && raw > 0 ? raw : DEFAULT_INDEX_THRESHOLD;
@@ -6598,6 +6717,20 @@ async function searchSemanticVectors(options) {
6598
6717
  distance: Number(row._distance ?? Number.POSITIVE_INFINITY)
6599
6718
  })).filter((row) => Number.isFinite(row.distance));
6600
6719
  }
6720
+ async function closeSemanticIndexProfile(dataDir, profile) {
6721
+ const key = stateKey(dataDir, profile);
6722
+ await flushPendingVectorBatch(key);
6723
+ await writeQueues.get(key);
6724
+ const state = await statePromises.get(key)?.catch(() => null);
6725
+ try {
6726
+ state?.connection?.close?.();
6727
+ } catch {
6728
+ }
6729
+ statePromises.delete(key);
6730
+ writeQueues.delete(key);
6731
+ indexBuilds.delete(key);
6732
+ mutationCounts.delete(key);
6733
+ }
6601
6734
  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;
6602
6735
  var init_semantic_index = __esm({
6603
6736
  "src/search/semantic-index.ts"() {
@@ -6620,6 +6753,59 @@ var init_semantic_index = __esm({
6620
6753
  }
6621
6754
  });
6622
6755
 
6756
+ // src/search/semantic-view.ts
6757
+ function createSemanticDerivedView(dataDir, profile) {
6758
+ return {
6759
+ async status() {
6760
+ if (!await isSemanticIndexAvailable()) return { state: "unavailable" };
6761
+ const stats = await getSemanticIndexStats(dataDir, profile);
6762
+ return stats ? { state: "ready", generation: stats.version, rowCount: stats.rowCount } : { state: "missing" };
6763
+ },
6764
+ async refresh(records) {
6765
+ if (records.length === 1) await upsertSemanticVector(dataDir, profile, records[0]);
6766
+ else await upsertSemanticVectors(dataDir, profile, records);
6767
+ },
6768
+ rebuild: () => ensureSemanticIndex(dataDir, profile),
6769
+ compact: () => optimizeSemanticIndex(dataDir, profile),
6770
+ close: () => closeSemanticIndexProfile(dataDir, profile)
6771
+ };
6772
+ }
6773
+ var init_semantic_view = __esm({
6774
+ "src/search/semantic-view.ts"() {
6775
+ "use strict";
6776
+ init_esm_shims();
6777
+ init_semantic_index();
6778
+ }
6779
+ });
6780
+
6781
+ // src/core/retrieval-contracts.ts
6782
+ function createRetrievalPlan(options) {
6783
+ const requestedLimit = Number.isFinite(options.limit) ? Math.floor(options.limit ?? 20) : 20;
6784
+ const requestedTokens = Number.isFinite(options.maxTokens) ? Math.floor(options.maxTokens ?? 0) : 0;
6785
+ return {
6786
+ query: options.query.trim(),
6787
+ quality: options.quality ?? "balanced",
6788
+ limit: Math.max(1, Math.min(1e4, requestedLimit)),
6789
+ ...options.projectId ? { projectId: options.projectId } : {},
6790
+ status: options.status ?? "active",
6791
+ ...options.source ? { source: options.source } : {},
6792
+ ...options.type ? { type: options.type } : {},
6793
+ ...options.since ? { since: options.since } : {},
6794
+ ...options.until ? { until: options.until } : {},
6795
+ maxTokens: Math.max(0, requestedTokens),
6796
+ trackAccess: options.trackAccess !== false,
6797
+ reader: options.reader,
6798
+ surfacedIds: [...options.surfacedIds ?? []],
6799
+ signal: options.signal
6800
+ };
6801
+ }
6802
+ var init_retrieval_contracts = __esm({
6803
+ "src/core/retrieval-contracts.ts"() {
6804
+ "use strict";
6805
+ init_esm_shims();
6806
+ }
6807
+ });
6808
+
6623
6809
  // src/memory/secret-filter.ts
6624
6810
  function applyRedaction(text2) {
6625
6811
  if (!text2) return text2;
@@ -7280,6 +7466,7 @@ var orama_store_exports = {};
7280
7466
  __export(orama_store_exports, {
7281
7467
  _classifyQueryTier: () => classifyQueryTier,
7282
7468
  batchGenerateEmbeddings: () => batchGenerateEmbeddings,
7469
+ countIndexedDocuments: () => countIndexedDocuments,
7283
7470
  createSearchTokenizer: () => createSearchTokenizer,
7284
7471
  generateEmbedding: () => generateEmbedding,
7285
7472
  generateEmbeddingInput: () => generateEmbeddingInput,
@@ -7303,10 +7490,19 @@ __export(orama_store_exports, {
7303
7490
  queueSemanticVector: () => queueSemanticVector,
7304
7491
  removeObservation: () => removeObservation,
7305
7492
  resetDb: () => resetDb,
7493
+ resolveSearchFuzzyTolerance: () => resolveSearchFuzzyTolerance,
7306
7494
  searchObservations: () => searchObservations,
7495
+ searchObservationsDetailed: () => searchObservationsDetailed,
7307
7496
  updateObservationMetadata: () => updateObservationMetadata
7308
7497
  });
7309
7498
  import { components, create, insert as insert2, insertMultiple, search, remove as remove2, update, count, getByID } from "@orama/orama";
7499
+ function resolveSearchFuzzyTolerance(query, quality) {
7500
+ if (quality === "fast") return void 0;
7501
+ const characters = [...query];
7502
+ const cjkCount = characters.filter((char) => /[\u3400-\u4dbf\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]/u.test(char)).length;
7503
+ if (characters.length > 0 && cjkCount / characters.length > 0.3) return void 0;
7504
+ return query.length > 6 ? 2 : 1;
7505
+ }
7310
7506
  function rememberSearchMode(key, value) {
7311
7507
  if (!lastSearchModeByProject.has(key) && lastSearchModeByProject.size >= MAX_SEARCH_MODE_KEYS) {
7312
7508
  const oldest = lastSearchModeByProject.keys().next().value;
@@ -7485,6 +7681,46 @@ async function searchPersistentLexically(options, projectIds, limit2) {
7485
7681
  return null;
7486
7682
  }
7487
7683
  }
7684
+ async function searchLanceInVectorOrder(options, projectIds, limit2, queryVector, provider2) {
7685
+ try {
7686
+ const { getObservationDataDir: getObservationDataDir2 } = await Promise.resolve().then(() => (init_observations(), observations_exports));
7687
+ const dataDir = getObservationDataDir2();
7688
+ if (!dataDir) return null;
7689
+ const vectorHits = await searchSemanticVectors({
7690
+ dataDir,
7691
+ profile: createSemanticIndexProfile(provider2),
7692
+ vector: queryVector,
7693
+ projectId: projectIds ?? options.projectId,
7694
+ status: "all",
7695
+ limit: Math.min(1e4, Math.max(limit2, 1) * 4)
7696
+ });
7697
+ if (!vectorHits || vectorHits.length === 0) return null;
7698
+ const store = getObservationStore();
7699
+ const hits = [];
7700
+ const seen = /* @__PURE__ */ new Set();
7701
+ for (const hit of vectorHits) {
7702
+ if (seen.has(hit.observationId)) continue;
7703
+ seen.add(hit.observationId);
7704
+ const observation = await store.getById(hit.observationId);
7705
+ if (!observation) continue;
7706
+ if (projectIds && !projectIds.includes(observation.projectId)) continue;
7707
+ if (options.status !== "all" && (observation.status ?? "active") !== (options.status ?? "active")) continue;
7708
+ if (options.type && observation.type !== options.type) continue;
7709
+ if (options.source && observation.source !== options.source) continue;
7710
+ const document2 = observationToSearchDocument(observation);
7711
+ hits.push({
7712
+ id: document2.id,
7713
+ score: 1 / (1 + hits.length),
7714
+ document: document2
7715
+ });
7716
+ if (hits.length >= limit2) break;
7717
+ }
7718
+ if (hits.length === 0) return null;
7719
+ return { count: hits.length, hits };
7720
+ } catch {
7721
+ return null;
7722
+ }
7723
+ }
7488
7724
  async function searchPersistentSemantically(options, projectIds, limit2, queryVector, provider2) {
7489
7725
  try {
7490
7726
  const { getObservationDataDir: getObservationDataDir2 } = await Promise.resolve().then(() => (init_observations(), observations_exports));
@@ -7649,6 +7885,9 @@ async function getDb(options = {}) {
7649
7885
  }
7650
7886
  }
7651
7887
  }
7888
+ async function countIndexedDocuments(database) {
7889
+ return count(database ?? await getDb({ allowNetworkProbe: false }));
7890
+ }
7652
7891
  async function resetDb() {
7653
7892
  dbGeneration++;
7654
7893
  db = null;
@@ -7678,7 +7917,7 @@ async function queueSemanticVector(dataDir, record80) {
7678
7917
  const profile = provider2 ? createSemanticIndexProfile(provider2) : null;
7679
7918
  if (!profile) return;
7680
7919
  try {
7681
- await upsertSemanticVector(dataDir, profile, record80);
7920
+ await createSemanticDerivedView(dataDir, profile).refresh([record80]);
7682
7921
  } catch {
7683
7922
  }
7684
7923
  }
@@ -7769,7 +8008,7 @@ async function attachCachedVectors(database, observations2) {
7769
8008
  }
7770
8009
  }
7771
8010
  if (semanticDataDir && semanticProfile && semanticRecords.length > 0) {
7772
- void upsertSemanticVectors(semanticDataDir, semanticProfile, semanticRecords).catch(() => {
8011
+ void createSemanticDerivedView(semanticDataDir, semanticProfile).refresh(semanticRecords).catch(() => {
7773
8012
  });
7774
8013
  }
7775
8014
  await new Promise((resolve2) => setImmediate(resolve2));
@@ -7880,7 +8119,9 @@ async function removeObservation(oramaId) {
7880
8119
  const database = await getDb();
7881
8120
  await remove2(database, oramaId);
7882
8121
  }
7883
- async function searchObservations(options) {
8122
+ async function searchObservationsDetailed(options) {
8123
+ const retrievalPlan = createRetrievalPlan(options);
8124
+ options = { ...options, ...retrievalPlan };
7884
8125
  const searchStartedAt = Date.now();
7885
8126
  const perf = !!process.env.MEMORIX_PERF;
7886
8127
  const t0 = perf ? performance.now() : 0;
@@ -7894,10 +8135,12 @@ async function searchObservations(options) {
7894
8135
  const modeKey = options.projectId ?? SEARCH_MODE_DEFAULT_KEY;
7895
8136
  const quality = options.quality ?? "balanced";
7896
8137
  const database = await getDb();
7897
- rememberSearchMode(
7898
- modeKey,
7899
- quality === "fast" ? "fulltext (fast profile)" : embeddingEnabled ? "hybrid" : "fulltext"
7900
- );
8138
+ let requestMode = quality === "fast" ? "fulltext (fast profile)" : embeddingEnabled ? "hybrid" : "fulltext";
8139
+ const setMode = (mode) => {
8140
+ requestMode = mode;
8141
+ rememberSearchMode(modeKey, mode);
8142
+ };
8143
+ setMode(requestMode);
7901
8144
  let projectIds = null;
7902
8145
  if (options.projectId) {
7903
8146
  try {
@@ -7918,7 +8161,7 @@ async function searchObservations(options) {
7918
8161
  filters["source"] = options.source;
7919
8162
  }
7920
8163
  const hasQuery = options.query && options.query.trim().length > 0;
7921
- const originalQuery = options.query;
8164
+ const originalQuery = retrievalPlan.query;
7922
8165
  const tier = quality === "fast" ? "fast" : hasQuery ? classifyQueryTier(originalQuery) : "fast";
7923
8166
  mark(`tier=${tier}`);
7924
8167
  if (quality === "thorough" && hasQuery) {
@@ -7952,7 +8195,10 @@ async function searchObservations(options) {
7952
8195
  // Fuzzy tolerance: allow 1-char typos for short queries, 2 for longer
7953
8196
  // Fuzzy matching is useful for ordinary recall, but grows sharply with
7954
8197
  // corpus size. The fast profile deliberately uses exact lexical matching.
7955
- ...hasQuery && quality !== "fast" ? { tolerance: originalQuery.length > 6 ? 2 : 1 } : {}
8198
+ ...hasQuery ? (() => {
8199
+ const tolerance = resolveSearchFuzzyTolerance(originalQuery, quality);
8200
+ return tolerance === void 0 ? {} : { tolerance };
8201
+ })() : {}
7956
8202
  };
7957
8203
  let queryVector = null;
7958
8204
  let embeddingProviderForSearch = null;
@@ -7969,10 +8215,7 @@ async function searchObservations(options) {
7969
8215
  embeddingUnavailable = true;
7970
8216
  fallbackUsed = true;
7971
8217
  fallbackReason = "embedding dimension mismatch; lexical search used";
7972
- rememberSearchMode(
7973
- modeKey,
7974
- `fulltext (embedding dimension mismatch: provider ${provider2.dimensions}d vs index ${activeVectorDimensions}d)`
7975
- );
8218
+ setMode(`fulltext (embedding dimension mismatch: provider ${provider2.dimensions}d vs index ${activeVectorDimensions}d)`);
7976
8219
  console.error(
7977
8220
  `[memorix] Embedding provider dimension mismatch (${provider2.dimensions}d provider vs ${activeVectorDimensions}d index); using fulltext search`
7978
8221
  );
@@ -7994,7 +8237,7 @@ async function searchObservations(options) {
7994
8237
  mark("embedding");
7995
8238
  const cjkRatio = (originalQuery.match(/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g) || []).length / originalQuery.length;
7996
8239
  const isCJKHeavy = cjkRatio > 0.3;
7997
- rememberSearchMode(modeKey, "hybrid");
8240
+ setMode("hybrid");
7998
8241
  searchParams = {
7999
8242
  ...searchParams,
8000
8243
  mode: "hybrid",
@@ -8017,32 +8260,41 @@ async function searchObservations(options) {
8017
8260
  embeddingUnavailable = true;
8018
8261
  fallbackUsed = true;
8019
8262
  fallbackReason = "embedding failed or timed out; lexical search used";
8020
- rememberSearchMode(modeKey, "fulltext (embedding unavailable)");
8263
+ setMode("fulltext (embedding unavailable)");
8021
8264
  console.error("[memorix] Embedding failed or timed out, falling back to fulltext search");
8022
8265
  }
8023
8266
  }
8024
8267
  mark("preSearch");
8025
8268
  let results;
8269
+ const retrieval = getResolvedConfig().retrieval;
8270
+ const wantLanceOrder = (isCjkHeavyQuery(originalQuery ?? "") ? retrieval.cjk : retrieval.ascii) === "vector";
8271
+ let lanceOrderUsed = false;
8272
+ let persistent = null;
8273
+ if (wantLanceOrder && queryVector && embeddingProviderForSearch) {
8274
+ persistent = await searchLanceInVectorOrder(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch);
8275
+ if (persistent) lanceOrderUsed = true;
8276
+ else {
8277
+ fallbackUsed = true;
8278
+ fallbackReason = fallbackReason ?? "lance vector index empty; hybrid search used";
8279
+ }
8280
+ }
8026
8281
  const persistentCorpusEligible = await shouldUsePersistentSearch(projectIds, options.projectId);
8027
8282
  const canUsePersistentLexical = persistentCorpusEligible && Boolean(hasQuery) && !queryVector && (quality === "fast" || tier === "fast" || !embeddingEnabled || embeddingUnavailable);
8028
- let persistent = persistentCorpusEligible && queryVector && embeddingProviderForSearch ? await searchPersistentSemantically(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch) : canUsePersistentLexical ? await searchPersistentLexically(options, projectIds, requestLimit) : null;
8283
+ if (!persistent) persistent = persistentCorpusEligible && queryVector && embeddingProviderForSearch ? await searchPersistentSemantically(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch) : canUsePersistentLexical ? await searchPersistentLexically(options, projectIds, requestLimit) : null;
8029
8284
  const durableStore = getOptionalObservationStore();
8030
8285
  if (!persistent && queryVector && durableStore?.hasLexicalIndex?.() && count(database) === 0) {
8031
8286
  persistent = await searchPersistentLexically(options, projectIds, requestLimit);
8032
8287
  }
8033
8288
  if (persistent) {
8034
8289
  results = persistent;
8035
- rememberSearchMode(
8036
- modeKey,
8037
- queryVector ? "hybrid" : quality === "fast" ? "fulltext (fast profile)" : "fulltext"
8038
- );
8290
+ setMode(lanceOrderUsed ? "vector" : queryVector ? "hybrid" : quality === "fast" ? "fulltext (fast profile)" : "fulltext");
8039
8291
  mark(queryVector ? "persistentHybridSearch" : "sqliteFtsSearch");
8040
8292
  } else {
8041
8293
  try {
8042
8294
  results = await search(database, searchParams);
8043
8295
  } catch (error) {
8044
8296
  if (queryVector && isVectorDimensionMismatchError(error)) {
8045
- rememberSearchMode(modeKey, "fulltext (embedding dimension mismatch)");
8297
+ setMode("fulltext (embedding dimension mismatch)");
8046
8298
  console.error("[memorix] Vector search dimension mismatch detected, retrying without embeddings");
8047
8299
  results = await search(database, stripVectorSearchParams(searchParams));
8048
8300
  } else {
@@ -8065,7 +8317,7 @@ async function searchObservations(options) {
8065
8317
  },
8066
8318
  similarity: 0.25
8067
8319
  };
8068
- rememberSearchMode(modeKey, "vector-only (hybrid empty fallback)");
8320
+ setMode("vector-only (hybrid empty fallback)");
8069
8321
  fallbackUsed = true;
8070
8322
  fallbackReason = "hybrid search returned no results; vector-only fallback used";
8071
8323
  results = await search(database, vectorOnlyParams);
@@ -8183,14 +8435,16 @@ async function searchObservations(options) {
8183
8435
  filesModified: doc.filesModified?.split?.("\n") ?? (Array.isArray(doc.filesModified) ? doc.filesModified : [])
8184
8436
  });
8185
8437
  }
8438
+ const topScore = Math.max(...intermediate.map((entry) => entry.score));
8439
+ const affinityTieWindow = topScore * 0.92;
8186
8440
  intermediate = intermediate.map((entry) => {
8187
8441
  const memory = memoryContentMap.get(entry.id);
8188
8442
  if (!memory) return entry;
8189
8443
  const { score: affinityScore } = calculateProjectAffinity(memory, affinityContext);
8444
+ if (entry.score < affinityTieWindow) return entry;
8190
8445
  return {
8191
8446
  ...entry,
8192
- score: entry.score * affinityScore
8193
- // Apply affinity as multiplier
8447
+ score: entry.score * (0.98 + affinityScore * 0.02)
8194
8448
  };
8195
8449
  });
8196
8450
  intermediate.sort((a, b) => b.score - a.score);
@@ -8308,7 +8562,7 @@ async function searchObservations(options) {
8308
8562
  const rerankedTop = neural.map((row) => candidateMap.get(row.id)).filter((entry) => entry != null);
8309
8563
  if (rerankedTop.length > 0) {
8310
8564
  intermediate = [...rerankedTop, ...intermediate.slice(RERANK_TOP_K)];
8311
- rememberSearchMode(modeKey, (lastSearchModeByProject.get(modeKey) ?? "fulltext") + " + neural rerank");
8565
+ setMode(requestMode + " + neural rerank");
8312
8566
  mark("rerank(usedNeural=true)");
8313
8567
  }
8314
8568
  }
@@ -8325,7 +8579,7 @@ async function searchObservations(options) {
8325
8579
  );
8326
8580
  mark(`rerank(usedLLM=${usedLLM})`);
8327
8581
  if (usedLLM) {
8328
- rememberSearchMode(modeKey, (lastSearchModeByProject.get(modeKey) ?? "fulltext") + " + LLM rerank");
8582
+ setMode(requestMode + " + LLM rerank");
8329
8583
  const rerankedTop = reranked.map((row) => candidateMap.get(row.id)).filter((entry) => entry != null);
8330
8584
  if (rerankedTop.length > 0) {
8331
8585
  intermediate = [...rerankedTop, ...intermediate.slice(RERANK_TOP_K)];
@@ -8388,9 +8642,9 @@ async function searchObservations(options) {
8388
8642
  if (options.maxTokens && options.maxTokens > 0) {
8389
8643
  entries = applyTokenBudget(entries, options.maxTokens);
8390
8644
  }
8391
- rememberSearchDiagnostics(modeKey, {
8645
+ const diagnostics = {
8392
8646
  version: "1",
8393
- mode: getLastSearchMode(options.projectId),
8647
+ mode: requestMode,
8394
8648
  rawCandidateCount: results.hits.length,
8395
8649
  candidateCount,
8396
8650
  selectedCount: entries.length,
@@ -8399,14 +8653,25 @@ async function searchObservations(options) {
8399
8653
  fallbackUsed,
8400
8654
  ...fallbackReason ? { fallbackReason } : {},
8401
8655
  elapsedMs: Math.max(0, Date.now() - searchStartedAt)
8402
- });
8403
- if (options.trackAccess !== false) {
8404
- const returnedKeys = new Set(entries.map((entry) => makeEntryKey(entry.projectId, entry.id)));
8656
+ };
8657
+ rememberSearchDiagnostics(modeKey, diagnostics);
8658
+ const recordAccess = (selected) => {
8659
+ if (options.trackAccess === false || selected.length === 0) return;
8660
+ const returnedKeys = new Set(selected.map((entry) => makeEntryKey(entry.projectId, entry.id)));
8405
8661
  const hitDocs = results.hits.map((hit) => ({ id: hit.id, doc: hit.document })).filter(({ doc }) => returnedKeys.has(makeEntryKey(doc.projectId, doc.observationId)));
8406
8662
  recordAccessBatch(hitDocs).catch(() => {
8407
8663
  });
8664
+ };
8665
+ const derivedViews = getSearchDerivedViews();
8666
+ if (fallbackUsed && fallbackReason) {
8667
+ derivedViews.embedding = { freshness: "stale", rebuildStatus: "failed", failureReason: fallbackReason };
8408
8668
  }
8409
- return entries;
8669
+ return { entries, diagnostics, derivedViews, recordAccess };
8670
+ }
8671
+ async function searchObservations(options) {
8672
+ const result = await searchObservationsDetailed(options);
8673
+ result.recordAccess?.(result.entries);
8674
+ return result.entries;
8410
8675
  }
8411
8676
  async function getObservationsByIds(ids, projectId) {
8412
8677
  const database = await getDb();
@@ -8531,6 +8796,10 @@ var init_orama_store = __esm({
8531
8796
  init_policy();
8532
8797
  init_timeout();
8533
8798
  init_obs_store();
8799
+ init_resolved_config();
8800
+ init_retrieval_strategy();
8801
+ init_semantic_view();
8802
+ init_retrieval_contracts();
8534
8803
  init_semantic_index();
8535
8804
  init_derived_view_receipt();
8536
8805
  db = null;
@@ -8657,6 +8926,24 @@ var init_entity_extractor = __esm({
8657
8926
  }
8658
8927
  });
8659
8928
 
8929
+ // src/core/maintenance-result.ts
8930
+ function assertMaintenanceProgress(progress) {
8931
+ if (!progress) return;
8932
+ const counts = [progress.attempted, progress.succeeded, progress.failed, progress.remaining];
8933
+ if (counts.some((count2) => !Number.isSafeInteger(count2) || count2 < 0)) {
8934
+ throw new Error("maintenance progress must contain non-negative safe integers");
8935
+ }
8936
+ if (progress.succeeded + progress.failed > progress.attempted) {
8937
+ throw new Error("maintenance progress outcomes exceed attempted work");
8938
+ }
8939
+ }
8940
+ var init_maintenance_result = __esm({
8941
+ "src/core/maintenance-result.ts"() {
8942
+ "use strict";
8943
+ init_esm_shims();
8944
+ }
8945
+ });
8946
+
8660
8947
  // src/runtime/maintenance-jobs.ts
8661
8948
  var maintenance_jobs_exports = {};
8662
8949
  __export(maintenance_jobs_exports, {
@@ -8666,7 +8953,7 @@ __export(maintenance_jobs_exports, {
8666
8953
  MaintenanceJobWorker: () => MaintenanceJobWorker,
8667
8954
  getMaintenanceRetryDelayMs: () => getMaintenanceRetryDelayMs
8668
8955
  });
8669
- import { randomUUID as randomUUID2 } from "crypto";
8956
+ import { randomUUID as randomUUID3 } from "crypto";
8670
8957
  function parsePayload(raw) {
8671
8958
  if (typeof raw !== "string" || !raw) return {};
8672
8959
  try {
@@ -8690,6 +8977,12 @@ function rowToJob(row) {
8690
8977
  ...row.lease_owner ? { leaseOwner: row.lease_owner } : {},
8691
8978
  ...row.lease_expires_at != null ? { leaseExpiresAt: Number(row.lease_expires_at) } : {},
8692
8979
  ...row.last_error ? { lastError: row.last_error } : {},
8980
+ ...Number(row.progress_recorded ?? 0) === 1 ? { progress: {
8981
+ attempted: Number(row.attempted ?? 0),
8982
+ succeeded: Number(row.succeeded ?? 0),
8983
+ failed: Number(row.failed ?? 0),
8984
+ remaining: Number(row.remaining ?? 0)
8985
+ } } : {},
8693
8986
  createdAt: Number(row.created_at),
8694
8987
  updatedAt: Number(row.updated_at),
8695
8988
  ...row.completed_at != null ? { completedAt: Number(row.completed_at) } : {}
@@ -8715,6 +9008,7 @@ var init_maintenance_jobs = __esm({
8715
9008
  "src/runtime/maintenance-jobs.ts"() {
8716
9009
  "use strict";
8717
9010
  init_esm_shims();
9011
+ init_maintenance_result();
8718
9012
  init_sqlite_db();
8719
9013
  init_secret_filter();
8720
9014
  MAINTENANCE_JOB_KINDS = [
@@ -8725,6 +9019,7 @@ var init_maintenance_jobs = __esm({
8725
9019
  "consolidation",
8726
9020
  "codegraph-refresh",
8727
9021
  "observation-qualify",
9022
+ "observation-project",
8728
9023
  "claim-derive",
8729
9024
  "claim-requalification",
8730
9025
  "knowledge-compile",
@@ -8763,6 +9058,16 @@ var init_maintenance_jobs = __esm({
8763
9058
  this.commit();
8764
9059
  return rowToJob(existing);
8765
9060
  }
9061
+ if (existing.status === "running") {
9062
+ this.db.prepare(`
9063
+ UPDATE maintenance_jobs
9064
+ SET rerun_requested = 1, payload_json = ?, updated_at = ?
9065
+ WHERE id = ?
9066
+ `).run(payloadJson, now3, existing.id);
9067
+ const updated2 = this.getRow(existing.id);
9068
+ this.commit();
9069
+ return rowToJob(updated2);
9070
+ }
8766
9071
  const nextRunAfter = Math.min(Number(existing.run_after), runAfter);
8767
9072
  this.db.prepare(`
8768
9073
  UPDATE maintenance_jobs
@@ -8793,7 +9098,7 @@ var init_maintenance_jobs = __esm({
8793
9098
  return rowToJob(revived);
8794
9099
  }
8795
9100
  }
8796
- const id = randomUUID2();
9101
+ const id = randomUUID3();
8797
9102
  this.db.prepare(`
8798
9103
  INSERT INTO maintenance_jobs (
8799
9104
  id, project_id, kind, dedupe_key, payload_json, status, attempts,
@@ -8890,8 +9195,10 @@ var init_maintenance_jobs = __esm({
8890
9195
  this.db.prepare(`
8891
9196
  UPDATE maintenance_jobs
8892
9197
  SET
8893
- status = CASE WHEN attempts >= max_attempts THEN 'failed' ELSE 'retry' END,
8894
- run_after = CASE WHEN attempts >= max_attempts THEN run_after ELSE ? END,
9198
+ status = CASE WHEN attempts >= max_attempts AND rerun_requested = 0 THEN 'failed' ELSE 'retry' END,
9199
+ run_after = CASE WHEN attempts >= max_attempts AND rerun_requested = 0 THEN run_after ELSE ? END,
9200
+ attempts = CASE WHEN rerun_requested = 1 AND attempts >= max_attempts THEN 0 ELSE attempts END,
9201
+ rerun_requested = 0,
8895
9202
  lease_owner = NULL,
8896
9203
  lease_expires_at = NULL,
8897
9204
  last_error = COALESCE(last_error, 'worker lease expired'),
@@ -8954,14 +9261,55 @@ var init_maintenance_jobs = __esm({
8954
9261
  `).run(expiresAt, now3, id, workerId);
8955
9262
  return Number(result.changes) > 0;
8956
9263
  }
8957
- complete(id, workerId, now3 = Date.now()) {
8958
- this.db.prepare(`
8959
- UPDATE maintenance_jobs
8960
- SET status = 'completed', lease_owner = NULL, lease_expires_at = NULL,
8961
- completed_at = ?, updated_at = ?
8962
- WHERE id = ? AND status = 'running' AND lease_owner = ?
8963
- `).run(now3, now3, id, workerId);
8964
- return this.get(id);
9264
+ complete(id, workerId, now3 = Date.now(), progress) {
9265
+ assertMaintenanceProgress(progress);
9266
+ this.begin();
9267
+ try {
9268
+ const current = this.db.prepare(`
9269
+ SELECT rerun_requested FROM maintenance_jobs
9270
+ WHERE id = ? AND status = 'running' AND lease_owner = ?
9271
+ `).get(id, workerId);
9272
+ if (!current) {
9273
+ this.commit();
9274
+ return void 0;
9275
+ }
9276
+ if (Number(current.rerun_requested) === 1) {
9277
+ this.db.prepare(`
9278
+ UPDATE maintenance_jobs
9279
+ SET status = 'pending', attempts = 0, run_after = ?,
9280
+ rerun_requested = 0, lease_owner = NULL, lease_expires_at = NULL,
9281
+ attempted = 0, succeeded = 0, failed = 0, remaining = 0,
9282
+ progress_recorded = 0, last_error = NULL, completed_at = NULL,
9283
+ updated_at = ?
9284
+ WHERE id = ?
9285
+ `).run(now3, now3, id);
9286
+ } else {
9287
+ this.db.prepare(`
9288
+ UPDATE maintenance_jobs
9289
+ SET status = 'completed', lease_owner = NULL, lease_expires_at = NULL,
9290
+ attempted = COALESCE(?, attempted), succeeded = COALESCE(?, succeeded),
9291
+ failed = COALESCE(?, failed), remaining = COALESCE(?, remaining),
9292
+ progress_recorded = CASE WHEN ? THEN 1 ELSE progress_recorded END,
9293
+ completed_at = ?, updated_at = ?
9294
+ WHERE id = ?
9295
+ `).run(
9296
+ progress?.attempted ?? null,
9297
+ progress?.succeeded ?? null,
9298
+ progress?.failed ?? null,
9299
+ progress?.remaining ?? null,
9300
+ progress ? 1 : 0,
9301
+ now3,
9302
+ now3,
9303
+ id
9304
+ );
9305
+ }
9306
+ const updated = this.get(id);
9307
+ this.commit();
9308
+ return updated;
9309
+ } catch (error) {
9310
+ this.rollback();
9311
+ throw error;
9312
+ }
8965
9313
  }
8966
9314
  reschedule(id, workerId, options) {
8967
9315
  const now3 = options.now ?? Date.now();
@@ -8970,22 +9318,37 @@ var init_maintenance_jobs = __esm({
8970
9318
  const status = options.status === "retry" ? "retry" : "pending";
8971
9319
  const hasLastError = options.lastError !== void 0;
8972
9320
  const lastError = hasLastError ? errorText(options.lastError) : null;
9321
+ const progress = options.progress;
9322
+ assertMaintenanceProgress(progress);
8973
9323
  this.db.prepare(`
8974
9324
  UPDATE maintenance_jobs
8975
- SET status = ?, run_after = ?, attempts = CASE WHEN ? THEN 0 ELSE attempts END,
8976
- payload_json = COALESCE(?, payload_json),
9325
+ SET status = ?,
9326
+ run_after = CASE WHEN rerun_requested = 1 AND ? = 0 THEN ? ELSE ? END,
9327
+ attempts = CASE WHEN rerun_requested = 1 AND ? = 0 THEN 0 WHEN ? THEN 0 ELSE attempts END,
9328
+ payload_json = CASE WHEN rerun_requested = 1 THEN payload_json ELSE COALESCE(?, payload_json) END,
9329
+ attempted = COALESCE(?, attempted), succeeded = COALESCE(?, succeeded),
9330
+ failed = COALESCE(?, failed), remaining = COALESCE(?, remaining),
9331
+ progress_recorded = CASE WHEN ? THEN 1 ELSE progress_recorded END,
8977
9332
  last_error = CASE
8978
9333
  WHEN ? THEN NULL
8979
9334
  WHEN ? THEN ?
8980
9335
  ELSE last_error
8981
9336
  END,
8982
- lease_owner = NULL, lease_expires_at = NULL, updated_at = ?
9337
+ rerun_requested = 0, lease_owner = NULL, lease_expires_at = NULL, updated_at = ?
8983
9338
  WHERE id = ? AND status = 'running' AND lease_owner = ?
8984
9339
  `).run(
8985
9340
  status,
9341
+ status === "retry" ? 1 : 0,
9342
+ now3,
8986
9343
  now3 + delayMs,
9344
+ status === "retry" ? 1 : 0,
8987
9345
  options.resetAttempts ? 1 : 0,
8988
9346
  payloadJson,
9347
+ progress?.attempted ?? null,
9348
+ progress?.succeeded ?? null,
9349
+ progress?.failed ?? null,
9350
+ progress?.remaining ?? null,
9351
+ progress ? 1 : 0,
8989
9352
  options.clearLastError ? 1 : 0,
8990
9353
  hasLastError ? 1 : 0,
8991
9354
  lastError,
@@ -9003,6 +9366,15 @@ var init_maintenance_jobs = __esm({
9003
9366
  `).run(now3, now3, projectId, dedupeKey);
9004
9367
  return Number(result.changes ?? 0);
9005
9368
  }
9369
+ /** A successful foreground projection can acknowledge its pending outbox row. */
9370
+ acknowledgePending(projectId, kind, dedupeKey, now3 = Date.now()) {
9371
+ const result = this.db.prepare(`
9372
+ UPDATE maintenance_jobs
9373
+ SET status = 'completed', completed_at = ?, updated_at = ?
9374
+ WHERE project_id = ? AND kind = ? AND dedupe_key = ? AND status = 'pending'
9375
+ `).run(now3, now3, projectId, kind, dedupeKey);
9376
+ return Number(result.changes ?? 0);
9377
+ }
9006
9378
  fail(id, workerId, error, now3 = Date.now()) {
9007
9379
  this.begin();
9008
9380
  try {
@@ -9015,15 +9387,18 @@ var init_maintenance_jobs = __esm({
9015
9387
  return void 0;
9016
9388
  }
9017
9389
  const attempts = Number(current.attempts);
9018
- const exhausted = attempts >= Number(current.max_attempts);
9390
+ const rerunRequested = Number(current.rerun_requested) === 1;
9391
+ const exhausted = attempts >= Number(current.max_attempts) && !rerunRequested;
9019
9392
  const status = exhausted ? "failed" : "retry";
9020
9393
  const runAfter = exhausted ? Number(current.run_after) : now3 + getMaintenanceRetryDelayMs(attempts);
9394
+ const nextAttempts = rerunRequested && attempts >= Number(current.max_attempts) ? 0 : attempts;
9021
9395
  this.db.prepare(`
9022
9396
  UPDATE maintenance_jobs
9023
- SET status = ?, run_after = ?, lease_owner = NULL, lease_expires_at = NULL,
9397
+ SET status = ?, run_after = ?, attempts = ?, rerun_requested = 0,
9398
+ lease_owner = NULL, lease_expires_at = NULL,
9024
9399
  last_error = ?, updated_at = ?
9025
9400
  WHERE id = ?
9026
- `).run(status, runAfter, errorText(error), now3, id);
9401
+ `).run(status, runAfter, nextAttempts, errorText(error), now3, id);
9027
9402
  const updated = this.getRow(id);
9028
9403
  this.commit();
9029
9404
  return rowToJob(updated);
@@ -9052,7 +9427,7 @@ var init_maintenance_jobs = __esm({
9052
9427
  constructor(store, handler, options = {}) {
9053
9428
  this.store = store;
9054
9429
  this.handler = handler;
9055
- this.workerId = options.workerId ?? `memorix-${process.pid}-${randomUUID2().slice(0, 8)}`;
9430
+ this.workerId = options.workerId ?? `memorix-${process.pid}-${randomUUID3().slice(0, 8)}`;
9056
9431
  this.leaseMs = clampPositiveInteger(options.leaseMs, DEFAULT_LEASE_MS);
9057
9432
  this.pollIntervalMs = clampPositiveInteger(options.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS);
9058
9433
  this.projectId = options.projectId;
@@ -9101,12 +9476,16 @@ var init_maintenance_jobs = __esm({
9101
9476
  status: result.status,
9102
9477
  lastError: result.lastError,
9103
9478
  clearLastError: result.clearLastError,
9479
+ progress: result.progress,
9104
9480
  now: now3
9105
9481
  });
9106
9482
  return { state: "rescheduled", job: updated2 };
9107
9483
  }
9108
- const updated = this.store.complete(job.id, this.workerId, now3);
9109
- return { state: "completed", job: updated };
9484
+ if (result?.progress && result.progress.remaining > 0) {
9485
+ throw new Error("maintenance job reported completion with remaining work");
9486
+ }
9487
+ const updated = this.store.complete(job.id, this.workerId, now3, result?.progress);
9488
+ return { state: updated?.status === "pending" ? "rescheduled" : "completed", job: updated };
9110
9489
  } catch (error) {
9111
9490
  const updated = this.store.fail(job.id, this.workerId, error, now3);
9112
9491
  return { state: "failed", job: updated };
@@ -9204,7 +9583,12 @@ var init_lifecycle = __esm({
9204
9583
  });
9205
9584
 
9206
9585
  // src/store/evidence-store.ts
9207
- import { createHash as createHash5, randomUUID as randomUUID3 } from "crypto";
9586
+ var evidence_store_exports = {};
9587
+ __export(evidence_store_exports, {
9588
+ EvidenceCardStore: () => EvidenceCardStore,
9589
+ buildEvidenceCardId: () => buildEvidenceCardId
9590
+ });
9591
+ import { createHash as createHash5, randomUUID as randomUUID4 } from "crypto";
9208
9592
  function safeJson(value, fallback) {
9209
9593
  if (typeof value !== "string" || value.length === 0) return fallback;
9210
9594
  try {
@@ -9253,6 +9637,9 @@ function sourceKind(observation) {
9253
9637
  if (observation.sourceDetail === "hook") return "hook";
9254
9638
  return observation.source ?? "agent";
9255
9639
  }
9640
+ function buildEvidenceCardId(projectId, candidateKind, candidateId) {
9641
+ return `evidence:${candidateKind}:${projectId}:${candidateId}`;
9642
+ }
9256
9643
  var EvidenceCardStore;
9257
9644
  var init_evidence_store = __esm({
9258
9645
  "src/store/evidence-store.ts"() {
@@ -9393,7 +9780,7 @@ var init_evidence_store = __esm({
9393
9780
  }
9394
9781
  recordEvent(projectId, cardId, kind, detail) {
9395
9782
  const event = {
9396
- id: randomUUID3(),
9783
+ id: randomUUID4(),
9397
9784
  projectId,
9398
9785
  cardId,
9399
9786
  kind,
@@ -9461,7 +9848,7 @@ var store_exports = {};
9461
9848
  __export(store_exports, {
9462
9849
  CodeGraphStore: () => CodeGraphStore
9463
9850
  });
9464
- import { randomUUID as randomUUID4 } from "crypto";
9851
+ import { randomUUID as randomUUID5 } from "crypto";
9465
9852
  import { posix as pathPosix } from "path";
9466
9853
  function rowToFile(row) {
9467
9854
  return {
@@ -10390,8 +10777,9 @@ var init_store = __esm({
10390
10777
  * so an interrupted scan cannot be advertised as complete.
10391
10778
  */
10392
10779
  recordCodeStateSnapshot(input) {
10393
- const id = randomUUID4();
10780
+ const id = randomUUID5();
10394
10781
  let snapshot;
10782
+ let compactNeeded = false;
10395
10783
  const tx = this.db.transaction(() => {
10396
10784
  const previous = this.db.prepare(
10397
10785
  "SELECT id, sourceEpoch FROM code_state_snapshots WHERE projectId = ? ORDER BY sourceEpoch DESC LIMIT 1"
@@ -10435,6 +10823,26 @@ var init_store = __esm({
10435
10823
  for (const file of snapshotFileRows) {
10436
10824
  insertSnapshotFile.run(id, file.projectId, file.id, file.path, file.contentHash);
10437
10825
  }
10826
+ const staleSymbolIds = this.db.prepare(
10827
+ "SELECT id FROM code_symbols WHERE projectId = ? AND stale = 1"
10828
+ ).all(input.projectId).map((row) => row.id);
10829
+ if (staleSymbolIds.length > 0) {
10830
+ const placeholders = staleSymbolIds.map(() => "?").join(", ");
10831
+ this.db.prepare(
10832
+ `DELETE FROM code_edges WHERE projectId = ? AND (fromSymbolId IN (${placeholders}) OR toSymbolId IN (${placeholders}))`
10833
+ ).run(input.projectId, ...staleSymbolIds, ...staleSymbolIds);
10834
+ this.db.prepare("DELETE FROM code_symbols WHERE projectId = ? AND stale = 1").run(input.projectId);
10835
+ compactNeeded = true;
10836
+ }
10837
+ const oldSnapshots = this.db.prepare(
10838
+ "SELECT id FROM code_state_snapshots WHERE projectId = ? ORDER BY sourceEpoch DESC LIMIT -1 OFFSET 2"
10839
+ ).all(input.projectId).map((row) => row.id);
10840
+ if (oldSnapshots.length > 0) {
10841
+ const placeholders = oldSnapshots.map(() => "?").join(", ");
10842
+ this.db.prepare(`DELETE FROM code_state_snapshot_files WHERE snapshotId IN (${placeholders})`).run(...oldSnapshots);
10843
+ this.db.prepare(`DELETE FROM code_state_snapshots WHERE id IN (${placeholders})`).run(...oldSnapshots);
10844
+ compactNeeded = true;
10845
+ }
10438
10846
  snapshot = {
10439
10847
  ...input,
10440
10848
  id,
@@ -10443,11 +10851,24 @@ var init_store = __esm({
10443
10851
  };
10444
10852
  });
10445
10853
  tx();
10854
+ if (compactNeeded) this.compactStorage();
10446
10855
  return snapshot;
10447
10856
  }
10857
+ /** Reclaim WAL/free pages after a derived codegraph sweep. */
10858
+ compactStorage() {
10859
+ try {
10860
+ this.db.pragma("wal_checkpoint(TRUNCATE)");
10861
+ } catch {
10862
+ }
10863
+ try {
10864
+ this.db.exec("VACUUM");
10865
+ } catch {
10866
+ }
10867
+ }
10448
10868
  status(projectId) {
10449
10869
  const files = this.db.prepare(`SELECT COUNT(*) AS count FROM code_files WHERE projectId = ?`).get(projectId).count;
10450
10870
  const symbols = this.db.prepare(`SELECT COUNT(*) AS count FROM code_symbols WHERE projectId = ? AND stale = 0`).get(projectId).count;
10871
+ const staleSymbols = this.db.prepare(`SELECT COUNT(*) AS count FROM code_symbols WHERE projectId = ? AND stale = 1`).get(projectId).count;
10451
10872
  const edges = this.db.prepare(`SELECT COUNT(*) AS count FROM code_edges WHERE projectId = ?`).get(projectId).count;
10452
10873
  const refs = this.db.prepare(`SELECT COUNT(*) AS count FROM observation_code_refs WHERE projectId = ?`).get(projectId).count;
10453
10874
  const semanticSymbols = this.db.prepare(`SELECT COUNT(*) AS count FROM code_symbols WHERE projectId = ? AND stale = 0 AND source = 'typescript-compiler'`).get(projectId).count;
@@ -10455,6 +10876,8 @@ var init_store = __esm({
10455
10876
  const parserErrors = this.db.prepare(`SELECT COUNT(*) AS count FROM code_files WHERE projectId = ? AND parserError IS NOT NULL`).get(projectId).count;
10456
10877
  const latest = this.db.prepare(`SELECT MAX(indexedAt) AS indexedAt FROM code_files WHERE projectId = ?`).get(projectId);
10457
10878
  const latestSnapshot = this.latestSnapshot(projectId);
10879
+ const snapshots = this.db.prepare(`SELECT COUNT(*) AS count FROM code_state_snapshots WHERE projectId = ?`).get(projectId).count;
10880
+ const snapshotFiles = this.db.prepare(`SELECT COUNT(*) AS count FROM code_state_snapshot_files WHERE projectId = ?`).get(projectId).count;
10458
10881
  return {
10459
10882
  provider: "lite",
10460
10883
  files,
@@ -10464,6 +10887,9 @@ var init_store = __esm({
10464
10887
  semanticSymbols,
10465
10888
  semanticEdges,
10466
10889
  parserErrors,
10890
+ staleSymbols,
10891
+ snapshots,
10892
+ snapshotFiles,
10467
10893
  ...latest?.indexedAt ? { indexedAt: latest.indexedAt } : {},
10468
10894
  ...latestSnapshot ? { latestSnapshot } : {}
10469
10895
  };
@@ -10669,10 +11095,22 @@ function resetObservationRuntime() {
10669
11095
  loadedObservationStore = null;
10670
11096
  embeddingWriteMode = "background";
10671
11097
  embeddingWorkerProjectRoot = void 0;
10672
- vectorMissingIds.clear();
11098
+ clearVectorMissingIds();
10673
11099
  vectorSchemaUpgradePromise = null;
10674
11100
  embeddingFailureLogTimestamps.clear();
10675
11101
  }
11102
+ function markVectorMissing(observationId2, projectId) {
11103
+ vectorMissingIds.add(observationId2);
11104
+ vectorMissingProjectIds.set(observationId2, projectId);
11105
+ }
11106
+ function clearVectorMissing(observationId2) {
11107
+ vectorMissingIds.delete(observationId2);
11108
+ vectorMissingProjectIds.delete(observationId2);
11109
+ }
11110
+ function clearVectorMissingIds() {
11111
+ vectorMissingIds.clear();
11112
+ vectorMissingProjectIds.clear();
11113
+ }
10676
11114
  function logEmbeddingFailureOnce(key, message) {
10677
11115
  const now3 = Date.now();
10678
11116
  const last = embeddingFailureLogTimestamps.get(key) ?? 0;
@@ -10739,24 +11177,40 @@ function queueVectorBackfill(projectId, options = {}) {
10739
11177
  });
10740
11178
  }
10741
11179
  async function bindObservationCodeRefsBestEffort(observation) {
10742
- if (!projectDir) return;
11180
+ if (!projectDir) return true;
10743
11181
  try {
10744
11182
  const { CodeGraphStore: CodeGraphStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
10745
11183
  const { bindObservationToCode: bindObservationToCode2 } = await Promise.resolve().then(() => (init_binder(), binder_exports));
10746
11184
  const codeStore = new CodeGraphStore2();
10747
11185
  await codeStore.init(projectDir);
10748
11186
  await bindObservationToCode2(codeStore, observation);
11187
+ return true;
10749
11188
  } catch {
11189
+ return false;
10750
11190
  }
10751
11191
  }
10752
11192
  async function persistEvidenceCard(observation) {
10753
- if (!projectDir) return;
11193
+ if (!projectDir) return true;
10754
11194
  try {
10755
11195
  const evidence = new EvidenceCardStore();
10756
11196
  await evidence.init(projectDir);
10757
11197
  evidence.upsertObservation(observation);
11198
+ return true;
10758
11199
  } catch (error) {
10759
11200
  console.error(`[memorix] Evidence card projection failed for obs-${observation.id}: ${error instanceof Error ? error.message : String(error)}`);
11201
+ return false;
11202
+ }
11203
+ }
11204
+ async function acknowledgeObservationProjection(observation) {
11205
+ if (!projectDir) return;
11206
+ try {
11207
+ const { MaintenanceJobStore: MaintenanceJobStore2 } = await Promise.resolve().then(() => (init_maintenance_jobs(), maintenance_jobs_exports));
11208
+ new MaintenanceJobStore2(projectDir).acknowledgePending(
11209
+ observation.projectId,
11210
+ "observation-project",
11211
+ "observation-project:" + observation.id
11212
+ );
11213
+ } catch {
10760
11214
  }
10761
11215
  }
10762
11216
  function queueClaimDerivation(observation) {
@@ -10785,6 +11239,41 @@ function queueObservationQualification(observation) {
10785
11239
  } catch {
10786
11240
  }
10787
11241
  }
11242
+ async function enqueueObservationDerivedWork(tx, observation) {
11243
+ if (!tx.enqueueMaintenanceJob) return false;
11244
+ if (!isEmbeddingExplicitlyDisabled()) {
11245
+ await tx.enqueueMaintenanceJob({
11246
+ projectId: observation.projectId,
11247
+ kind: "vector-backfill",
11248
+ dedupeKey: "vector-backfill",
11249
+ payload: { limit: 12 }
11250
+ });
11251
+ }
11252
+ if (observation.admissionState === "candidate") {
11253
+ await tx.enqueueMaintenanceJob({
11254
+ projectId: observation.projectId,
11255
+ kind: "observation-qualify",
11256
+ dedupeKey: "observation-qualify",
11257
+ payload: { source: "automatic-capture:" + observation.id, limit: 100 }
11258
+ });
11259
+ }
11260
+ const claimSource = observation.sourceDetail === "explicit" || observation.source === "git" || observation.sourceDetail === "git-ingest";
11261
+ if (claimSource && resolveObservationVisibility(observation) === "project") {
11262
+ await tx.enqueueMaintenanceJob({
11263
+ projectId: observation.projectId,
11264
+ kind: "claim-derive",
11265
+ dedupeKey: "claim-derive:" + observation.id,
11266
+ payload: { observationId: observation.id }
11267
+ });
11268
+ }
11269
+ await tx.enqueueMaintenanceJob({
11270
+ projectId: observation.projectId,
11271
+ kind: "observation-project",
11272
+ dedupeKey: "observation-project:" + observation.id,
11273
+ payload: { observationId: observation.id }
11274
+ });
11275
+ return true;
11276
+ }
10788
11277
  function isVectorCompatibleWithCurrentIndex(embedding) {
10789
11278
  if (!embedding) return false;
10790
11279
  const vectorDimensions = getVectorDimensions();
@@ -10792,10 +11281,13 @@ function isVectorCompatibleWithCurrentIndex(embedding) {
10792
11281
  }
10793
11282
  async function upgradeVectorSchemaAfterFirstEmbedding(embedding) {
10794
11283
  if (isVectorCompatibleWithCurrentIndex(embedding)) return true;
10795
- if (getVectorDimensions() !== null || !embedding.every(Number.isFinite)) return false;
11284
+ if (!embedding.every(Number.isFinite)) return false;
10796
11285
  const targetProjectDir = projectDir;
10797
11286
  if (!vectorSchemaUpgradePromise) {
10798
- vectorSchemaUpgradePromise = reindexObservations().then(() => projectDir === targetProjectDir && isVectorCompatibleWithCurrentIndex(embedding)).catch(() => false).finally(() => {
11287
+ vectorSchemaUpgradePromise = getDb().then(async () => {
11288
+ if (getVectorDimensions() === null && observations.length > 0) await reindexObservations();
11289
+ return projectDir === targetProjectDir && isVectorCompatibleWithCurrentIndex(embedding);
11290
+ }).catch(() => false).finally(() => {
10799
11291
  vectorSchemaUpgradePromise = null;
10800
11292
  });
10801
11293
  }
@@ -10835,9 +11327,9 @@ async function initObservations(dir, options = {}) {
10835
11327
  }
10836
11328
  function scheduleObservationEmbedding(input) {
10837
11329
  const { observationId: observationId2, projectId, searchableText, doc } = input;
10838
- vectorMissingIds.add(observationId2);
11330
+ markVectorMissing(observationId2, projectId);
10839
11331
  if (isEmbeddingExplicitlyDisabled()) {
10840
- vectorMissingIds.delete(observationId2);
11332
+ clearVectorMissing(observationId2);
10841
11333
  return;
10842
11334
  }
10843
11335
  if (embeddingWriteMode === "deferred") {
@@ -10872,13 +11364,13 @@ function scheduleObservationEmbedding(input) {
10872
11364
  vector: embedding
10873
11365
  });
10874
11366
  }
10875
- vectorMissingIds.delete(observationId2);
11367
+ clearVectorMissing(observationId2);
10876
11368
  } catch {
10877
11369
  console.error(`[memorix] Embedding index update failed for obs-${observationId2} (kept in backfill queue)`);
10878
11370
  queueVectorBackfill(projectId);
10879
11371
  }
10880
11372
  } else if (isEmbeddingExplicitlyDisabled()) {
10881
- vectorMissingIds.delete(observationId2);
11373
+ clearVectorMissing(observationId2);
10882
11374
  } else {
10883
11375
  queueVectorBackfill(projectId);
10884
11376
  logEmbeddingFailureOnce(
@@ -10960,7 +11452,6 @@ async function storeObservation(input) {
10960
11452
  throw new Error("Cannot update a memory outside this session's write scope.");
10961
11453
  }
10962
11454
  const observation2 = await upsertObservation(existing, input, now3);
10963
- await input.onPersisted?.(observation2);
10964
11455
  return { observation: observation2, upserted: true };
10965
11456
  }
10966
11457
  }
@@ -10987,6 +11478,7 @@ async function storeObservation(input) {
10987
11478
  let upsertedInsideLock = false;
10988
11479
  let reloadCacheAfterCommit = false;
10989
11480
  let persistedCallbackInvoked = false;
11481
+ let derivedJobsCommitted = false;
10990
11482
  const assignAndPersist = async () => {
10991
11483
  if (projectDir) {
10992
11484
  const store = getObservationStore();
@@ -11042,6 +11534,7 @@ async function storeObservation(input) {
11042
11534
  writeGeneration: transactionGeneration + 1
11043
11535
  };
11044
11536
  await tx.insert(observation);
11537
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, observation);
11045
11538
  await input.onPersisted?.(observation);
11046
11539
  persistedCallbackInvoked = true;
11047
11540
  await tx.saveIdCounter(id + 1);
@@ -11140,15 +11633,17 @@ async function storeObservation(input) {
11140
11633
  await assignAndPersist();
11141
11634
  if (upsertedInsideLock) {
11142
11635
  const updated = await upsertObservation(observation, input, now3);
11143
- await input.onPersisted?.(updated);
11144
11636
  return { observation: updated, upserted: true };
11145
11637
  }
11146
11638
  if (!persistedCallbackInvoked) await input.onPersisted?.(observation);
11147
- await bindObservationCodeRefsBestEffort(observation);
11148
- await persistEvidenceCard(observation);
11149
- queueObservationQualification(observation);
11150
- if (resolveObservationVisibility(observation) === "project") {
11151
- queueClaimDerivation(observation);
11639
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(observation);
11640
+ const evidenceProjected = await persistEvidenceCard(observation);
11641
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(observation);
11642
+ if (!derivedJobsCommitted) {
11643
+ queueObservationQualification(observation);
11644
+ if (resolveObservationVisibility(observation) === "project") {
11645
+ queueClaimDerivation(observation);
11646
+ }
11152
11647
  }
11153
11648
  scheduleObservationEmbedding({
11154
11649
  observationId: observation.id,
@@ -11170,86 +11665,115 @@ async function upsertObservation(existing, input, now3) {
11170
11665
  }
11171
11666
  const fullText = [input.title, input.narrative, ...input.facts ?? [], ...enrichedFiles, ...enrichedConcepts].join(" ");
11172
11667
  const tokens = countTextTokens(fullText);
11173
- existing.entityName = input.entityName;
11174
- existing.type = input.type;
11175
- existing.title = input.title;
11176
- existing.narrative = input.narrative;
11177
- existing.facts = input.facts ?? [];
11178
- existing.attachments = input.attachments;
11179
- existing.filesModified = enrichedFiles;
11180
- existing.concepts = enrichedConcepts;
11181
- existing.tokens = tokens;
11182
- existing.updatedAt = now3;
11183
- existing.hasCausalLanguage = extracted.hasCausalLanguage;
11184
- existing.revisionCount = (existing.revisionCount ?? 1) + 1;
11185
- existing.status = "active";
11186
- if (input.sessionId) existing.sessionId = input.sessionId;
11187
- if (input.progress) existing.progress = input.progress;
11188
- if (input.sourceDetail !== void 0) existing.sourceDetail = input.sourceDetail;
11189
- if (input.valueCategory !== void 0) existing.valueCategory = input.valueCategory;
11190
- if (input.admissionState !== void 0) existing.admissionState = input.admissionState;
11191
- if (input.admissionReason !== void 0) existing.admissionReason = sanitizeCredentials(input.admissionReason);
11192
- if (input.visibility !== void 0) existing.visibility = input.visibility;
11193
- if (input.sharedWithAgentIds !== void 0) existing.sharedWithAgentIds = input.sharedWithAgentIds;
11668
+ const applyUpdate = (current) => ({
11669
+ ...current,
11670
+ entityName: input.entityName,
11671
+ type: input.type,
11672
+ title: input.title,
11673
+ narrative: input.narrative,
11674
+ facts: input.facts ?? [],
11675
+ attachments: input.attachments,
11676
+ filesModified: enrichedFiles,
11677
+ concepts: enrichedConcepts,
11678
+ tokens,
11679
+ updatedAt: now3,
11680
+ hasCausalLanguage: extracted.hasCausalLanguage,
11681
+ revisionCount: (current.revisionCount ?? 1) + 1,
11682
+ status: "active",
11683
+ ...input.sessionId ? { sessionId: input.sessionId } : {},
11684
+ ...input.progress ? { progress: input.progress } : {},
11685
+ ...input.sourceDetail !== void 0 ? { sourceDetail: input.sourceDetail } : {},
11686
+ ...input.valueCategory !== void 0 ? { valueCategory: input.valueCategory } : {},
11687
+ ...input.admissionState !== void 0 ? { admissionState: input.admissionState } : {},
11688
+ ...input.admissionReason !== void 0 ? { admissionReason: sanitizeCredentials(input.admissionReason) } : {},
11689
+ ...input.visibility !== void 0 ? { visibility: input.visibility } : {},
11690
+ ...input.sharedWithAgentIds !== void 0 ? { sharedWithAgentIds: input.sharedWithAgentIds } : {}
11691
+ });
11692
+ let updated = applyUpdate(existing);
11693
+ let derivedJobsCommitted = false;
11694
+ if (projectDir) {
11695
+ const store = getObservationStore();
11696
+ await store.atomic(async (tx) => {
11697
+ const current = await tx.getById(existing.id);
11698
+ if (!current || current.projectId !== existing.projectId) {
11699
+ throw new Error("Topic observation changed before update");
11700
+ }
11701
+ updated = applyUpdate(current);
11702
+ updated.writeGeneration = await tx.getGeneration() + 1;
11703
+ await tx.update(updated);
11704
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, updated);
11705
+ await input.onPersisted?.(updated);
11706
+ });
11707
+ updated.writeGeneration = store.getGeneration();
11708
+ } else {
11709
+ await input.onPersisted?.(updated);
11710
+ }
11711
+ if (corpusLoaded) {
11712
+ const cacheIndex = observations.findIndex((observation) => observation.id === updated.id);
11713
+ if (cacheIndex >= 0) observations[cacheIndex] = updated;
11714
+ }
11194
11715
  const doc = {
11195
- id: makeOramaObservationId(existing.projectId, existing.id),
11196
- observationId: existing.id,
11197
- entityName: existing.entityName,
11198
- type: existing.type,
11199
- title: existing.title,
11200
- narrative: existing.narrative,
11201
- facts: existing.facts.join("\n"),
11716
+ id: makeOramaObservationId(updated.projectId, updated.id),
11717
+ observationId: updated.id,
11718
+ entityName: updated.entityName,
11719
+ type: updated.type,
11720
+ title: updated.title,
11721
+ narrative: updated.narrative,
11722
+ facts: updated.facts.join("\n"),
11202
11723
  filesModified: enrichedFiles.join("\n"),
11203
11724
  concepts: enrichedConcepts.map((c) => c.replace(/-/g, " ")).join(", "),
11204
- attachments: formatAttachmentProvenance(existing.attachments),
11725
+ attachments: formatAttachmentProvenance(updated.attachments),
11205
11726
  tokens,
11206
- createdAt: existing.createdAt,
11207
- projectId: existing.projectId,
11727
+ createdAt: updated.createdAt,
11728
+ projectId: updated.projectId,
11208
11729
  accessCount: 0,
11209
11730
  lastAccessedAt: "",
11210
11731
  status: "active",
11211
- source: existing.source ?? "agent",
11212
- sourceDetail: existing.sourceDetail ?? "",
11213
- valueCategory: existing.valueCategory ?? "",
11214
- admissionState: existing.admissionState ?? "",
11215
- admissionReason: existing.admissionReason ?? "",
11216
- visibility: existing.visibility ?? "project",
11217
- createdByAgentId: existing.createdByAgentId ?? "",
11218
- sharedWithAgentIds: JSON.stringify(existing.sharedWithAgentIds ?? [])
11219
- };
11220
- const oramaId = makeOramaObservationId(existing.projectId, existing.id);
11221
- try {
11222
- const { removeObservation: removeObservation2 } = await Promise.resolve().then(() => (init_orama_store(), orama_store_exports));
11223
- await removeObservation2(oramaId);
11224
- } catch {
11225
- }
11226
- try {
11227
- await insertObservation(doc);
11228
- } catch {
11732
+ source: updated.source ?? "agent",
11733
+ sourceDetail: updated.sourceDetail ?? "",
11734
+ valueCategory: updated.valueCategory ?? "",
11735
+ admissionState: updated.admissionState ?? "",
11736
+ admissionReason: updated.admissionReason ?? "",
11737
+ visibility: updated.visibility ?? "project",
11738
+ createdByAgentId: updated.createdByAgentId ?? "",
11739
+ sharedWithAgentIds: JSON.stringify(updated.sharedWithAgentIds ?? [])
11740
+ };
11741
+ if (corpusLoaded) {
11742
+ const oramaId = makeOramaObservationId(updated.projectId, updated.id);
11229
11743
  try {
11230
- const { removeObservation: removeObs } = await Promise.resolve().then(() => (init_orama_store(), orama_store_exports));
11231
- await removeObs(oramaId);
11744
+ try {
11745
+ await removeObservation(oramaId);
11746
+ } catch {
11747
+ }
11232
11748
  await insertObservation(doc);
11233
11749
  } catch {
11750
+ try {
11751
+ try {
11752
+ await removeObservation(oramaId);
11753
+ } catch {
11754
+ }
11755
+ await insertObservation(doc);
11756
+ } catch (error) {
11757
+ console.error(`[memorix] Observation index projection failed for obs-${updated.id}: ${sanitizeCredentials(error instanceof Error ? error.message : String(error))}`);
11758
+ }
11234
11759
  }
11235
11760
  }
11236
- if (projectDir) {
11237
- const store = getObservationStore();
11238
- await store.update(existing);
11239
- }
11240
- await bindObservationCodeRefsBestEffort(existing);
11241
- await persistEvidenceCard(existing);
11242
- queueObservationQualification(existing);
11243
- if (resolveObservationVisibility(existing) === "project") {
11244
- queueClaimDerivation(existing);
11761
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(updated);
11762
+ const evidenceProjected = await persistEvidenceCard(updated);
11763
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(updated);
11764
+ if (!derivedJobsCommitted) {
11765
+ queueObservationQualification(updated);
11766
+ if (resolveObservationVisibility(updated) === "project") {
11767
+ queueClaimDerivation(updated);
11768
+ }
11245
11769
  }
11246
11770
  scheduleObservationEmbedding({
11247
- observationId: existing.id,
11248
- projectId: existing.projectId,
11771
+ observationId: updated.id,
11772
+ projectId: updated.projectId,
11249
11773
  searchableText: [input.title, input.narrative, ...input.facts ?? []].join(" "),
11250
11774
  doc
11251
11775
  });
11252
- return existing;
11776
+ return updated;
11253
11777
  }
11254
11778
  function getObservation(id, projectId) {
11255
11779
  return observations.find((o) => o.id === id && (projectId ? o.projectId === projectId : true));
@@ -11438,7 +11962,7 @@ async function reindexObservations() {
11438
11962
  if (observations.length === 0) return 0;
11439
11963
  await resetDb();
11440
11964
  searchIndexPrepared = false;
11441
- vectorMissingIds.clear();
11965
+ clearVectorMissingIds();
11442
11966
  let embeddings = observations.map(() => null);
11443
11967
  const provider2 = await getEmbeddingProvider();
11444
11968
  const canBatchEmbedAtStartup = provider2 !== null && !provider2.name.startsWith("api-");
@@ -11503,7 +12027,7 @@ async function reindexObservations() {
11503
12027
  };
11504
12028
  await insertObservation(doc);
11505
12029
  if (!compatibleEmbedding && !isEmbeddingExplicitlyDisabled()) {
11506
- vectorMissingIds.add(obs.id);
12030
+ markVectorMissing(obs.id, obs.projectId);
11507
12031
  }
11508
12032
  count2++;
11509
12033
  } catch (err) {
@@ -11520,7 +12044,17 @@ async function prepareSearchIndex(options = {}) {
11520
12044
  if (!isEmbeddingExplicitlyDisabled()) {
11521
12045
  const store = getObservationStore();
11522
12046
  const projects = await store.listProjectIds?.() ?? [];
11523
- for (const projectId of projects) queueVectorBackfill(projectId);
12047
+ await getDb({ allowNetworkProbe: false }).catch(() => void 0);
12048
+ const persistedIds = projectDir ? await getPersistentSemanticVectorIds(projectDir).catch(() => null) : null;
12049
+ for (const projectId of projects) {
12050
+ const projectObservations = await store.loadByProject(projectId);
12051
+ for (const observation of projectObservations) {
12052
+ if (!persistedIds?.has(observation.id)) markVectorMissing(observation.id, observation.projectId);
12053
+ }
12054
+ if (projectObservations.some((observation) => !persistedIds?.has(observation.id))) {
12055
+ queueVectorBackfill(projectId);
12056
+ }
12057
+ }
11524
12058
  }
11525
12059
  return 0;
11526
12060
  }
@@ -11534,13 +12068,13 @@ async function prepareSearchIndex(options = {}) {
11534
12068
  const hydratedProjectDir = projectDir;
11535
12069
  const queueMissingVectors = async () => {
11536
12070
  if (!hydratedProjectDir || projectDir !== hydratedProjectDir) return;
11537
- vectorMissingIds.clear();
12071
+ clearVectorMissingIds();
11538
12072
  if (!isEmbeddingExplicitlyDisabled()) {
11539
12073
  const persistedSemanticIds = await getPersistentSemanticVectorIds(hydratedProjectDir).catch(() => null);
11540
12074
  const projectsWithMissingVectors = /* @__PURE__ */ new Set();
11541
12075
  for (const obs of observations) {
11542
12076
  if (!hasObservationVector(obs.projectId, obs.id) && !persistedSemanticIds?.has(obs.id)) {
11543
- vectorMissingIds.add(obs.id);
12077
+ markVectorMissing(obs.id, obs.projectId);
11544
12078
  projectsWithMissingVectors.add(obs.projectId);
11545
12079
  }
11546
12080
  }
@@ -11558,6 +12092,9 @@ async function prepareSearchIndex(options = {}) {
11558
12092
  }
11559
12093
  function getVectorMissingIds(projectId) {
11560
12094
  if (!projectId) return [...vectorMissingIds];
12095
+ if (!corpusLoaded) {
12096
+ return [...vectorMissingIds].filter((id) => vectorMissingProjectIds.get(id) === projectId);
12097
+ }
11561
12098
  const observationById = new Map(observations.map((observation) => [observation.id, observation]));
11562
12099
  return [...vectorMissingIds].filter((id) => observationById.get(id)?.projectId === projectId);
11563
12100
  }
@@ -11580,7 +12117,7 @@ function getSearchIndexStatus(projectId) {
11580
12117
  };
11581
12118
  }
11582
12119
  async function probeSearchIndex(projectId) {
11583
- await searchObservations({
12120
+ const result = await searchObservationsDetailed({
11584
12121
  query: "semantic memory retrieval status",
11585
12122
  projectId,
11586
12123
  reader: { projectId },
@@ -11588,14 +12125,15 @@ async function probeSearchIndex(projectId) {
11588
12125
  status: "all",
11589
12126
  trackAccess: false
11590
12127
  });
11591
- return getLastSearchMode(projectId);
12128
+ return result.diagnostics.mode;
11592
12129
  }
11593
12130
  async function backfillVectorEmbeddings(options = {}) {
11594
12131
  if (vectorBackfillRunning) {
11595
12132
  return { attempted: 0, succeeded: 0, failed: 0 };
11596
12133
  }
11597
12134
  vectorBackfillRunning = true;
11598
- const observationById = new Map(observations.map((observation) => [observation.id, observation]));
12135
+ const sourceObservations = corpusLoaded ? observations : options.projectId ? await getObservationStore().loadByProject(options.projectId, { status: "active" }) : await getObservationStore().loadAll();
12136
+ const observationById = new Map(sourceObservations.map((observation) => [observation.id, observation]));
11599
12137
  const limit2 = Number.isFinite(options.limit) ? Math.max(1, Math.floor(options.limit)) : Number.POSITIVE_INFINITY;
11600
12138
  const ids = [...vectorMissingIds].filter((id) => !options.projectId || observationById.get(id)?.projectId === options.projectId).slice(0, limit2);
11601
12139
  let succeeded = 0;
@@ -11608,7 +12146,7 @@ async function backfillVectorEmbeddings(options = {}) {
11608
12146
  for (const id of ids) {
11609
12147
  const observation = observationById.get(id);
11610
12148
  if (!observation) {
11611
- vectorMissingIds.delete(id);
12149
+ clearVectorMissing(id);
11612
12150
  continue;
11613
12151
  }
11614
12152
  candidates.push({
@@ -11626,7 +12164,7 @@ async function backfillVectorEmbeddings(options = {}) {
11626
12164
  const provider2 = await getEmbeddingProvider();
11627
12165
  if (!provider2) {
11628
12166
  if (isEmbeddingExplicitlyDisabled()) {
11629
- for (const candidate of candidates) vectorMissingIds.delete(candidate.id);
12167
+ for (const candidate of candidates) clearVectorMissing(candidate.id);
11630
12168
  } else {
11631
12169
  recordFailure("embedding provider unavailable");
11632
12170
  failed += candidates.length;
@@ -11703,7 +12241,7 @@ async function backfillVectorEmbeddings(options = {}) {
11703
12241
  vector: embedding
11704
12242
  });
11705
12243
  }
11706
- vectorMissingIds.delete(id);
12244
+ clearVectorMissing(id);
11707
12245
  succeeded++;
11708
12246
  } catch (error) {
11709
12247
  recordFailure(vectorBackfillError(error));
@@ -11728,7 +12266,7 @@ async function backfillVectorEmbeddings(options = {}) {
11728
12266
  ...lastFailure ? { lastError: lastFailure } : {}
11729
12267
  };
11730
12268
  }
11731
- var observations, nextId, projectDir, searchIndexPrepared, embeddingWriteMode, embeddingWorkerProjectRoot, corpusLoaded, largeCorpusLazyMode, loadedObservationStore, DEFAULT_ORAMA_HYDRATION_THRESHOLD, vectorMissingIds, vectorBackfillRunning, vectorSchemaUpgradePromise, lastVectorBackfill, embeddingFailureLogTimestamps, EMBEDDING_FAILURE_LOG_COOLDOWN_MS, MAX_EMBEDDING_FAILURE_KEYS;
12269
+ var observations, nextId, projectDir, searchIndexPrepared, embeddingWriteMode, embeddingWorkerProjectRoot, corpusLoaded, largeCorpusLazyMode, loadedObservationStore, DEFAULT_ORAMA_HYDRATION_THRESHOLD, vectorMissingIds, vectorMissingProjectIds, vectorBackfillRunning, vectorSchemaUpgradePromise, lastVectorBackfill, embeddingFailureLogTimestamps, EMBEDDING_FAILURE_LOG_COOLDOWN_MS, MAX_EMBEDDING_FAILURE_KEYS;
11732
12270
  var init_observations = __esm({
11733
12271
  "src/memory/observations.ts"() {
11734
12272
  "use strict";
@@ -11753,6 +12291,7 @@ var init_observations = __esm({
11753
12291
  loadedObservationStore = null;
11754
12292
  DEFAULT_ORAMA_HYDRATION_THRESHOLD = 1e4;
11755
12293
  vectorMissingIds = /* @__PURE__ */ new Set();
12294
+ vectorMissingProjectIds = /* @__PURE__ */ new Map();
11756
12295
  vectorBackfillRunning = false;
11757
12296
  vectorSchemaUpgradePromise = null;
11758
12297
  lastVectorBackfill = null;
@@ -11813,7 +12352,7 @@ var init_maintenance_targets = __esm({
11813
12352
  });
11814
12353
 
11815
12354
  // src/knowledge/workspace-store.ts
11816
- import { randomUUID as randomUUID5 } from "crypto";
12355
+ import { randomUUID as randomUUID6 } from "crypto";
11817
12356
  function arrayValue(raw) {
11818
12357
  if (typeof raw !== "string" || !raw) return [];
11819
12358
  try {
@@ -11954,7 +12493,7 @@ var init_workspace_store = __esm({
11954
12493
  }
11955
12494
  createProposal(input) {
11956
12495
  const proposal = {
11957
- id: input.id ?? randomUUID5(),
12496
+ id: input.id ?? randomUUID6(),
11958
12497
  ...input,
11959
12498
  status: input.status ?? "pending",
11960
12499
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
@@ -12240,11 +12779,11 @@ __export(consolidation_exports, {
12240
12779
  });
12241
12780
  function tokenize(text2) {
12242
12781
  return new Set(
12243
- text2.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff\s-]/g, " ").split(/\s+/).filter((t2) => t2.length > 1)
12782
+ text2.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, " ").split(/\s+/).filter((t2) => t2.length > 1)
12244
12783
  );
12245
12784
  }
12246
12785
  function jaccardSimilarity(a, b) {
12247
- if (a.size === 0 && b.size === 0) return 1;
12786
+ if (a.size === 0 && b.size === 0) return 0;
12248
12787
  let intersection = 0;
12249
12788
  for (const token of a) {
12250
12789
  if (b.has(token)) intersection++;
@@ -12610,7 +13149,7 @@ Respond in JSON only:
12610
13149
  });
12611
13150
 
12612
13151
  // src/media/media-store.ts
12613
- import { randomUUID as randomUUID6 } from "crypto";
13152
+ import { randomUUID as randomUUID7 } from "crypto";
12614
13153
  function asOptionalText(value) {
12615
13154
  return typeof value === "string" && value.length > 0 ? value : void 0;
12616
13155
  }
@@ -12780,7 +13319,7 @@ var init_media_store = __esm({
12780
13319
  return { asset: this.getAsset(input.projectId, existing.id), deduplicated: true };
12781
13320
  }
12782
13321
  const asset = {
12783
- id: randomUUID6(),
13322
+ id: randomUUID7(),
12784
13323
  ...input,
12785
13324
  createdAt: now3,
12786
13325
  updatedAt: now3
@@ -12860,7 +13399,7 @@ var init_media_store = __esm({
12860
13399
  `).get(input.assetId, input.observationId ?? null, input.role);
12861
13400
  if (existing) return rowToLink(existing);
12862
13401
  const link = {
12863
- id: randomUUID6(),
13402
+ id: randomUUID7(),
12864
13403
  assetId: input.assetId,
12865
13404
  projectId: input.projectId,
12866
13405
  ...input.observationId !== void 0 ? { observationId: input.observationId } : {},
@@ -12899,7 +13438,7 @@ var init_media_store = __esm({
12899
13438
  return rowToDerivation(this.db.prepare("SELECT * FROM media_derivations WHERE id = ?").get(existing.id));
12900
13439
  }
12901
13440
  const derivation = {
12902
- id: randomUUID6(),
13441
+ id: randomUUID7(),
12903
13442
  ...input,
12904
13443
  content,
12905
13444
  ...error ? { error } : {},
@@ -12986,7 +13525,7 @@ var init_media_store = __esm({
12986
13525
  createJob(input) {
12987
13526
  const now3 = Date.now();
12988
13527
  const job = {
12989
- id: randomUUID6(),
13528
+ id: randomUUID7(),
12990
13529
  projectId: input.projectId,
12991
13530
  kind: input.kind,
12992
13531
  status: "queued",
@@ -13148,7 +13687,7 @@ var init_types2 = __esm({
13148
13687
  });
13149
13688
 
13150
13689
  // src/media/asset-store.ts
13151
- import { createHash as createHash8, randomUUID as randomUUID7 } from "crypto";
13690
+ import { createHash as createHash8, randomUUID as randomUUID8 } from "crypto";
13152
13691
  import { copyFile, lstat, mkdir as mkdir3, open, readFile as readFile3, readdir, rename as rename2, rm, stat as stat2, writeFile as writeFile3 } from "fs/promises";
13153
13692
  import path11 from "path";
13154
13693
  function mediaRoot(dataDir) {
@@ -13219,7 +13758,7 @@ async function destinationExists(destination) {
13219
13758
  async function persistBuffer(bytes, destination) {
13220
13759
  await mkdir3(path11.dirname(destination), { recursive: true });
13221
13760
  if (await destinationExists(destination)) return false;
13222
- const temporary = `${destination}.${randomUUID7()}.tmp`;
13761
+ const temporary = `${destination}.${randomUUID8()}.tmp`;
13223
13762
  try {
13224
13763
  await writeFile3(temporary, bytes, { flag: "wx" });
13225
13764
  await rename2(temporary, destination);
@@ -66121,7 +66660,7 @@ var require_gaxios = __commonJS({
66121
66660
  var retry_js_1 = require_retry3();
66122
66661
  var stream_1 = __require("stream");
66123
66662
  var interceptor_js_1 = require_interceptor();
66124
- var randomUUID16 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
66663
+ var randomUUID17 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
66125
66664
  var HTTP_STATUS_NO_CONTENT = 204;
66126
66665
  var Gaxios = class {
66127
66666
  agentCache = /* @__PURE__ */ new Map();
@@ -66394,7 +66933,7 @@ var require_gaxios = __commonJS({
66394
66933
  */
66395
66934
  ["Blob", "File", "FormData"].includes(opts.data?.constructor?.name || "");
66396
66935
  if (opts.multipart?.length) {
66397
- const boundary = await randomUUID16();
66936
+ const boundary = await randomUUID17();
66398
66937
  preparedHeaders.set("content-type", `multipart/related; boundary=${boundary}`);
66399
66938
  opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary));
66400
66939
  } else if (shouldDirectlyPassData) {
@@ -147149,14 +147688,23 @@ var init_audio_jobs = __esm({
147149
147688
  }
147150
147689
  });
147151
147690
 
147152
- // src/memory/feedback-model.ts
147691
+ // src/core/retrieval-policy.ts
147153
147692
  function feedbackWeightMultiplier(weight) {
147154
147693
  return Math.max(0.35, Math.min(1.4, 0.35 + Math.max(0, Math.min(2, weight)) * 0.525));
147155
147694
  }
147695
+ var init_retrieval_policy = __esm({
147696
+ "src/core/retrieval-policy.ts"() {
147697
+ "use strict";
147698
+ init_esm_shims();
147699
+ }
147700
+ });
147701
+
147702
+ // src/memory/feedback-model.ts
147156
147703
  var init_feedback_model = __esm({
147157
147704
  "src/memory/feedback-model.ts"() {
147158
147705
  "use strict";
147159
147706
  init_esm_shims();
147707
+ init_retrieval_policy();
147160
147708
  }
147161
147709
  });
147162
147710
 
@@ -147168,7 +147716,7 @@ __export(feedback_exports, {
147168
147716
  applyMemoryFeedback: () => applyMemoryFeedback,
147169
147717
  feedbackWeightMultiplier: () => feedbackWeightMultiplier
147170
147718
  });
147171
- import { randomUUID as randomUUID8 } from "crypto";
147719
+ import { randomUUID as randomUUID9 } from "crypto";
147172
147720
  function applyMemoryFeedback(current, event) {
147173
147721
  const delta = event.signal === "revoke" ? 0 : FEEDBACK_DELTAS[event.signal];
147174
147722
  const weight = Math.max(0, Math.min(2, current.weight + delta));
@@ -147286,7 +147834,7 @@ var init_feedback = __esm({
147286
147834
  if (!target) throw new Error("The feedback event to revoke was not found in the same candidate scope.");
147287
147835
  }
147288
147836
  const event = {
147289
- id: randomUUID8(),
147837
+ id: randomUUID9(),
147290
147838
  projectId: input.projectId,
147291
147839
  candidateKind: input.candidateKind,
147292
147840
  candidateId: input.candidateId,
@@ -147674,7 +148222,7 @@ var init_retention = __esm({
147674
148222
  });
147675
148223
 
147676
148224
  // src/memory/owner.ts
147677
- import { randomUUID as randomUUID9 } from "crypto";
148225
+ import { randomUUID as randomUUID10 } from "crypto";
147678
148226
  import { promises as fs9 } from "fs";
147679
148227
  import path17 from "path";
147680
148228
  function ownerPath(dataDir) {
@@ -147704,7 +148252,7 @@ async function resolveLocalMemoryOwner(dataDir, options = {}) {
147704
148252
  await fs9.mkdir(path17.dirname(filePath), { recursive: true });
147705
148253
  const created = {
147706
148254
  version: 1,
147707
- id: "local-" + randomUUID9(),
148255
+ id: "local-" + randomUUID10(),
147708
148256
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
147709
148257
  };
147710
148258
  try {
@@ -147727,7 +148275,7 @@ var init_owner = __esm({
147727
148275
  });
147728
148276
 
147729
148277
  // src/memory/long-term-store.ts
147730
- import { randomUUID as randomUUID10 } from "crypto";
148278
+ import { randomUUID as randomUUID11 } from "crypto";
147731
148279
  function optionalText2(value) {
147732
148280
  return typeof value === "string" && value.trim() ? value : void 0;
147733
148281
  }
@@ -147887,7 +148435,7 @@ var init_long_term_store = __esm({
147887
148435
  }
147888
148436
  insertEvidence(input) {
147889
148437
  const evidence = {
147890
- id: randomUUID10(),
148438
+ id: randomUUID11(),
147891
148439
  ...input,
147892
148440
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
147893
148441
  };
@@ -147914,7 +148462,7 @@ var init_long_term_store = __esm({
147914
148462
  }
147915
148463
  recordEvent(input) {
147916
148464
  const event = {
147917
- id: randomUUID10(),
148465
+ id: randomUUID11(),
147918
148466
  ...input,
147919
148467
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
147920
148468
  };
@@ -148004,7 +148552,7 @@ __export(long_term_exports, {
148004
148552
  selectLongTermMemoriesForTask: () => selectLongTermMemoriesForTask,
148005
148553
  supersedeLongTermMemory: () => supersedeLongTermMemory
148006
148554
  });
148007
- import { randomUUID as randomUUID11 } from "crypto";
148555
+ import { randomUUID as randomUUID12 } from "crypto";
148008
148556
  function isOneOf(value, values) {
148009
148557
  return typeof value === "string" && values.includes(value);
148010
148558
  }
@@ -148186,7 +148734,7 @@ async function createManualLongTermMemory(input) {
148186
148734
  const owner = await resolveLocalMemoryOwner(input.dataDir, { create: true });
148187
148735
  if (!owner) throw new Error("Memorix could not resolve a local memory owner.");
148188
148736
  assertScope(input.scope);
148189
- const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID11(), relation: "supports" }];
148737
+ const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID12(), relation: "supports" }];
148190
148738
  return createLongTermMemoryWithDataDir({
148191
148739
  dataDir: input.dataDir,
148192
148740
  originProjectId: input.projectId,
@@ -148241,7 +148789,7 @@ async function createLongTermMemoryWithDataDir(input) {
148241
148789
  assertPortableEvidence(input.scope, portability, evidenceInputs);
148242
148790
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
148243
148791
  const memory = {
148244
- id: randomUUID11(),
148792
+ id: randomUUID12(),
148245
148793
  originProjectId: compactText(input.originProjectId, "origin project id", 1e3),
148246
148794
  ownerId: compactText(input.ownerId, "owner id", 160),
148247
148795
  scope: input.scope,
@@ -149513,7 +150061,7 @@ var claim_store_exports = {};
149513
150061
  __export(claim_store_exports, {
149514
150062
  ClaimStore: () => ClaimStore
149515
150063
  });
149516
- import { createHash as createHash12, randomUUID as randomUUID12 } from "crypto";
150064
+ import { createHash as createHash12, randomUUID as randomUUID13 } from "crypto";
149517
150065
  function optionalText3(value) {
149518
150066
  return typeof value === "string" && value ? value : void 0;
149519
150067
  }
@@ -149697,7 +150245,7 @@ var init_claim_store = __esm({
149697
150245
  locator, capturedHash, evidenceKey, createdAt
149698
150246
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
149699
150247
  `).run(
149700
- randomUUID12(),
150248
+ randomUUID13(),
149701
150249
  input.claimId,
149702
150250
  input.evidenceKind,
149703
150251
  input.evidenceId,
@@ -149719,7 +150267,7 @@ var init_claim_store = __esm({
149719
150267
  }
149720
150268
  recordEvent(input) {
149721
150269
  const event = {
149722
- id: randomUUID12(),
150270
+ id: randomUUID13(),
149723
150271
  ...input,
149724
150272
  ...input.detail ? { detail: sanitizeCredentials(input.detail) } : {},
149725
150273
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
@@ -149764,7 +150312,7 @@ __export(claims_exports, {
149764
150312
  supersedeClaim: () => supersedeClaim,
149765
150313
  writeClaim: () => writeClaim
149766
150314
  });
149767
- import { createHash as createHash13, randomUUID as randomUUID13 } from "crypto";
150315
+ import { createHash as createHash13, randomUUID as randomUUID14 } from "crypto";
149768
150316
  function compactText2(value, field) {
149769
150317
  if (typeof value !== "string") throw new Error("Claim " + field + " must be text");
149770
150318
  const sanitized = sanitizeCredentials(value).trim().replace(/\s+/g, " ");
@@ -149850,7 +150398,7 @@ function normalizeClaimInput(input) {
149850
150398
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
149851
150399
  return {
149852
150400
  claim: {
149853
- id: randomUUID13(),
150401
+ id: randomUUID14(),
149854
150402
  projectId,
149855
150403
  subject,
149856
150404
  predicate,
@@ -150935,7 +151483,7 @@ var init_workflow_sync = __esm({
150935
151483
  });
150936
151484
 
150937
151485
  // src/knowledge/workflow-store.ts
150938
- import { randomUUID as randomUUID14 } from "crypto";
151486
+ import { randomUUID as randomUUID15 } from "crypto";
150939
151487
  function parseJson(value, fallback) {
150940
151488
  if (typeof value !== "string" || !value) return fallback;
150941
151489
  try {
@@ -151035,7 +151583,7 @@ var init_workflow_store = __esm({
151035
151583
  }
151036
151584
  recordRun(input) {
151037
151585
  const run = {
151038
- id: randomUUID14(),
151586
+ id: randomUUID15(),
151039
151587
  workflowId: input.workflowId,
151040
151588
  projectId: input.projectId,
151041
151589
  task: input.task.trim(),
@@ -151103,7 +151651,7 @@ var init_outcome_types = __esm({
151103
151651
  });
151104
151652
 
151105
151653
  // src/knowledge/outcome-store.ts
151106
- import { randomUUID as randomUUID15 } from "crypto";
151654
+ import { randomUUID as randomUUID16 } from "crypto";
151107
151655
  function optionalText5(value) {
151108
151656
  return typeof value === "string" && value.trim() ? value : void 0;
151109
151657
  }
@@ -151147,7 +151695,7 @@ var init_outcome_store = __esm({
151147
151695
  }
151148
151696
  record(input) {
151149
151697
  const signal = {
151150
- id: randomUUID15(),
151698
+ id: randomUUID16(),
151151
151699
  projectId: text(input.projectId, "project id"),
151152
151700
  candidateKind: oneOf(input.candidateKind, MEMORY_OUTCOME_CANDIDATE_KINDS, "candidate kind"),
151153
151701
  candidateId: text(input.candidateId, "candidate id"),
@@ -151981,6 +152529,15 @@ function observationId(payload) {
151981
152529
  const value = payload.observationId;
151982
152530
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
151983
152531
  }
152532
+ async function automaticCleanupEnabled(projectRoot) {
152533
+ if (!projectRoot) return true;
152534
+ try {
152535
+ const { getResolvedConfig: getResolvedConfig2 } = await Promise.resolve().then(() => (init_resolved_config(), resolved_config_exports));
152536
+ return getResolvedConfig2({ projectRoot }).memory.autoCleanup !== false;
152537
+ } catch {
152538
+ return true;
152539
+ }
152540
+ }
151984
152541
  function workspaceMode(payload) {
151985
152542
  return payload.workspaceMode === "local" || payload.workspaceMode === "versioned" ? payload.workspaceMode : void 0;
151986
152543
  }
@@ -152069,6 +152626,9 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
152069
152626
  if (job.projectId !== projectId) {
152070
152627
  return { action: "reschedule", delayMs: VECTOR_RETRY_DELAY_MS };
152071
152628
  }
152629
+ if ((job.kind === "retention-archive" || job.kind === "consolidation" || job.kind === "long-term-maintenance") && !await automaticCleanupEnabled(projectRoot)) {
152630
+ return { action: "complete" };
152631
+ }
152072
152632
  if (job.kind === "media-video-generation") {
152073
152633
  const { runMiniMaxVideoGenerationJob: runMiniMaxVideoGenerationJob2 } = await Promise.resolve().then(() => (init_video_jobs(), video_jobs_exports));
152074
152634
  return runMiniMaxVideoGenerationJob2(job, { dataDir: projectDir2, projectId });
@@ -152161,6 +152721,33 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
152161
152721
  });
152162
152722
  return { action: "complete" };
152163
152723
  }
152724
+ if (job.kind === "observation-project") {
152725
+ if (!projectRoot) {
152726
+ throw new Error(`Observation projection requires a project root for ${projectId}`);
152727
+ }
152728
+ const id = observationId(job.payload);
152729
+ if (!id) return { action: "complete" };
152730
+ const [
152731
+ { CodeGraphStore: CodeGraphStore2 },
152732
+ { bindObservationToCode: bindObservationToCode2 },
152733
+ { EvidenceCardStore: EvidenceCardStore2 },
152734
+ { getObservationStore: getObservationStore2 }
152735
+ ] = await Promise.all([
152736
+ Promise.resolve().then(() => (init_store(), store_exports)),
152737
+ Promise.resolve().then(() => (init_binder(), binder_exports)),
152738
+ Promise.resolve().then(() => (init_evidence_store(), evidence_store_exports)),
152739
+ Promise.resolve().then(() => (init_obs_store(), obs_store_exports))
152740
+ ]);
152741
+ const observation = await getObservationStore2().getById(id);
152742
+ if (!observation || observation.projectId !== projectId) return { action: "complete" };
152743
+ const codeStore = new CodeGraphStore2();
152744
+ await codeStore.init(projectDir2);
152745
+ await bindObservationToCode2(codeStore, observation);
152746
+ const evidence = new EvidenceCardStore2();
152747
+ await evidence.init(projectDir2);
152748
+ evidence.upsertObservation(observation);
152749
+ return { action: "complete" };
152750
+ }
152164
152751
  if (job.kind === "observation-qualify") {
152165
152752
  const [
152166
152753
  { CodeGraphStore: CodeGraphStore2 },
@@ -152368,7 +152955,15 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
152368
152955
  const after = getVectorStatus2(projectId);
152369
152956
  if (after.missing === 0) {
152370
152957
  resolveSupersededVectorFailures(projectDir2, projectId);
152371
- return { action: "complete" };
152958
+ return {
152959
+ action: "complete",
152960
+ progress: {
152961
+ attempted: result.attempted,
152962
+ succeeded: result.succeeded,
152963
+ failed: result.failed,
152964
+ remaining: 0
152965
+ }
152966
+ };
152372
152967
  }
152373
152968
  if (result.failed > 0 && result.succeeded === 0) {
152374
152969
  const streak = vectorBackfillFailureStreak(job.payload) + 1;
@@ -152383,6 +152978,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
152383
152978
  ...job.payload,
152384
152979
  vectorBackfillFailureStreak: streak
152385
152980
  },
152981
+ progress: {
152982
+ attempted: result.attempted,
152983
+ succeeded: result.succeeded,
152984
+ failed: result.failed,
152985
+ remaining: after.missing
152986
+ },
152386
152987
  lastError: result.lastError ?? `vector backfill made no progress (${result.failed}/${result.attempted} failed)`
152387
152988
  };
152388
152989
  }
@@ -152392,6 +152993,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
152392
152993
  action: "reschedule",
152393
152994
  delayMs: result.attempted === 0 ? VECTOR_RETRY_DELAY_MS : 0,
152394
152995
  resetAttempts: result.succeeded > 0,
152996
+ progress: {
152997
+ attempted: result.attempted,
152998
+ succeeded: result.succeeded,
152999
+ failed: result.failed,
153000
+ remaining: after.missing
153001
+ },
152395
153002
  ...result.succeeded > 0 ? {
152396
153003
  ...priorFailureStreak > 0 ? { payload } : {},
152397
153004
  ...result.failed > 0 && result.lastError ? { lastError: result.lastError } : priorFailureStreak > 0 ? { clearLastError: true } : {}