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,
@@ -9474,7 +9861,7 @@ var init_maintenance_targets = __esm({
9474
9861
  });
9475
9862
 
9476
9863
  // src/knowledge/workspace-store.ts
9477
- import { randomUUID as randomUUID4 } from "crypto";
9864
+ import { randomUUID as randomUUID5 } from "crypto";
9478
9865
  function arrayValue(raw) {
9479
9866
  if (typeof raw !== "string" || !raw) return [];
9480
9867
  try {
@@ -9615,7 +10002,7 @@ var init_workspace_store = __esm({
9615
10002
  }
9616
10003
  createProposal(input) {
9617
10004
  const proposal = {
9618
- id: input.id ?? randomUUID4(),
10005
+ id: input.id ?? randomUUID5(),
9619
10006
  ...input,
9620
10007
  status: input.status ?? "pending",
9621
10008
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
@@ -9901,11 +10288,11 @@ __export(consolidation_exports, {
9901
10288
  });
9902
10289
  function tokenize(text2) {
9903
10290
  return new Set(
9904
- text2.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff\s-]/g, " ").split(/\s+/).filter((t2) => t2.length > 1)
10291
+ text2.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, " ").split(/\s+/).filter((t2) => t2.length > 1)
9905
10292
  );
9906
10293
  }
9907
10294
  function jaccardSimilarity(a, b) {
9908
- if (a.size === 0 && b.size === 0) return 1;
10295
+ if (a.size === 0 && b.size === 0) return 0;
9909
10296
  let intersection = 0;
9910
10297
  for (const token of a) {
9911
10298
  if (b.has(token)) intersection++;
@@ -10271,7 +10658,7 @@ Respond in JSON only:
10271
10658
  });
10272
10659
 
10273
10660
  // src/media/media-store.ts
10274
- import { randomUUID as randomUUID5 } from "crypto";
10661
+ import { randomUUID as randomUUID6 } from "crypto";
10275
10662
  function asOptionalText(value) {
10276
10663
  return typeof value === "string" && value.length > 0 ? value : void 0;
10277
10664
  }
@@ -10441,7 +10828,7 @@ var init_media_store = __esm({
10441
10828
  return { asset: this.getAsset(input.projectId, existing.id), deduplicated: true };
10442
10829
  }
10443
10830
  const asset = {
10444
- id: randomUUID5(),
10831
+ id: randomUUID6(),
10445
10832
  ...input,
10446
10833
  createdAt: now3,
10447
10834
  updatedAt: now3
@@ -10521,7 +10908,7 @@ var init_media_store = __esm({
10521
10908
  `).get(input.assetId, input.observationId ?? null, input.role);
10522
10909
  if (existing) return rowToLink(existing);
10523
10910
  const link = {
10524
- id: randomUUID5(),
10911
+ id: randomUUID6(),
10525
10912
  assetId: input.assetId,
10526
10913
  projectId: input.projectId,
10527
10914
  ...input.observationId !== void 0 ? { observationId: input.observationId } : {},
@@ -10560,7 +10947,7 @@ var init_media_store = __esm({
10560
10947
  return rowToDerivation(this.db.prepare("SELECT * FROM media_derivations WHERE id = ?").get(existing.id));
10561
10948
  }
10562
10949
  const derivation = {
10563
- id: randomUUID5(),
10950
+ id: randomUUID6(),
10564
10951
  ...input,
10565
10952
  content,
10566
10953
  ...error ? { error } : {},
@@ -10647,7 +11034,7 @@ var init_media_store = __esm({
10647
11034
  createJob(input) {
10648
11035
  const now3 = Date.now();
10649
11036
  const job = {
10650
- id: randomUUID5(),
11037
+ id: randomUUID6(),
10651
11038
  projectId: input.projectId,
10652
11039
  kind: input.kind,
10653
11040
  status: "queued",
@@ -10809,7 +11196,7 @@ var init_types2 = __esm({
10809
11196
  });
10810
11197
 
10811
11198
  // src/media/asset-store.ts
10812
- import { createHash as createHash7, randomUUID as randomUUID6 } from "crypto";
11199
+ import { createHash as createHash7, randomUUID as randomUUID7 } from "crypto";
10813
11200
  import { copyFile, lstat, mkdir as mkdir3, open, readFile as readFile3, readdir, rename as rename2, rm, stat as stat2, writeFile as writeFile3 } from "fs/promises";
10814
11201
  import path11 from "path";
10815
11202
  function mediaRoot(dataDir) {
@@ -10880,7 +11267,7 @@ async function destinationExists(destination) {
10880
11267
  async function persistBuffer(bytes, destination) {
10881
11268
  await mkdir3(path11.dirname(destination), { recursive: true });
10882
11269
  if (await destinationExists(destination)) return false;
10883
- const temporary = `${destination}.${randomUUID6()}.tmp`;
11270
+ const temporary = `${destination}.${randomUUID7()}.tmp`;
10884
11271
  try {
10885
11272
  await writeFile3(temporary, bytes, { flag: "wx" });
10886
11273
  await rename2(temporary, destination);
@@ -63782,7 +64169,7 @@ var require_gaxios = __commonJS({
63782
64169
  var retry_js_1 = require_retry3();
63783
64170
  var stream_1 = __require("stream");
63784
64171
  var interceptor_js_1 = require_interceptor();
63785
- var randomUUID16 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
64172
+ var randomUUID17 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
63786
64173
  var HTTP_STATUS_NO_CONTENT = 204;
63787
64174
  var Gaxios = class {
63788
64175
  agentCache = /* @__PURE__ */ new Map();
@@ -64055,7 +64442,7 @@ var require_gaxios = __commonJS({
64055
64442
  */
64056
64443
  ["Blob", "File", "FormData"].includes(opts.data?.constructor?.name || "");
64057
64444
  if (opts.multipart?.length) {
64058
- const boundary = await randomUUID16();
64445
+ const boundary = await randomUUID17();
64059
64446
  preparedHeaders.set("content-type", `multipart/related; boundary=${boundary}`);
64060
64447
  opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary));
64061
64448
  } else if (shouldDirectlyPassData) {
@@ -144810,14 +145197,23 @@ var init_audio_jobs = __esm({
144810
145197
  }
144811
145198
  });
144812
145199
 
144813
- // src/memory/feedback-model.ts
145200
+ // src/core/retrieval-policy.ts
144814
145201
  function feedbackWeightMultiplier(weight) {
144815
145202
  return Math.max(0.35, Math.min(1.4, 0.35 + Math.max(0, Math.min(2, weight)) * 0.525));
144816
145203
  }
145204
+ var init_retrieval_policy = __esm({
145205
+ "src/core/retrieval-policy.ts"() {
145206
+ "use strict";
145207
+ init_esm_shims();
145208
+ }
145209
+ });
145210
+
145211
+ // src/memory/feedback-model.ts
144817
145212
  var init_feedback_model = __esm({
144818
145213
  "src/memory/feedback-model.ts"() {
144819
145214
  "use strict";
144820
145215
  init_esm_shims();
145216
+ init_retrieval_policy();
144821
145217
  }
144822
145218
  });
144823
145219
 
@@ -144829,7 +145225,7 @@ __export(feedback_exports, {
144829
145225
  applyMemoryFeedback: () => applyMemoryFeedback,
144830
145226
  feedbackWeightMultiplier: () => feedbackWeightMultiplier
144831
145227
  });
144832
- import { randomUUID as randomUUID7 } from "crypto";
145228
+ import { randomUUID as randomUUID8 } from "crypto";
144833
145229
  function applyMemoryFeedback(current, event) {
144834
145230
  const delta = event.signal === "revoke" ? 0 : FEEDBACK_DELTAS[event.signal];
144835
145231
  const weight = Math.max(0, Math.min(2, current.weight + delta));
@@ -144947,7 +145343,7 @@ var init_feedback = __esm({
144947
145343
  if (!target) throw new Error("The feedback event to revoke was not found in the same candidate scope.");
144948
145344
  }
144949
145345
  const event = {
144950
- id: randomUUID7(),
145346
+ id: randomUUID8(),
144951
145347
  projectId: input.projectId,
144952
145348
  candidateKind: input.candidateKind,
144953
145349
  candidateId: input.candidateId,
@@ -145335,7 +145731,7 @@ var init_retention = __esm({
145335
145731
  });
145336
145732
 
145337
145733
  // src/memory/owner.ts
145338
- import { randomUUID as randomUUID8 } from "crypto";
145734
+ import { randomUUID as randomUUID9 } from "crypto";
145339
145735
  import { promises as fs9 } from "fs";
145340
145736
  import path17 from "path";
145341
145737
  function ownerPath(dataDir) {
@@ -145365,7 +145761,7 @@ async function resolveLocalMemoryOwner(dataDir, options = {}) {
145365
145761
  await fs9.mkdir(path17.dirname(filePath), { recursive: true });
145366
145762
  const created = {
145367
145763
  version: 1,
145368
- id: "local-" + randomUUID8(),
145764
+ id: "local-" + randomUUID9(),
145369
145765
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
145370
145766
  };
145371
145767
  try {
@@ -145388,7 +145784,7 @@ var init_owner = __esm({
145388
145784
  });
145389
145785
 
145390
145786
  // src/memory/long-term-store.ts
145391
- import { randomUUID as randomUUID9 } from "crypto";
145787
+ import { randomUUID as randomUUID10 } from "crypto";
145392
145788
  function optionalText2(value) {
145393
145789
  return typeof value === "string" && value.trim() ? value : void 0;
145394
145790
  }
@@ -145548,7 +145944,7 @@ var init_long_term_store = __esm({
145548
145944
  }
145549
145945
  insertEvidence(input) {
145550
145946
  const evidence = {
145551
- id: randomUUID9(),
145947
+ id: randomUUID10(),
145552
145948
  ...input,
145553
145949
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
145554
145950
  };
@@ -145575,7 +145971,7 @@ var init_long_term_store = __esm({
145575
145971
  }
145576
145972
  recordEvent(input) {
145577
145973
  const event = {
145578
- id: randomUUID9(),
145974
+ id: randomUUID10(),
145579
145975
  ...input,
145580
145976
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
145581
145977
  };
@@ -145665,7 +146061,7 @@ __export(long_term_exports, {
145665
146061
  selectLongTermMemoriesForTask: () => selectLongTermMemoriesForTask,
145666
146062
  supersedeLongTermMemory: () => supersedeLongTermMemory
145667
146063
  });
145668
- import { randomUUID as randomUUID10 } from "crypto";
146064
+ import { randomUUID as randomUUID11 } from "crypto";
145669
146065
  function isOneOf(value, values) {
145670
146066
  return typeof value === "string" && values.includes(value);
145671
146067
  }
@@ -145847,7 +146243,7 @@ async function createManualLongTermMemory(input) {
145847
146243
  const owner = await resolveLocalMemoryOwner(input.dataDir, { create: true });
145848
146244
  if (!owner) throw new Error("Memorix could not resolve a local memory owner.");
145849
146245
  assertScope(input.scope);
145850
- const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID10(), relation: "supports" }];
146246
+ const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID11(), relation: "supports" }];
145851
146247
  return createLongTermMemoryWithDataDir({
145852
146248
  dataDir: input.dataDir,
145853
146249
  originProjectId: input.projectId,
@@ -145902,7 +146298,7 @@ async function createLongTermMemoryWithDataDir(input) {
145902
146298
  assertPortableEvidence(input.scope, portability, evidenceInputs);
145903
146299
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
145904
146300
  const memory = {
145905
- id: randomUUID10(),
146301
+ id: randomUUID11(),
145906
146302
  originProjectId: compactText(input.originProjectId, "origin project id", 1e3),
145907
146303
  ownerId: compactText(input.ownerId, "owner id", 160),
145908
146304
  scope: input.scope,
@@ -146257,7 +146653,7 @@ var store_exports = {};
146257
146653
  __export(store_exports, {
146258
146654
  CodeGraphStore: () => CodeGraphStore
146259
146655
  });
146260
- import { randomUUID as randomUUID11 } from "crypto";
146656
+ import { randomUUID as randomUUID12 } from "crypto";
146261
146657
  import { posix as pathPosix } from "path";
146262
146658
  function rowToFile(row) {
146263
146659
  return {
@@ -147186,8 +147582,9 @@ var init_store = __esm({
147186
147582
  * so an interrupted scan cannot be advertised as complete.
147187
147583
  */
147188
147584
  recordCodeStateSnapshot(input) {
147189
- const id = randomUUID11();
147585
+ const id = randomUUID12();
147190
147586
  let snapshot;
147587
+ let compactNeeded = false;
147191
147588
  const tx = this.db.transaction(() => {
147192
147589
  const previous = this.db.prepare(
147193
147590
  "SELECT id, sourceEpoch FROM code_state_snapshots WHERE projectId = ? ORDER BY sourceEpoch DESC LIMIT 1"
@@ -147231,6 +147628,26 @@ var init_store = __esm({
147231
147628
  for (const file of snapshotFileRows) {
147232
147629
  insertSnapshotFile.run(id, file.projectId, file.id, file.path, file.contentHash);
147233
147630
  }
147631
+ const staleSymbolIds = this.db.prepare(
147632
+ "SELECT id FROM code_symbols WHERE projectId = ? AND stale = 1"
147633
+ ).all(input.projectId).map((row) => row.id);
147634
+ if (staleSymbolIds.length > 0) {
147635
+ const placeholders = staleSymbolIds.map(() => "?").join(", ");
147636
+ this.db.prepare(
147637
+ `DELETE FROM code_edges WHERE projectId = ? AND (fromSymbolId IN (${placeholders}) OR toSymbolId IN (${placeholders}))`
147638
+ ).run(input.projectId, ...staleSymbolIds, ...staleSymbolIds);
147639
+ this.db.prepare("DELETE FROM code_symbols WHERE projectId = ? AND stale = 1").run(input.projectId);
147640
+ compactNeeded = true;
147641
+ }
147642
+ const oldSnapshots = this.db.prepare(
147643
+ "SELECT id FROM code_state_snapshots WHERE projectId = ? ORDER BY sourceEpoch DESC LIMIT -1 OFFSET 2"
147644
+ ).all(input.projectId).map((row) => row.id);
147645
+ if (oldSnapshots.length > 0) {
147646
+ const placeholders = oldSnapshots.map(() => "?").join(", ");
147647
+ this.db.prepare(`DELETE FROM code_state_snapshot_files WHERE snapshotId IN (${placeholders})`).run(...oldSnapshots);
147648
+ this.db.prepare(`DELETE FROM code_state_snapshots WHERE id IN (${placeholders})`).run(...oldSnapshots);
147649
+ compactNeeded = true;
147650
+ }
147234
147651
  snapshot = {
147235
147652
  ...input,
147236
147653
  id,
@@ -147239,11 +147656,24 @@ var init_store = __esm({
147239
147656
  };
147240
147657
  });
147241
147658
  tx();
147659
+ if (compactNeeded) this.compactStorage();
147242
147660
  return snapshot;
147243
147661
  }
147662
+ /** Reclaim WAL/free pages after a derived codegraph sweep. */
147663
+ compactStorage() {
147664
+ try {
147665
+ this.db.pragma("wal_checkpoint(TRUNCATE)");
147666
+ } catch {
147667
+ }
147668
+ try {
147669
+ this.db.exec("VACUUM");
147670
+ } catch {
147671
+ }
147672
+ }
147244
147673
  status(projectId) {
147245
147674
  const files = this.db.prepare(`SELECT COUNT(*) AS count FROM code_files WHERE projectId = ?`).get(projectId).count;
147246
147675
  const symbols = this.db.prepare(`SELECT COUNT(*) AS count FROM code_symbols WHERE projectId = ? AND stale = 0`).get(projectId).count;
147676
+ const staleSymbols = this.db.prepare(`SELECT COUNT(*) AS count FROM code_symbols WHERE projectId = ? AND stale = 1`).get(projectId).count;
147247
147677
  const edges = this.db.prepare(`SELECT COUNT(*) AS count FROM code_edges WHERE projectId = ?`).get(projectId).count;
147248
147678
  const refs = this.db.prepare(`SELECT COUNT(*) AS count FROM observation_code_refs WHERE projectId = ?`).get(projectId).count;
147249
147679
  const semanticSymbols = this.db.prepare(`SELECT COUNT(*) AS count FROM code_symbols WHERE projectId = ? AND stale = 0 AND source = 'typescript-compiler'`).get(projectId).count;
@@ -147251,6 +147681,8 @@ var init_store = __esm({
147251
147681
  const parserErrors = this.db.prepare(`SELECT COUNT(*) AS count FROM code_files WHERE projectId = ? AND parserError IS NOT NULL`).get(projectId).count;
147252
147682
  const latest = this.db.prepare(`SELECT MAX(indexedAt) AS indexedAt FROM code_files WHERE projectId = ?`).get(projectId);
147253
147683
  const latestSnapshot = this.latestSnapshot(projectId);
147684
+ const snapshots = this.db.prepare(`SELECT COUNT(*) AS count FROM code_state_snapshots WHERE projectId = ?`).get(projectId).count;
147685
+ const snapshotFiles = this.db.prepare(`SELECT COUNT(*) AS count FROM code_state_snapshot_files WHERE projectId = ?`).get(projectId).count;
147254
147686
  return {
147255
147687
  provider: "lite",
147256
147688
  files,
@@ -147260,6 +147692,9 @@ var init_store = __esm({
147260
147692
  semanticSymbols,
147261
147693
  semanticEdges,
147262
147694
  parserErrors,
147695
+ staleSymbols,
147696
+ snapshots,
147697
+ snapshotFiles,
147263
147698
  ...latest?.indexedAt ? { indexedAt: latest.indexedAt } : {},
147264
147699
  ...latestSnapshot ? { latestSnapshot } : {}
147265
147700
  };
@@ -148380,7 +148815,7 @@ var claim_store_exports = {};
148380
148815
  __export(claim_store_exports, {
148381
148816
  ClaimStore: () => ClaimStore
148382
148817
  });
148383
- import { createHash as createHash12, randomUUID as randomUUID12 } from "crypto";
148818
+ import { createHash as createHash12, randomUUID as randomUUID13 } from "crypto";
148384
148819
  function optionalText3(value) {
148385
148820
  return typeof value === "string" && value ? value : void 0;
148386
148821
  }
@@ -148564,7 +148999,7 @@ var init_claim_store = __esm({
148564
148999
  locator, capturedHash, evidenceKey, createdAt
148565
149000
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
148566
149001
  `).run(
148567
- randomUUID12(),
149002
+ randomUUID13(),
148568
149003
  input.claimId,
148569
149004
  input.evidenceKind,
148570
149005
  input.evidenceId,
@@ -148586,7 +149021,7 @@ var init_claim_store = __esm({
148586
149021
  }
148587
149022
  recordEvent(input) {
148588
149023
  const event = {
148589
- id: randomUUID12(),
149024
+ id: randomUUID13(),
148590
149025
  ...input,
148591
149026
  ...input.detail ? { detail: sanitizeCredentials(input.detail) } : {},
148592
149027
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
@@ -148631,7 +149066,7 @@ __export(claims_exports, {
148631
149066
  supersedeClaim: () => supersedeClaim,
148632
149067
  writeClaim: () => writeClaim
148633
149068
  });
148634
- import { createHash as createHash13, randomUUID as randomUUID13 } from "crypto";
149069
+ import { createHash as createHash13, randomUUID as randomUUID14 } from "crypto";
148635
149070
  function compactText2(value, field) {
148636
149071
  if (typeof value !== "string") throw new Error("Claim " + field + " must be text");
148637
149072
  const sanitized = sanitizeCredentials(value).trim().replace(/\s+/g, " ");
@@ -148717,7 +149152,7 @@ function normalizeClaimInput(input) {
148717
149152
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
148718
149153
  return {
148719
149154
  claim: {
148720
- id: randomUUID13(),
149155
+ id: randomUUID14(),
148721
149156
  projectId,
148722
149157
  subject,
148723
149158
  predicate,
@@ -149802,7 +150237,7 @@ var init_workflow_sync = __esm({
149802
150237
  });
149803
150238
 
149804
150239
  // src/knowledge/workflow-store.ts
149805
- import { randomUUID as randomUUID14 } from "crypto";
150240
+ import { randomUUID as randomUUID15 } from "crypto";
149806
150241
  function parseJson(value, fallback) {
149807
150242
  if (typeof value !== "string" || !value) return fallback;
149808
150243
  try {
@@ -149902,7 +150337,7 @@ var init_workflow_store = __esm({
149902
150337
  }
149903
150338
  recordRun(input) {
149904
150339
  const run = {
149905
- id: randomUUID14(),
150340
+ id: randomUUID15(),
149906
150341
  workflowId: input.workflowId,
149907
150342
  projectId: input.projectId,
149908
150343
  task: input.task.trim(),
@@ -149970,7 +150405,7 @@ var init_outcome_types = __esm({
149970
150405
  });
149971
150406
 
149972
150407
  // src/knowledge/outcome-store.ts
149973
- import { randomUUID as randomUUID15 } from "crypto";
150408
+ import { randomUUID as randomUUID16 } from "crypto";
149974
150409
  function optionalText5(value) {
149975
150410
  return typeof value === "string" && value.trim() ? value : void 0;
149976
150411
  }
@@ -150014,7 +150449,7 @@ var init_outcome_store = __esm({
150014
150449
  }
150015
150450
  record(input) {
150016
150451
  const signal = {
150017
- id: randomUUID15(),
150452
+ id: randomUUID16(),
150018
150453
  projectId: text(input.projectId, "project id"),
150019
150454
  candidateKind: oneOf(input.candidateKind, MEMORY_OUTCOME_CANDIDATE_KINDS, "candidate kind"),
150020
150455
  candidateId: text(input.candidateId, "candidate id"),
@@ -150848,6 +151283,15 @@ function observationId(payload) {
150848
151283
  const value = payload.observationId;
150849
151284
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
150850
151285
  }
151286
+ async function automaticCleanupEnabled(projectRoot) {
151287
+ if (!projectRoot) return true;
151288
+ try {
151289
+ const { getResolvedConfig: getResolvedConfig2 } = await Promise.resolve().then(() => (init_resolved_config(), resolved_config_exports));
151290
+ return getResolvedConfig2({ projectRoot }).memory.autoCleanup !== false;
151291
+ } catch {
151292
+ return true;
151293
+ }
151294
+ }
150851
151295
  function workspaceMode(payload) {
150852
151296
  return payload.workspaceMode === "local" || payload.workspaceMode === "versioned" ? payload.workspaceMode : void 0;
150853
151297
  }
@@ -150936,6 +151380,9 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
150936
151380
  if (job.projectId !== projectId) {
150937
151381
  return { action: "reschedule", delayMs: VECTOR_RETRY_DELAY_MS };
150938
151382
  }
151383
+ if ((job.kind === "retention-archive" || job.kind === "consolidation" || job.kind === "long-term-maintenance") && !await automaticCleanupEnabled(projectRoot)) {
151384
+ return { action: "complete" };
151385
+ }
150939
151386
  if (job.kind === "media-video-generation") {
150940
151387
  const { runMiniMaxVideoGenerationJob: runMiniMaxVideoGenerationJob2 } = await Promise.resolve().then(() => (init_video_jobs(), video_jobs_exports));
150941
151388
  return runMiniMaxVideoGenerationJob2(job, { dataDir: projectDir2, projectId });
@@ -151028,6 +151475,33 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
151028
151475
  });
151029
151476
  return { action: "complete" };
151030
151477
  }
151478
+ if (job.kind === "observation-project") {
151479
+ if (!projectRoot) {
151480
+ throw new Error(`Observation projection requires a project root for ${projectId}`);
151481
+ }
151482
+ const id = observationId(job.payload);
151483
+ if (!id) return { action: "complete" };
151484
+ const [
151485
+ { CodeGraphStore: CodeGraphStore2 },
151486
+ { bindObservationToCode: bindObservationToCode2 },
151487
+ { EvidenceCardStore: EvidenceCardStore2 },
151488
+ { getObservationStore: getObservationStore2 }
151489
+ ] = await Promise.all([
151490
+ Promise.resolve().then(() => (init_store(), store_exports)),
151491
+ Promise.resolve().then(() => (init_binder(), binder_exports)),
151492
+ Promise.resolve().then(() => (init_evidence_store(), evidence_store_exports)),
151493
+ Promise.resolve().then(() => (init_obs_store(), obs_store_exports))
151494
+ ]);
151495
+ const observation = await getObservationStore2().getById(id);
151496
+ if (!observation || observation.projectId !== projectId) return { action: "complete" };
151497
+ const codeStore = new CodeGraphStore2();
151498
+ await codeStore.init(projectDir2);
151499
+ await bindObservationToCode2(codeStore, observation);
151500
+ const evidence = new EvidenceCardStore2();
151501
+ await evidence.init(projectDir2);
151502
+ evidence.upsertObservation(observation);
151503
+ return { action: "complete" };
151504
+ }
151031
151505
  if (job.kind === "observation-qualify") {
151032
151506
  const [
151033
151507
  { CodeGraphStore: CodeGraphStore2 },
@@ -151235,7 +151709,15 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
151235
151709
  const after = getVectorStatus2(projectId);
151236
151710
  if (after.missing === 0) {
151237
151711
  resolveSupersededVectorFailures(projectDir2, projectId);
151238
- return { action: "complete" };
151712
+ return {
151713
+ action: "complete",
151714
+ progress: {
151715
+ attempted: result.attempted,
151716
+ succeeded: result.succeeded,
151717
+ failed: result.failed,
151718
+ remaining: 0
151719
+ }
151720
+ };
151239
151721
  }
151240
151722
  if (result.failed > 0 && result.succeeded === 0) {
151241
151723
  const streak = vectorBackfillFailureStreak(job.payload) + 1;
@@ -151250,6 +151732,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
151250
151732
  ...job.payload,
151251
151733
  vectorBackfillFailureStreak: streak
151252
151734
  },
151735
+ progress: {
151736
+ attempted: result.attempted,
151737
+ succeeded: result.succeeded,
151738
+ failed: result.failed,
151739
+ remaining: after.missing
151740
+ },
151253
151741
  lastError: result.lastError ?? `vector backfill made no progress (${result.failed}/${result.attempted} failed)`
151254
151742
  };
151255
151743
  }
@@ -151259,6 +151747,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
151259
151747
  action: "reschedule",
151260
151748
  delayMs: result.attempted === 0 ? VECTOR_RETRY_DELAY_MS : 0,
151261
151749
  resetAttempts: result.succeeded > 0,
151750
+ progress: {
151751
+ attempted: result.attempted,
151752
+ succeeded: result.succeeded,
151753
+ failed: result.failed,
151754
+ remaining: after.missing
151755
+ },
151262
151756
  ...result.succeeded > 0 ? {
151263
151757
  ...priorFailureStreak > 0 ? { payload } : {},
151264
151758
  ...result.failed > 0 && result.lastError ? { lastError: result.lastError } : priorFailureStreak > 0 ? { clearLastError: true } : {}
@@ -151585,10 +152079,22 @@ function resetObservationRuntime() {
151585
152079
  loadedObservationStore = null;
151586
152080
  embeddingWriteMode = "background";
151587
152081
  embeddingWorkerProjectRoot = void 0;
151588
- vectorMissingIds.clear();
152082
+ clearVectorMissingIds();
151589
152083
  vectorSchemaUpgradePromise = null;
151590
152084
  embeddingFailureLogTimestamps.clear();
151591
152085
  }
152086
+ function markVectorMissing(observationId2, projectId) {
152087
+ vectorMissingIds.add(observationId2);
152088
+ vectorMissingProjectIds.set(observationId2, projectId);
152089
+ }
152090
+ function clearVectorMissing(observationId2) {
152091
+ vectorMissingIds.delete(observationId2);
152092
+ vectorMissingProjectIds.delete(observationId2);
152093
+ }
152094
+ function clearVectorMissingIds() {
152095
+ vectorMissingIds.clear();
152096
+ vectorMissingProjectIds.clear();
152097
+ }
151592
152098
  function logEmbeddingFailureOnce(key, message) {
151593
152099
  const now3 = Date.now();
151594
152100
  const last = embeddingFailureLogTimestamps.get(key) ?? 0;
@@ -151655,24 +152161,40 @@ function queueVectorBackfill(projectId, options = {}) {
151655
152161
  });
151656
152162
  }
151657
152163
  async function bindObservationCodeRefsBestEffort(observation) {
151658
- if (!projectDir) return;
152164
+ if (!projectDir) return true;
151659
152165
  try {
151660
152166
  const { CodeGraphStore: CodeGraphStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
151661
152167
  const { bindObservationToCode: bindObservationToCode2 } = await Promise.resolve().then(() => (init_binder(), binder_exports));
151662
152168
  const codeStore = new CodeGraphStore2();
151663
152169
  await codeStore.init(projectDir);
151664
152170
  await bindObservationToCode2(codeStore, observation);
152171
+ return true;
151665
152172
  } catch {
152173
+ return false;
151666
152174
  }
151667
152175
  }
151668
152176
  async function persistEvidenceCard(observation) {
151669
- if (!projectDir) return;
152177
+ if (!projectDir) return true;
151670
152178
  try {
151671
152179
  const evidence = new EvidenceCardStore();
151672
152180
  await evidence.init(projectDir);
151673
152181
  evidence.upsertObservation(observation);
152182
+ return true;
151674
152183
  } catch (error) {
151675
152184
  console.error(`[memorix] Evidence card projection failed for obs-${observation.id}: ${error instanceof Error ? error.message : String(error)}`);
152185
+ return false;
152186
+ }
152187
+ }
152188
+ async function acknowledgeObservationProjection(observation) {
152189
+ if (!projectDir) return;
152190
+ try {
152191
+ const { MaintenanceJobStore: MaintenanceJobStore2 } = await Promise.resolve().then(() => (init_maintenance_jobs(), maintenance_jobs_exports));
152192
+ new MaintenanceJobStore2(projectDir).acknowledgePending(
152193
+ observation.projectId,
152194
+ "observation-project",
152195
+ "observation-project:" + observation.id
152196
+ );
152197
+ } catch {
151676
152198
  }
151677
152199
  }
151678
152200
  function queueClaimDerivation(observation) {
@@ -151701,6 +152223,41 @@ function queueObservationQualification(observation) {
151701
152223
  } catch {
151702
152224
  }
151703
152225
  }
152226
+ async function enqueueObservationDerivedWork(tx, observation) {
152227
+ if (!tx.enqueueMaintenanceJob) return false;
152228
+ if (!isEmbeddingExplicitlyDisabled()) {
152229
+ await tx.enqueueMaintenanceJob({
152230
+ projectId: observation.projectId,
152231
+ kind: "vector-backfill",
152232
+ dedupeKey: "vector-backfill",
152233
+ payload: { limit: 12 }
152234
+ });
152235
+ }
152236
+ if (observation.admissionState === "candidate") {
152237
+ await tx.enqueueMaintenanceJob({
152238
+ projectId: observation.projectId,
152239
+ kind: "observation-qualify",
152240
+ dedupeKey: "observation-qualify",
152241
+ payload: { source: "automatic-capture:" + observation.id, limit: 100 }
152242
+ });
152243
+ }
152244
+ const claimSource = observation.sourceDetail === "explicit" || observation.source === "git" || observation.sourceDetail === "git-ingest";
152245
+ if (claimSource && resolveObservationVisibility(observation) === "project") {
152246
+ await tx.enqueueMaintenanceJob({
152247
+ projectId: observation.projectId,
152248
+ kind: "claim-derive",
152249
+ dedupeKey: "claim-derive:" + observation.id,
152250
+ payload: { observationId: observation.id }
152251
+ });
152252
+ }
152253
+ await tx.enqueueMaintenanceJob({
152254
+ projectId: observation.projectId,
152255
+ kind: "observation-project",
152256
+ dedupeKey: "observation-project:" + observation.id,
152257
+ payload: { observationId: observation.id }
152258
+ });
152259
+ return true;
152260
+ }
151704
152261
  function isVectorCompatibleWithCurrentIndex(embedding) {
151705
152262
  if (!embedding) return false;
151706
152263
  const vectorDimensions = getVectorDimensions();
@@ -151708,10 +152265,13 @@ function isVectorCompatibleWithCurrentIndex(embedding) {
151708
152265
  }
151709
152266
  async function upgradeVectorSchemaAfterFirstEmbedding(embedding) {
151710
152267
  if (isVectorCompatibleWithCurrentIndex(embedding)) return true;
151711
- if (getVectorDimensions() !== null || !embedding.every(Number.isFinite)) return false;
152268
+ if (!embedding.every(Number.isFinite)) return false;
151712
152269
  const targetProjectDir = projectDir;
151713
152270
  if (!vectorSchemaUpgradePromise) {
151714
- vectorSchemaUpgradePromise = reindexObservations().then(() => projectDir === targetProjectDir && isVectorCompatibleWithCurrentIndex(embedding)).catch(() => false).finally(() => {
152271
+ vectorSchemaUpgradePromise = getDb().then(async () => {
152272
+ if (getVectorDimensions() === null && observations.length > 0) await reindexObservations();
152273
+ return projectDir === targetProjectDir && isVectorCompatibleWithCurrentIndex(embedding);
152274
+ }).catch(() => false).finally(() => {
151715
152275
  vectorSchemaUpgradePromise = null;
151716
152276
  });
151717
152277
  }
@@ -151751,9 +152311,9 @@ async function initObservations(dir, options = {}) {
151751
152311
  }
151752
152312
  function scheduleObservationEmbedding(input) {
151753
152313
  const { observationId: observationId2, projectId, searchableText, doc } = input;
151754
- vectorMissingIds.add(observationId2);
152314
+ markVectorMissing(observationId2, projectId);
151755
152315
  if (isEmbeddingExplicitlyDisabled()) {
151756
- vectorMissingIds.delete(observationId2);
152316
+ clearVectorMissing(observationId2);
151757
152317
  return;
151758
152318
  }
151759
152319
  if (embeddingWriteMode === "deferred") {
@@ -151788,13 +152348,13 @@ function scheduleObservationEmbedding(input) {
151788
152348
  vector: embedding
151789
152349
  });
151790
152350
  }
151791
- vectorMissingIds.delete(observationId2);
152351
+ clearVectorMissing(observationId2);
151792
152352
  } catch {
151793
152353
  console.error(`[memorix] Embedding index update failed for obs-${observationId2} (kept in backfill queue)`);
151794
152354
  queueVectorBackfill(projectId);
151795
152355
  }
151796
152356
  } else if (isEmbeddingExplicitlyDisabled()) {
151797
- vectorMissingIds.delete(observationId2);
152357
+ clearVectorMissing(observationId2);
151798
152358
  } else {
151799
152359
  queueVectorBackfill(projectId);
151800
152360
  logEmbeddingFailureOnce(
@@ -151876,7 +152436,6 @@ async function storeObservation(input) {
151876
152436
  throw new Error("Cannot update a memory outside this session's write scope.");
151877
152437
  }
151878
152438
  const observation2 = await upsertObservation(existing, input, now3);
151879
- await input.onPersisted?.(observation2);
151880
152439
  return { observation: observation2, upserted: true };
151881
152440
  }
151882
152441
  }
@@ -151903,6 +152462,7 @@ async function storeObservation(input) {
151903
152462
  let upsertedInsideLock = false;
151904
152463
  let reloadCacheAfterCommit = false;
151905
152464
  let persistedCallbackInvoked = false;
152465
+ let derivedJobsCommitted = false;
151906
152466
  const assignAndPersist = async () => {
151907
152467
  if (projectDir) {
151908
152468
  const store = getObservationStore();
@@ -151958,6 +152518,7 @@ async function storeObservation(input) {
151958
152518
  writeGeneration: transactionGeneration + 1
151959
152519
  };
151960
152520
  await tx.insert(observation);
152521
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, observation);
151961
152522
  await input.onPersisted?.(observation);
151962
152523
  persistedCallbackInvoked = true;
151963
152524
  await tx.saveIdCounter(id + 1);
@@ -152056,15 +152617,17 @@ async function storeObservation(input) {
152056
152617
  await assignAndPersist();
152057
152618
  if (upsertedInsideLock) {
152058
152619
  const updated = await upsertObservation(observation, input, now3);
152059
- await input.onPersisted?.(updated);
152060
152620
  return { observation: updated, upserted: true };
152061
152621
  }
152062
152622
  if (!persistedCallbackInvoked) await input.onPersisted?.(observation);
152063
- await bindObservationCodeRefsBestEffort(observation);
152064
- await persistEvidenceCard(observation);
152065
- queueObservationQualification(observation);
152066
- if (resolveObservationVisibility(observation) === "project") {
152067
- queueClaimDerivation(observation);
152623
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(observation);
152624
+ const evidenceProjected = await persistEvidenceCard(observation);
152625
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(observation);
152626
+ if (!derivedJobsCommitted) {
152627
+ queueObservationQualification(observation);
152628
+ if (resolveObservationVisibility(observation) === "project") {
152629
+ queueClaimDerivation(observation);
152630
+ }
152068
152631
  }
152069
152632
  scheduleObservationEmbedding({
152070
152633
  observationId: observation.id,
@@ -152086,86 +152649,115 @@ async function upsertObservation(existing, input, now3) {
152086
152649
  }
152087
152650
  const fullText = [input.title, input.narrative, ...input.facts ?? [], ...enrichedFiles, ...enrichedConcepts].join(" ");
152088
152651
  const tokens = countTextTokens(fullText);
152089
- existing.entityName = input.entityName;
152090
- existing.type = input.type;
152091
- existing.title = input.title;
152092
- existing.narrative = input.narrative;
152093
- existing.facts = input.facts ?? [];
152094
- existing.attachments = input.attachments;
152095
- existing.filesModified = enrichedFiles;
152096
- existing.concepts = enrichedConcepts;
152097
- existing.tokens = tokens;
152098
- existing.updatedAt = now3;
152099
- existing.hasCausalLanguage = extracted.hasCausalLanguage;
152100
- existing.revisionCount = (existing.revisionCount ?? 1) + 1;
152101
- existing.status = "active";
152102
- if (input.sessionId) existing.sessionId = input.sessionId;
152103
- if (input.progress) existing.progress = input.progress;
152104
- if (input.sourceDetail !== void 0) existing.sourceDetail = input.sourceDetail;
152105
- if (input.valueCategory !== void 0) existing.valueCategory = input.valueCategory;
152106
- if (input.admissionState !== void 0) existing.admissionState = input.admissionState;
152107
- if (input.admissionReason !== void 0) existing.admissionReason = sanitizeCredentials(input.admissionReason);
152108
- if (input.visibility !== void 0) existing.visibility = input.visibility;
152109
- if (input.sharedWithAgentIds !== void 0) existing.sharedWithAgentIds = input.sharedWithAgentIds;
152652
+ const applyUpdate = (current) => ({
152653
+ ...current,
152654
+ entityName: input.entityName,
152655
+ type: input.type,
152656
+ title: input.title,
152657
+ narrative: input.narrative,
152658
+ facts: input.facts ?? [],
152659
+ attachments: input.attachments,
152660
+ filesModified: enrichedFiles,
152661
+ concepts: enrichedConcepts,
152662
+ tokens,
152663
+ updatedAt: now3,
152664
+ hasCausalLanguage: extracted.hasCausalLanguage,
152665
+ revisionCount: (current.revisionCount ?? 1) + 1,
152666
+ status: "active",
152667
+ ...input.sessionId ? { sessionId: input.sessionId } : {},
152668
+ ...input.progress ? { progress: input.progress } : {},
152669
+ ...input.sourceDetail !== void 0 ? { sourceDetail: input.sourceDetail } : {},
152670
+ ...input.valueCategory !== void 0 ? { valueCategory: input.valueCategory } : {},
152671
+ ...input.admissionState !== void 0 ? { admissionState: input.admissionState } : {},
152672
+ ...input.admissionReason !== void 0 ? { admissionReason: sanitizeCredentials(input.admissionReason) } : {},
152673
+ ...input.visibility !== void 0 ? { visibility: input.visibility } : {},
152674
+ ...input.sharedWithAgentIds !== void 0 ? { sharedWithAgentIds: input.sharedWithAgentIds } : {}
152675
+ });
152676
+ let updated = applyUpdate(existing);
152677
+ let derivedJobsCommitted = false;
152678
+ if (projectDir) {
152679
+ const store = getObservationStore();
152680
+ await store.atomic(async (tx) => {
152681
+ const current = await tx.getById(existing.id);
152682
+ if (!current || current.projectId !== existing.projectId) {
152683
+ throw new Error("Topic observation changed before update");
152684
+ }
152685
+ updated = applyUpdate(current);
152686
+ updated.writeGeneration = await tx.getGeneration() + 1;
152687
+ await tx.update(updated);
152688
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, updated);
152689
+ await input.onPersisted?.(updated);
152690
+ });
152691
+ updated.writeGeneration = store.getGeneration();
152692
+ } else {
152693
+ await input.onPersisted?.(updated);
152694
+ }
152695
+ if (corpusLoaded) {
152696
+ const cacheIndex = observations.findIndex((observation) => observation.id === updated.id);
152697
+ if (cacheIndex >= 0) observations[cacheIndex] = updated;
152698
+ }
152110
152699
  const doc = {
152111
- id: makeOramaObservationId(existing.projectId, existing.id),
152112
- observationId: existing.id,
152113
- entityName: existing.entityName,
152114
- type: existing.type,
152115
- title: existing.title,
152116
- narrative: existing.narrative,
152117
- facts: existing.facts.join("\n"),
152700
+ id: makeOramaObservationId(updated.projectId, updated.id),
152701
+ observationId: updated.id,
152702
+ entityName: updated.entityName,
152703
+ type: updated.type,
152704
+ title: updated.title,
152705
+ narrative: updated.narrative,
152706
+ facts: updated.facts.join("\n"),
152118
152707
  filesModified: enrichedFiles.join("\n"),
152119
152708
  concepts: enrichedConcepts.map((c) => c.replace(/-/g, " ")).join(", "),
152120
- attachments: formatAttachmentProvenance(existing.attachments),
152709
+ attachments: formatAttachmentProvenance(updated.attachments),
152121
152710
  tokens,
152122
- createdAt: existing.createdAt,
152123
- projectId: existing.projectId,
152711
+ createdAt: updated.createdAt,
152712
+ projectId: updated.projectId,
152124
152713
  accessCount: 0,
152125
152714
  lastAccessedAt: "",
152126
152715
  status: "active",
152127
- source: existing.source ?? "agent",
152128
- sourceDetail: existing.sourceDetail ?? "",
152129
- valueCategory: existing.valueCategory ?? "",
152130
- admissionState: existing.admissionState ?? "",
152131
- admissionReason: existing.admissionReason ?? "",
152132
- visibility: existing.visibility ?? "project",
152133
- createdByAgentId: existing.createdByAgentId ?? "",
152134
- sharedWithAgentIds: JSON.stringify(existing.sharedWithAgentIds ?? [])
152135
- };
152136
- const oramaId = makeOramaObservationId(existing.projectId, existing.id);
152137
- try {
152138
- const { removeObservation: removeObservation2 } = await Promise.resolve().then(() => (init_orama_store(), orama_store_exports));
152139
- await removeObservation2(oramaId);
152140
- } catch {
152141
- }
152142
- try {
152143
- await insertObservation(doc);
152144
- } catch {
152716
+ source: updated.source ?? "agent",
152717
+ sourceDetail: updated.sourceDetail ?? "",
152718
+ valueCategory: updated.valueCategory ?? "",
152719
+ admissionState: updated.admissionState ?? "",
152720
+ admissionReason: updated.admissionReason ?? "",
152721
+ visibility: updated.visibility ?? "project",
152722
+ createdByAgentId: updated.createdByAgentId ?? "",
152723
+ sharedWithAgentIds: JSON.stringify(updated.sharedWithAgentIds ?? [])
152724
+ };
152725
+ if (corpusLoaded) {
152726
+ const oramaId = makeOramaObservationId(updated.projectId, updated.id);
152145
152727
  try {
152146
- const { removeObservation: removeObs } = await Promise.resolve().then(() => (init_orama_store(), orama_store_exports));
152147
- await removeObs(oramaId);
152728
+ try {
152729
+ await removeObservation(oramaId);
152730
+ } catch {
152731
+ }
152148
152732
  await insertObservation(doc);
152149
152733
  } catch {
152734
+ try {
152735
+ try {
152736
+ await removeObservation(oramaId);
152737
+ } catch {
152738
+ }
152739
+ await insertObservation(doc);
152740
+ } catch (error) {
152741
+ console.error(`[memorix] Observation index projection failed for obs-${updated.id}: ${sanitizeCredentials(error instanceof Error ? error.message : String(error))}`);
152742
+ }
152150
152743
  }
152151
152744
  }
152152
- if (projectDir) {
152153
- const store = getObservationStore();
152154
- await store.update(existing);
152155
- }
152156
- await bindObservationCodeRefsBestEffort(existing);
152157
- await persistEvidenceCard(existing);
152158
- queueObservationQualification(existing);
152159
- if (resolveObservationVisibility(existing) === "project") {
152160
- queueClaimDerivation(existing);
152745
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(updated);
152746
+ const evidenceProjected = await persistEvidenceCard(updated);
152747
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(updated);
152748
+ if (!derivedJobsCommitted) {
152749
+ queueObservationQualification(updated);
152750
+ if (resolveObservationVisibility(updated) === "project") {
152751
+ queueClaimDerivation(updated);
152752
+ }
152161
152753
  }
152162
152754
  scheduleObservationEmbedding({
152163
- observationId: existing.id,
152164
- projectId: existing.projectId,
152755
+ observationId: updated.id,
152756
+ projectId: updated.projectId,
152165
152757
  searchableText: [input.title, input.narrative, ...input.facts ?? []].join(" "),
152166
152758
  doc
152167
152759
  });
152168
- return existing;
152760
+ return updated;
152169
152761
  }
152170
152762
  function getObservation(id, projectId) {
152171
152763
  return observations.find((o) => o.id === id && (projectId ? o.projectId === projectId : true));
@@ -152354,7 +152946,7 @@ async function reindexObservations() {
152354
152946
  if (observations.length === 0) return 0;
152355
152947
  await resetDb();
152356
152948
  searchIndexPrepared = false;
152357
- vectorMissingIds.clear();
152949
+ clearVectorMissingIds();
152358
152950
  let embeddings = observations.map(() => null);
152359
152951
  const provider2 = await getEmbeddingProvider();
152360
152952
  const canBatchEmbedAtStartup = provider2 !== null && !provider2.name.startsWith("api-");
@@ -152419,7 +153011,7 @@ async function reindexObservations() {
152419
153011
  };
152420
153012
  await insertObservation(doc);
152421
153013
  if (!compatibleEmbedding && !isEmbeddingExplicitlyDisabled()) {
152422
- vectorMissingIds.add(obs.id);
153014
+ markVectorMissing(obs.id, obs.projectId);
152423
153015
  }
152424
153016
  count2++;
152425
153017
  } catch (err) {
@@ -152436,7 +153028,17 @@ async function prepareSearchIndex(options = {}) {
152436
153028
  if (!isEmbeddingExplicitlyDisabled()) {
152437
153029
  const store = getObservationStore();
152438
153030
  const projects = await store.listProjectIds?.() ?? [];
152439
- for (const projectId of projects) queueVectorBackfill(projectId);
153031
+ await getDb({ allowNetworkProbe: false }).catch(() => void 0);
153032
+ const persistedIds = projectDir ? await getPersistentSemanticVectorIds(projectDir).catch(() => null) : null;
153033
+ for (const projectId of projects) {
153034
+ const projectObservations = await store.loadByProject(projectId);
153035
+ for (const observation of projectObservations) {
153036
+ if (!persistedIds?.has(observation.id)) markVectorMissing(observation.id, observation.projectId);
153037
+ }
153038
+ if (projectObservations.some((observation) => !persistedIds?.has(observation.id))) {
153039
+ queueVectorBackfill(projectId);
153040
+ }
153041
+ }
152440
153042
  }
152441
153043
  return 0;
152442
153044
  }
@@ -152450,13 +153052,13 @@ async function prepareSearchIndex(options = {}) {
152450
153052
  const hydratedProjectDir = projectDir;
152451
153053
  const queueMissingVectors = async () => {
152452
153054
  if (!hydratedProjectDir || projectDir !== hydratedProjectDir) return;
152453
- vectorMissingIds.clear();
153055
+ clearVectorMissingIds();
152454
153056
  if (!isEmbeddingExplicitlyDisabled()) {
152455
153057
  const persistedSemanticIds = await getPersistentSemanticVectorIds(hydratedProjectDir).catch(() => null);
152456
153058
  const projectsWithMissingVectors = /* @__PURE__ */ new Set();
152457
153059
  for (const obs of observations) {
152458
153060
  if (!hasObservationVector(obs.projectId, obs.id) && !persistedSemanticIds?.has(obs.id)) {
152459
- vectorMissingIds.add(obs.id);
153061
+ markVectorMissing(obs.id, obs.projectId);
152460
153062
  projectsWithMissingVectors.add(obs.projectId);
152461
153063
  }
152462
153064
  }
@@ -152474,6 +153076,9 @@ async function prepareSearchIndex(options = {}) {
152474
153076
  }
152475
153077
  function getVectorMissingIds(projectId) {
152476
153078
  if (!projectId) return [...vectorMissingIds];
153079
+ if (!corpusLoaded) {
153080
+ return [...vectorMissingIds].filter((id) => vectorMissingProjectIds.get(id) === projectId);
153081
+ }
152477
153082
  const observationById = new Map(observations.map((observation) => [observation.id, observation]));
152478
153083
  return [...vectorMissingIds].filter((id) => observationById.get(id)?.projectId === projectId);
152479
153084
  }
@@ -152496,7 +153101,7 @@ function getSearchIndexStatus(projectId) {
152496
153101
  };
152497
153102
  }
152498
153103
  async function probeSearchIndex(projectId) {
152499
- await searchObservations({
153104
+ const result = await searchObservationsDetailed({
152500
153105
  query: "semantic memory retrieval status",
152501
153106
  projectId,
152502
153107
  reader: { projectId },
@@ -152504,14 +153109,15 @@ async function probeSearchIndex(projectId) {
152504
153109
  status: "all",
152505
153110
  trackAccess: false
152506
153111
  });
152507
- return getLastSearchMode(projectId);
153112
+ return result.diagnostics.mode;
152508
153113
  }
152509
153114
  async function backfillVectorEmbeddings(options = {}) {
152510
153115
  if (vectorBackfillRunning) {
152511
153116
  return { attempted: 0, succeeded: 0, failed: 0 };
152512
153117
  }
152513
153118
  vectorBackfillRunning = true;
152514
- const observationById = new Map(observations.map((observation) => [observation.id, observation]));
153119
+ const sourceObservations = corpusLoaded ? observations : options.projectId ? await getObservationStore().loadByProject(options.projectId, { status: "active" }) : await getObservationStore().loadAll();
153120
+ const observationById = new Map(sourceObservations.map((observation) => [observation.id, observation]));
152515
153121
  const limit2 = Number.isFinite(options.limit) ? Math.max(1, Math.floor(options.limit)) : Number.POSITIVE_INFINITY;
152516
153122
  const ids = [...vectorMissingIds].filter((id) => !options.projectId || observationById.get(id)?.projectId === options.projectId).slice(0, limit2);
152517
153123
  let succeeded = 0;
@@ -152524,7 +153130,7 @@ async function backfillVectorEmbeddings(options = {}) {
152524
153130
  for (const id of ids) {
152525
153131
  const observation = observationById.get(id);
152526
153132
  if (!observation) {
152527
- vectorMissingIds.delete(id);
153133
+ clearVectorMissing(id);
152528
153134
  continue;
152529
153135
  }
152530
153136
  candidates.push({
@@ -152542,7 +153148,7 @@ async function backfillVectorEmbeddings(options = {}) {
152542
153148
  const provider2 = await getEmbeddingProvider();
152543
153149
  if (!provider2) {
152544
153150
  if (isEmbeddingExplicitlyDisabled()) {
152545
- for (const candidate of candidates) vectorMissingIds.delete(candidate.id);
153151
+ for (const candidate of candidates) clearVectorMissing(candidate.id);
152546
153152
  } else {
152547
153153
  recordFailure("embedding provider unavailable");
152548
153154
  failed += candidates.length;
@@ -152619,7 +153225,7 @@ async function backfillVectorEmbeddings(options = {}) {
152619
153225
  vector: embedding
152620
153226
  });
152621
153227
  }
152622
- vectorMissingIds.delete(id);
153228
+ clearVectorMissing(id);
152623
153229
  succeeded++;
152624
153230
  } catch (error) {
152625
153231
  recordFailure(vectorBackfillError(error));
@@ -152644,7 +153250,7 @@ async function backfillVectorEmbeddings(options = {}) {
152644
153250
  ...lastFailure ? { lastError: lastFailure } : {}
152645
153251
  };
152646
153252
  }
152647
- 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;
153253
+ 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;
152648
153254
  var init_observations = __esm({
152649
153255
  "src/memory/observations.ts"() {
152650
153256
  "use strict";
@@ -152669,6 +153275,7 @@ var init_observations = __esm({
152669
153275
  loadedObservationStore = null;
152670
153276
  DEFAULT_ORAMA_HYDRATION_THRESHOLD = 1e4;
152671
153277
  vectorMissingIds = /* @__PURE__ */ new Set();
153278
+ vectorMissingProjectIds = /* @__PURE__ */ new Map();
152672
153279
  vectorBackfillRunning = false;
152673
153280
  vectorSchemaUpgradePromise = null;
152674
153281
  lastVectorBackfill = null;