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
@@ -1177,6 +1177,12 @@ CREATE TABLE IF NOT EXISTS maintenance_jobs (
1177
1177
  lease_owner TEXT,
1178
1178
  lease_expires_at INTEGER,
1179
1179
  last_error TEXT,
1180
+ attempted INTEGER NOT NULL DEFAULT 0,
1181
+ succeeded INTEGER NOT NULL DEFAULT 0,
1182
+ failed INTEGER NOT NULL DEFAULT 0,
1183
+ remaining INTEGER NOT NULL DEFAULT 0,
1184
+ progress_recorded INTEGER NOT NULL DEFAULT 0,
1185
+ rerun_requested INTEGER NOT NULL DEFAULT 0,
1180
1186
  created_at INTEGER NOT NULL,
1181
1187
  updated_at INTEGER NOT NULL,
1182
1188
  completed_at INTEGER
@@ -1597,6 +1603,22 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_maintenance_jobs_active_dedupe
1597
1603
  ON task_continuity_events(project_id, task_id, event_key)
1598
1604
  WHERE event_key IS NOT NULL`);
1599
1605
  }
1606
+ },
1607
+ {
1608
+ id: "1.11-maintenance-progress",
1609
+ apply: (db2) => {
1610
+ addColumnIfMissing(db2, "maintenance_jobs", "attempted", "attempted INTEGER NOT NULL DEFAULT 0");
1611
+ addColumnIfMissing(db2, "maintenance_jobs", "succeeded", "succeeded INTEGER NOT NULL DEFAULT 0");
1612
+ addColumnIfMissing(db2, "maintenance_jobs", "failed", "failed INTEGER NOT NULL DEFAULT 0");
1613
+ addColumnIfMissing(db2, "maintenance_jobs", "remaining", "remaining INTEGER NOT NULL DEFAULT 0");
1614
+ addColumnIfMissing(db2, "maintenance_jobs", "progress_recorded", "progress_recorded INTEGER NOT NULL DEFAULT 0");
1615
+ }
1616
+ },
1617
+ {
1618
+ id: "1.11-maintenance-rerun",
1619
+ apply: (db2) => {
1620
+ addColumnIfMissing(db2, "maintenance_jobs", "rerun_requested", "rerun_requested INTEGER NOT NULL DEFAULT 0");
1621
+ }
1600
1622
  }
1601
1623
  ];
1602
1624
  _dbCache = /* @__PURE__ */ new Map();
@@ -1741,6 +1763,7 @@ function loadYamlConfig(projectRoot, options = {}) {
1741
1763
  llm: { ...userConfig.llm, ...projectConfig.llm },
1742
1764
  agent: { ...userConfig.agent, ...projectConfig.agent },
1743
1765
  embedding: { ...userConfig.embedding, ...projectConfig.embedding },
1766
+ retrieval: { ...userConfig.retrieval, ...projectConfig.retrieval },
1744
1767
  rerank: { ...userConfig.rerank, ...projectConfig.rerank },
1745
1768
  git: { ...userConfig.git, ...projectConfig.git },
1746
1769
  codegraph: { ...userConfig.codegraph, ...projectConfig.codegraph },
@@ -1978,6 +2001,7 @@ function mergeTomlConfig(base, override) {
1978
2001
  llm: { ...base.memory?.llm, ...override.memory?.llm }
1979
2002
  },
1980
2003
  embedding: { ...base.embedding, ...override.embedding },
2004
+ retrieval: { ...base.retrieval, ...override.retrieval },
1981
2005
  rerank: { ...base.rerank, ...override.rerank },
1982
2006
  hooks: { ...base.hooks, ...override.hooks },
1983
2007
  git: { ...base.git, ...override.git },
@@ -2067,6 +2091,32 @@ var init_toml_loader = __esm({
2067
2091
  }
2068
2092
  });
2069
2093
 
2094
+ // src/config/retrieval-strategy.ts
2095
+ function isCjkHeavyQuery(query) {
2096
+ if (!query) return false;
2097
+ const matches = query.match(CJK);
2098
+ return (matches?.length ?? 0) / query.length > 0.3;
2099
+ }
2100
+ function normalizeRetrievalStrategy(value) {
2101
+ if (value === "vector" || value === "hybrid") return value;
2102
+ return void 0;
2103
+ }
2104
+ function firstRetrievalStrategy(fallback, ...values) {
2105
+ for (const value of values) {
2106
+ const normalized = normalizeRetrievalStrategy(value);
2107
+ if (normalized) return normalized;
2108
+ }
2109
+ return fallback;
2110
+ }
2111
+ var CJK;
2112
+ var init_retrieval_strategy = __esm({
2113
+ "src/config/retrieval-strategy.ts"() {
2114
+ "use strict";
2115
+ init_esm_shims();
2116
+ CJK = /[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g;
2117
+ }
2118
+ });
2119
+
2070
2120
  // src/config/resolved-config.ts
2071
2121
  var resolved_config_exports = {};
2072
2122
  __export(resolved_config_exports, {
@@ -2113,7 +2163,8 @@ function getResolvedConfig(options = {}) {
2113
2163
  const isRequesty = memoryLlmProvider === "requesty";
2114
2164
  const isApiRoute = memoryLlmProvider === "apiroute";
2115
2165
  const isCheaperInference = memoryLlmProvider === "cheaperinference";
2116
- const usesPresetKeyOnly = isAtlasCloud || isRequesty || isApiRoute || isCheaperInference;
2166
+ const isRuncrate = memoryLlmProvider === "runcrate";
2167
+ const usesPresetKeyOnly = isAtlasCloud || isRequesty || isApiRoute || isCheaperInference || isRuncrate;
2117
2168
  const memoryLlmApiKey = first(
2118
2169
  process.env.MEMORIX_LLM_API_KEY,
2119
2170
  process.env.MEMORIX_API_KEY,
@@ -2121,7 +2172,7 @@ function getResolvedConfig(options = {}) {
2121
2172
  yaml.llm?.apiKey,
2122
2173
  legacy.llm?.apiKey,
2123
2174
  // Never borrow another provider's credentials for these gateway presets.
2124
- 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,
2175
+ 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,
2125
2176
  usesPresetKeyOnly ? void 0 : process.env.ANTHROPIC_API_KEY,
2126
2177
  usesPresetKeyOnly ? void 0 : openRouterMemoryLlmApiKey
2127
2178
  );
@@ -2175,6 +2226,10 @@ function getResolvedConfig(options = {}) {
2175
2226
  apiKey: first(process.env.MEMORIX_EMBEDDING_API_KEY, toml.embedding?.api_key, yaml.embedding?.apiKey, legacy.embeddingApi?.apiKey, openRouterEmbeddingApiKey, requestyEmbeddingApiKey),
2176
2227
  dimensions: firstNumber(parseNumber(process.env.MEMORIX_EMBEDDING_DIMENSIONS), toml.embedding?.dimensions, yaml.embedding?.dimensions, legacy.embeddingApi?.dimensions)
2177
2228
  },
2229
+ retrieval: {
2230
+ cjk: firstRetrievalStrategy("vector", process.env.MEMORIX_RETRIEVAL_CJK, toml.retrieval?.cjk, yaml.retrieval?.cjk),
2231
+ ascii: firstRetrievalStrategy("hybrid", process.env.MEMORIX_RETRIEVAL_ASCII, toml.retrieval?.ascii, yaml.retrieval?.ascii)
2232
+ },
2178
2233
  rerank: resolveRerankLane({
2179
2234
  toml,
2180
2235
  yaml,
@@ -2192,6 +2247,7 @@ function getResolvedConfig(options = {}) {
2192
2247
  codegraph: {
2193
2248
  excludePatterns: firstArray(toml.codegraph?.exclude_patterns, yaml.codegraph?.excludePatterns),
2194
2249
  maxFileBytes: firstNumber(toml.codegraph?.max_file_bytes, yaml.codegraph?.maxFileBytes),
2250
+ autoRefresh: first(toml.codegraph?.auto_refresh, yaml.codegraph?.autoRefresh, "auto"),
2195
2251
  externalContext: first(
2196
2252
  normalizeExternalContext(process.env.MEMORIX_CODEGRAPH_EXTERNAL_CONTEXT),
2197
2253
  toml.codegraph?.external_context,
@@ -2295,6 +2351,8 @@ function getEnvSourceNames() {
2295
2351
  "MEMORIX_EMBEDDING_BASE_URL",
2296
2352
  "MEMORIX_EMBEDDING_MODEL",
2297
2353
  "MEMORIX_EMBEDDING_DIMENSIONS",
2354
+ "MEMORIX_RETRIEVAL_CJK",
2355
+ "MEMORIX_RETRIEVAL_ASCII",
2298
2356
  "MEMORIX_RERANK_PROVIDER",
2299
2357
  "MEMORIX_RERANK_MODEL",
2300
2358
  "MEMORIX_RERANK_BASE_URL",
@@ -2306,6 +2364,7 @@ function getEnvSourceNames() {
2306
2364
  "REQUESTY_API_KEY",
2307
2365
  "API_ROUTE_API_KEY",
2308
2366
  "CHEAPER_INFERENCE_API_KEY",
2367
+ "RUNCRATE_API_KEY",
2309
2368
  "ATLASCLOUD_API_KEY"
2310
2369
  ].filter((name) => process.env[name]);
2311
2370
  }
@@ -2402,6 +2461,7 @@ var init_resolved_config = __esm({
2402
2461
  init_toml_loader();
2403
2462
  init_yaml_loader();
2404
2463
  init_dotenv_loader();
2464
+ init_retrieval_strategy();
2405
2465
  }
2406
2466
  });
2407
2467
 
@@ -3152,6 +3212,7 @@ var init_provider = __esm({
3152
3212
  requesty: { baseUrl: "https://router.requesty.ai/v1", model: "openai/gpt-4.1-nano" },
3153
3213
  apiroute: { baseUrl: "https://global.api-route.com/v1", model: "deepseek-v4.1-flash" },
3154
3214
  cheaperinference: { baseUrl: "https://api.cheaperinference.com/v1", model: "gpt-5.4-mini" },
3215
+ runcrate: { baseUrl: "https://api.runcrate.ai/v1", model: "deepseek-ai/DeepSeek-V4.1-Flash" },
3155
3216
  atlascloud: { baseUrl: "https://api.atlascloud.ai/v1", model: "deepseek-ai/deepseek-v3.2" },
3156
3217
  custom: { baseUrl: "http://localhost:11434/v1", model: "llama3" }
3157
3218
  };
@@ -3271,6 +3332,7 @@ var sqlite_store_exports = {};
3271
3332
  __export(sqlite_store_exports, {
3272
3333
  SqliteBackend: () => SqliteBackend
3273
3334
  });
3335
+ import { randomUUID as randomUUID2 } from "crypto";
3274
3336
  import path6 from "path";
3275
3337
  import fs3 from "fs";
3276
3338
  function obsToRow(obs) {
@@ -3659,6 +3721,32 @@ var init_sqlite_store = __esm({
3659
3721
  }, "Observation atomic write");
3660
3722
  try {
3661
3723
  const tx = {
3724
+ enqueueMaintenanceJob: async (input) => {
3725
+ const payloadJson = JSON.stringify(input.payload ?? {});
3726
+ const existing = this.db.prepare(`
3727
+ SELECT id, status FROM maintenance_jobs
3728
+ WHERE project_id = ? AND kind = ? AND dedupe_key = ?
3729
+ AND status IN ('pending', 'running', 'retry')
3730
+ LIMIT 1
3731
+ `).get(input.projectId, input.kind, input.dedupeKey);
3732
+ if (existing) {
3733
+ if (existing.status === "running") {
3734
+ this.db.prepare(`
3735
+ UPDATE maintenance_jobs
3736
+ SET rerun_requested = 1, payload_json = ?, updated_at = ?
3737
+ WHERE id = ?
3738
+ `).run(payloadJson, Date.now(), existing.id);
3739
+ }
3740
+ return;
3741
+ }
3742
+ const now3 = Date.now();
3743
+ this.db.prepare(`
3744
+ INSERT INTO maintenance_jobs (
3745
+ id, project_id, kind, dedupe_key, payload_json, status, attempts,
3746
+ max_attempts, run_after, created_at, updated_at
3747
+ ) VALUES (?, ?, ?, ?, ?, 'pending', 0, 8, ?, ?, ?)
3748
+ `).run(randomUUID2(), input.projectId, input.kind, input.dedupeKey, payloadJson, now3, now3, now3);
3749
+ },
3662
3750
  loadAll: async () => this.rawLoadAll(),
3663
3751
  getById: async (id) => this.rawGetById(id),
3664
3752
  findByTopicKey: async (projectId, topicKey) => this.rawFindByTopicKey(projectId, topicKey),
@@ -3729,6 +3817,7 @@ __export(obs_store_exports, {
3729
3817
  DegradedBackend: () => DegradedBackend,
3730
3818
  createObservationStore: () => createObservationStore,
3731
3819
  getObservationStore: () => getObservationStore,
3820
+ getObservationStoreDataDir: () => getObservationStoreDataDir,
3732
3821
  initObservationStore: () => initObservationStore,
3733
3822
  resetObservationStore: () => resetObservationStore,
3734
3823
  setObservationStore: () => setObservationStore
@@ -3739,6 +3828,12 @@ function getObservationStore() {
3739
3828
  }
3740
3829
  return _store;
3741
3830
  }
3831
+ function getObservationStoreDataDir() {
3832
+ if (!_store || !_storeDataDir) {
3833
+ throw new Error("[memorix] ObservationStore data directory is not bound");
3834
+ }
3835
+ return _storeDataDir;
3836
+ }
3742
3837
  function setObservationStore(store) {
3743
3838
  _store = store;
3744
3839
  }
@@ -4721,8 +4816,8 @@ async function loadCacheJsonl(filePath) {
4721
4816
  loaded = cache3.size;
4722
4817
  } catch {
4723
4818
  }
4724
- if (onDiskCount % 250 === 0) {
4725
- await new Promise((resolve2) => setImmediate(resolve2));
4819
+ if (onDiskCount % CACHE_LOAD_YIELD_EVERY === 0) {
4820
+ await new Promise((resolve2) => setTimeout(resolve2, 0));
4726
4821
  }
4727
4822
  }
4728
4823
  diskCacheEntryCount = onDiskCount;
@@ -5051,6 +5146,12 @@ async function fetchWithRetry(url, apiKey, body, options = {}, attempt = 0, nati
5051
5146
  if (err instanceof Error && (err.name === "AbortError" || controller.signal.aborted || options.signal?.aborted)) {
5052
5147
  throw new Error(`Embedding API timeout after ${timeoutMs}ms: ${url}`);
5053
5148
  }
5149
+ if (options.retry !== false && attempt < MAX_RETRIES2) {
5150
+ const delay3 = BASE_DELAY_MS * Math.pow(2, attempt);
5151
+ console.error(`[memorix] Embedding transport failure, retry ${attempt + 1}/${MAX_RETRIES2} in ${delay3}ms`);
5152
+ await waitForRetry(delay3, options.signal);
5153
+ return fetchWithRetry(url, apiKey, body, options, attempt + 1, nativeGemini);
5154
+ }
5054
5155
  throw err;
5055
5156
  }
5056
5157
  try {
@@ -5129,7 +5230,7 @@ async function waitForRetry(waitMs, signal) {
5129
5230
  abortSignal.addEventListener("abort", onAbort, { once: true });
5130
5231
  });
5131
5232
  }
5132
- 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;
5233
+ 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;
5133
5234
  var init_api_provider = __esm({
5134
5235
  "src/embedding/api-provider.ts"() {
5135
5236
  "use strict";
@@ -5157,6 +5258,7 @@ var init_api_provider = __esm({
5157
5258
  DASHSCOPE_MAX_BATCH_SIZE = 10;
5158
5259
  MAX_RETRIES2 = 3;
5159
5260
  BASE_DELAY_MS = 500;
5261
+ CACHE_LOAD_YIELD_EVERY = 32;
5160
5262
  EmbeddingAPIError = class extends Error {
5161
5263
  status;
5162
5264
  constructor(status, detail) {
@@ -5208,7 +5310,7 @@ var init_api_provider = __esm({
5208
5310
  console.error(`[memorix] Dimension shortening: ${config.requestedDimensions}d requested`);
5209
5311
  }
5210
5312
  if (allowNetworkProbe) {
5211
- startDiskCacheLoad();
5313
+ setImmediate(startDiskCacheLoad);
5212
5314
  }
5213
5315
  return new _APIEmbeddingProvider(config, probeDimensions);
5214
5316
  }
@@ -5280,10 +5382,8 @@ var init_api_provider = __esm({
5280
5382
  return this.embedInput({ modality: "text", text: normalized }, { intent: "document", ...options });
5281
5383
  }
5282
5384
  const hash4 = textHash2(normalized, this.cacheKeyNamespace);
5283
- if (diskCacheLoaded) {
5284
- const cached = cache3.get(hash4);
5285
- if (cached) return cached;
5286
- }
5385
+ const cached = cache3.get(hash4);
5386
+ if (cached) return cached;
5287
5387
  const apiCall = async () => {
5288
5388
  const body = {
5289
5389
  model: this.config.model,
@@ -5308,8 +5408,8 @@ var init_api_provider = __esm({
5308
5408
  let embedding;
5309
5409
  if (!diskCacheLoaded && diskCacheLoadPromise) {
5310
5410
  const cacheRace = diskCacheLoadPromise.then(() => {
5311
- const cached = cache3.get(hash4);
5312
- if (cached) return cached;
5411
+ const cached2 = cache3.get(hash4);
5412
+ if (cached2) return cached2;
5313
5413
  return null;
5314
5414
  });
5315
5415
  const result = await Promise.race([
@@ -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,
@@ -9492,6 +9879,7 @@ var init_isolated_maintenance = __esm({
9492
9879
  "consolidation",
9493
9880
  "codegraph-refresh",
9494
9881
  "observation-qualify",
9882
+ "observation-project",
9495
9883
  "claim-derive",
9496
9884
  "claim-requalification",
9497
9885
  "knowledge-compile",
@@ -9504,7 +9892,7 @@ var init_isolated_maintenance = __esm({
9504
9892
  });
9505
9893
 
9506
9894
  // src/knowledge/workspace-store.ts
9507
- import { randomUUID as randomUUID4 } from "crypto";
9895
+ import { randomUUID as randomUUID5 } from "crypto";
9508
9896
  function arrayValue(raw) {
9509
9897
  if (typeof raw !== "string" || !raw) return [];
9510
9898
  try {
@@ -9645,7 +10033,7 @@ var init_workspace_store = __esm({
9645
10033
  }
9646
10034
  createProposal(input) {
9647
10035
  const proposal = {
9648
- id: input.id ?? randomUUID4(),
10036
+ id: input.id ?? randomUUID5(),
9649
10037
  ...input,
9650
10038
  status: input.status ?? "pending",
9651
10039
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
@@ -9931,11 +10319,11 @@ __export(consolidation_exports, {
9931
10319
  });
9932
10320
  function tokenize(text2) {
9933
10321
  return new Set(
9934
- text2.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff\s-]/g, " ").split(/\s+/).filter((t2) => t2.length > 1)
10322
+ text2.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, " ").split(/\s+/).filter((t2) => t2.length > 1)
9935
10323
  );
9936
10324
  }
9937
10325
  function jaccardSimilarity(a, b) {
9938
- if (a.size === 0 && b.size === 0) return 1;
10326
+ if (a.size === 0 && b.size === 0) return 0;
9939
10327
  let intersection = 0;
9940
10328
  for (const token of a) {
9941
10329
  if (b.has(token)) intersection++;
@@ -10301,7 +10689,7 @@ Respond in JSON only:
10301
10689
  });
10302
10690
 
10303
10691
  // src/media/media-store.ts
10304
- import { randomUUID as randomUUID5 } from "crypto";
10692
+ import { randomUUID as randomUUID6 } from "crypto";
10305
10693
  function asOptionalText(value) {
10306
10694
  return typeof value === "string" && value.length > 0 ? value : void 0;
10307
10695
  }
@@ -10471,7 +10859,7 @@ var init_media_store = __esm({
10471
10859
  return { asset: this.getAsset(input.projectId, existing.id), deduplicated: true };
10472
10860
  }
10473
10861
  const asset = {
10474
- id: randomUUID5(),
10862
+ id: randomUUID6(),
10475
10863
  ...input,
10476
10864
  createdAt: now3,
10477
10865
  updatedAt: now3
@@ -10551,7 +10939,7 @@ var init_media_store = __esm({
10551
10939
  `).get(input.assetId, input.observationId ?? null, input.role);
10552
10940
  if (existing) return rowToLink(existing);
10553
10941
  const link = {
10554
- id: randomUUID5(),
10942
+ id: randomUUID6(),
10555
10943
  assetId: input.assetId,
10556
10944
  projectId: input.projectId,
10557
10945
  ...input.observationId !== void 0 ? { observationId: input.observationId } : {},
@@ -10590,7 +10978,7 @@ var init_media_store = __esm({
10590
10978
  return rowToDerivation(this.db.prepare("SELECT * FROM media_derivations WHERE id = ?").get(existing.id));
10591
10979
  }
10592
10980
  const derivation = {
10593
- id: randomUUID5(),
10981
+ id: randomUUID6(),
10594
10982
  ...input,
10595
10983
  content,
10596
10984
  ...error ? { error } : {},
@@ -10677,7 +11065,7 @@ var init_media_store = __esm({
10677
11065
  createJob(input) {
10678
11066
  const now3 = Date.now();
10679
11067
  const job = {
10680
- id: randomUUID5(),
11068
+ id: randomUUID6(),
10681
11069
  projectId: input.projectId,
10682
11070
  kind: input.kind,
10683
11071
  status: "queued",
@@ -10839,7 +11227,7 @@ var init_types2 = __esm({
10839
11227
  });
10840
11228
 
10841
11229
  // src/media/asset-store.ts
10842
- import { createHash as createHash7, randomUUID as randomUUID6 } from "crypto";
11230
+ import { createHash as createHash7, randomUUID as randomUUID7 } from "crypto";
10843
11231
  import { copyFile, lstat, mkdir as mkdir3, open, readFile as readFile3, readdir, rename as rename2, rm, stat as stat2, writeFile as writeFile3 } from "fs/promises";
10844
11232
  import path12 from "path";
10845
11233
  function mediaRoot(dataDir) {
@@ -10910,7 +11298,7 @@ async function destinationExists(destination) {
10910
11298
  async function persistBuffer(bytes, destination) {
10911
11299
  await mkdir3(path12.dirname(destination), { recursive: true });
10912
11300
  if (await destinationExists(destination)) return false;
10913
- const temporary = `${destination}.${randomUUID6()}.tmp`;
11301
+ const temporary = `${destination}.${randomUUID7()}.tmp`;
10914
11302
  try {
10915
11303
  await writeFile3(temporary, bytes, { flag: "wx" });
10916
11304
  await rename2(temporary, destination);
@@ -63812,7 +64200,7 @@ var require_gaxios = __commonJS({
63812
64200
  var retry_js_1 = require_retry3();
63813
64201
  var stream_1 = __require("stream");
63814
64202
  var interceptor_js_1 = require_interceptor();
63815
- var randomUUID16 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
64203
+ var randomUUID17 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
63816
64204
  var HTTP_STATUS_NO_CONTENT = 204;
63817
64205
  var Gaxios = class {
63818
64206
  agentCache = /* @__PURE__ */ new Map();
@@ -64085,7 +64473,7 @@ var require_gaxios = __commonJS({
64085
64473
  */
64086
64474
  ["Blob", "File", "FormData"].includes(opts.data?.constructor?.name || "");
64087
64475
  if (opts.multipart?.length) {
64088
- const boundary = await randomUUID16();
64476
+ const boundary = await randomUUID17();
64089
64477
  preparedHeaders.set("content-type", `multipart/related; boundary=${boundary}`);
64090
64478
  opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary));
64091
64479
  } else if (shouldDirectlyPassData) {
@@ -144840,14 +145228,23 @@ var init_audio_jobs = __esm({
144840
145228
  }
144841
145229
  });
144842
145230
 
144843
- // src/memory/feedback-model.ts
145231
+ // src/core/retrieval-policy.ts
144844
145232
  function feedbackWeightMultiplier(weight) {
144845
145233
  return Math.max(0.35, Math.min(1.4, 0.35 + Math.max(0, Math.min(2, weight)) * 0.525));
144846
145234
  }
145235
+ var init_retrieval_policy = __esm({
145236
+ "src/core/retrieval-policy.ts"() {
145237
+ "use strict";
145238
+ init_esm_shims();
145239
+ }
145240
+ });
145241
+
145242
+ // src/memory/feedback-model.ts
144847
145243
  var init_feedback_model = __esm({
144848
145244
  "src/memory/feedback-model.ts"() {
144849
145245
  "use strict";
144850
145246
  init_esm_shims();
145247
+ init_retrieval_policy();
144851
145248
  }
144852
145249
  });
144853
145250
 
@@ -144859,7 +145256,7 @@ __export(feedback_exports, {
144859
145256
  applyMemoryFeedback: () => applyMemoryFeedback,
144860
145257
  feedbackWeightMultiplier: () => feedbackWeightMultiplier
144861
145258
  });
144862
- import { randomUUID as randomUUID7 } from "crypto";
145259
+ import { randomUUID as randomUUID8 } from "crypto";
144863
145260
  function applyMemoryFeedback(current, event) {
144864
145261
  const delta = event.signal === "revoke" ? 0 : FEEDBACK_DELTAS[event.signal];
144865
145262
  const weight = Math.max(0, Math.min(2, current.weight + delta));
@@ -144977,7 +145374,7 @@ var init_feedback = __esm({
144977
145374
  if (!target) throw new Error("The feedback event to revoke was not found in the same candidate scope.");
144978
145375
  }
144979
145376
  const event = {
144980
- id: randomUUID7(),
145377
+ id: randomUUID8(),
144981
145378
  projectId: input.projectId,
144982
145379
  candidateKind: input.candidateKind,
144983
145380
  candidateId: input.candidateId,
@@ -145365,7 +145762,7 @@ var init_retention = __esm({
145365
145762
  });
145366
145763
 
145367
145764
  // src/memory/owner.ts
145368
- import { randomUUID as randomUUID8 } from "crypto";
145765
+ import { randomUUID as randomUUID9 } from "crypto";
145369
145766
  import { promises as fs9 } from "fs";
145370
145767
  import path18 from "path";
145371
145768
  function ownerPath(dataDir) {
@@ -145395,7 +145792,7 @@ async function resolveLocalMemoryOwner(dataDir, options = {}) {
145395
145792
  await fs9.mkdir(path18.dirname(filePath), { recursive: true });
145396
145793
  const created = {
145397
145794
  version: 1,
145398
- id: "local-" + randomUUID8(),
145795
+ id: "local-" + randomUUID9(),
145399
145796
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
145400
145797
  };
145401
145798
  try {
@@ -145418,7 +145815,7 @@ var init_owner = __esm({
145418
145815
  });
145419
145816
 
145420
145817
  // src/memory/long-term-store.ts
145421
- import { randomUUID as randomUUID9 } from "crypto";
145818
+ import { randomUUID as randomUUID10 } from "crypto";
145422
145819
  function optionalText2(value) {
145423
145820
  return typeof value === "string" && value.trim() ? value : void 0;
145424
145821
  }
@@ -145578,7 +145975,7 @@ var init_long_term_store = __esm({
145578
145975
  }
145579
145976
  insertEvidence(input) {
145580
145977
  const evidence = {
145581
- id: randomUUID9(),
145978
+ id: randomUUID10(),
145582
145979
  ...input,
145583
145980
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
145584
145981
  };
@@ -145605,7 +146002,7 @@ var init_long_term_store = __esm({
145605
146002
  }
145606
146003
  recordEvent(input) {
145607
146004
  const event = {
145608
- id: randomUUID9(),
146005
+ id: randomUUID10(),
145609
146006
  ...input,
145610
146007
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
145611
146008
  };
@@ -145695,7 +146092,7 @@ __export(long_term_exports, {
145695
146092
  selectLongTermMemoriesForTask: () => selectLongTermMemoriesForTask,
145696
146093
  supersedeLongTermMemory: () => supersedeLongTermMemory
145697
146094
  });
145698
- import { randomUUID as randomUUID10 } from "crypto";
146095
+ import { randomUUID as randomUUID11 } from "crypto";
145699
146096
  function isOneOf(value, values) {
145700
146097
  return typeof value === "string" && values.includes(value);
145701
146098
  }
@@ -145877,7 +146274,7 @@ async function createManualLongTermMemory(input) {
145877
146274
  const owner = await resolveLocalMemoryOwner(input.dataDir, { create: true });
145878
146275
  if (!owner) throw new Error("Memorix could not resolve a local memory owner.");
145879
146276
  assertScope(input.scope);
145880
- const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID10(), relation: "supports" }];
146277
+ const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID11(), relation: "supports" }];
145881
146278
  return createLongTermMemoryWithDataDir({
145882
146279
  dataDir: input.dataDir,
145883
146280
  originProjectId: input.projectId,
@@ -145932,7 +146329,7 @@ async function createLongTermMemoryWithDataDir(input) {
145932
146329
  assertPortableEvidence(input.scope, portability, evidenceInputs);
145933
146330
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
145934
146331
  const memory = {
145935
- id: randomUUID10(),
146332
+ id: randomUUID11(),
145936
146333
  originProjectId: compactText(input.originProjectId, "origin project id", 1e3),
145937
146334
  ownerId: compactText(input.ownerId, "owner id", 160),
145938
146335
  scope: input.scope,
@@ -146287,7 +146684,7 @@ var store_exports = {};
146287
146684
  __export(store_exports, {
146288
146685
  CodeGraphStore: () => CodeGraphStore
146289
146686
  });
146290
- import { randomUUID as randomUUID11 } from "crypto";
146687
+ import { randomUUID as randomUUID12 } from "crypto";
146291
146688
  import { posix as pathPosix } from "path";
146292
146689
  function rowToFile(row) {
146293
146690
  return {
@@ -147216,8 +147613,9 @@ var init_store = __esm({
147216
147613
  * so an interrupted scan cannot be advertised as complete.
147217
147614
  */
147218
147615
  recordCodeStateSnapshot(input) {
147219
- const id = randomUUID11();
147616
+ const id = randomUUID12();
147220
147617
  let snapshot;
147618
+ let compactNeeded = false;
147221
147619
  const tx = this.db.transaction(() => {
147222
147620
  const previous = this.db.prepare(
147223
147621
  "SELECT id, sourceEpoch FROM code_state_snapshots WHERE projectId = ? ORDER BY sourceEpoch DESC LIMIT 1"
@@ -147261,6 +147659,26 @@ var init_store = __esm({
147261
147659
  for (const file of snapshotFileRows) {
147262
147660
  insertSnapshotFile.run(id, file.projectId, file.id, file.path, file.contentHash);
147263
147661
  }
147662
+ const staleSymbolIds = this.db.prepare(
147663
+ "SELECT id FROM code_symbols WHERE projectId = ? AND stale = 1"
147664
+ ).all(input.projectId).map((row) => row.id);
147665
+ if (staleSymbolIds.length > 0) {
147666
+ const placeholders = staleSymbolIds.map(() => "?").join(", ");
147667
+ this.db.prepare(
147668
+ `DELETE FROM code_edges WHERE projectId = ? AND (fromSymbolId IN (${placeholders}) OR toSymbolId IN (${placeholders}))`
147669
+ ).run(input.projectId, ...staleSymbolIds, ...staleSymbolIds);
147670
+ this.db.prepare("DELETE FROM code_symbols WHERE projectId = ? AND stale = 1").run(input.projectId);
147671
+ compactNeeded = true;
147672
+ }
147673
+ const oldSnapshots = this.db.prepare(
147674
+ "SELECT id FROM code_state_snapshots WHERE projectId = ? ORDER BY sourceEpoch DESC LIMIT -1 OFFSET 2"
147675
+ ).all(input.projectId).map((row) => row.id);
147676
+ if (oldSnapshots.length > 0) {
147677
+ const placeholders = oldSnapshots.map(() => "?").join(", ");
147678
+ this.db.prepare(`DELETE FROM code_state_snapshot_files WHERE snapshotId IN (${placeholders})`).run(...oldSnapshots);
147679
+ this.db.prepare(`DELETE FROM code_state_snapshots WHERE id IN (${placeholders})`).run(...oldSnapshots);
147680
+ compactNeeded = true;
147681
+ }
147264
147682
  snapshot = {
147265
147683
  ...input,
147266
147684
  id,
@@ -147269,11 +147687,24 @@ var init_store = __esm({
147269
147687
  };
147270
147688
  });
147271
147689
  tx();
147690
+ if (compactNeeded) this.compactStorage();
147272
147691
  return snapshot;
147273
147692
  }
147693
+ /** Reclaim WAL/free pages after a derived codegraph sweep. */
147694
+ compactStorage() {
147695
+ try {
147696
+ this.db.pragma("wal_checkpoint(TRUNCATE)");
147697
+ } catch {
147698
+ }
147699
+ try {
147700
+ this.db.exec("VACUUM");
147701
+ } catch {
147702
+ }
147703
+ }
147274
147704
  status(projectId) {
147275
147705
  const files = this.db.prepare(`SELECT COUNT(*) AS count FROM code_files WHERE projectId = ?`).get(projectId).count;
147276
147706
  const symbols = this.db.prepare(`SELECT COUNT(*) AS count FROM code_symbols WHERE projectId = ? AND stale = 0`).get(projectId).count;
147707
+ const staleSymbols = this.db.prepare(`SELECT COUNT(*) AS count FROM code_symbols WHERE projectId = ? AND stale = 1`).get(projectId).count;
147277
147708
  const edges = this.db.prepare(`SELECT COUNT(*) AS count FROM code_edges WHERE projectId = ?`).get(projectId).count;
147278
147709
  const refs = this.db.prepare(`SELECT COUNT(*) AS count FROM observation_code_refs WHERE projectId = ?`).get(projectId).count;
147279
147710
  const semanticSymbols = this.db.prepare(`SELECT COUNT(*) AS count FROM code_symbols WHERE projectId = ? AND stale = 0 AND source = 'typescript-compiler'`).get(projectId).count;
@@ -147281,6 +147712,8 @@ var init_store = __esm({
147281
147712
  const parserErrors = this.db.prepare(`SELECT COUNT(*) AS count FROM code_files WHERE projectId = ? AND parserError IS NOT NULL`).get(projectId).count;
147282
147713
  const latest = this.db.prepare(`SELECT MAX(indexedAt) AS indexedAt FROM code_files WHERE projectId = ?`).get(projectId);
147283
147714
  const latestSnapshot = this.latestSnapshot(projectId);
147715
+ const snapshots = this.db.prepare(`SELECT COUNT(*) AS count FROM code_state_snapshots WHERE projectId = ?`).get(projectId).count;
147716
+ const snapshotFiles = this.db.prepare(`SELECT COUNT(*) AS count FROM code_state_snapshot_files WHERE projectId = ?`).get(projectId).count;
147284
147717
  return {
147285
147718
  provider: "lite",
147286
147719
  files,
@@ -147290,6 +147723,9 @@ var init_store = __esm({
147290
147723
  semanticSymbols,
147291
147724
  semanticEdges,
147292
147725
  parserErrors,
147726
+ staleSymbols,
147727
+ snapshots,
147728
+ snapshotFiles,
147293
147729
  ...latest?.indexedAt ? { indexedAt: latest.indexedAt } : {},
147294
147730
  ...latestSnapshot ? { latestSnapshot } : {}
147295
147731
  };
@@ -148410,7 +148846,7 @@ var claim_store_exports = {};
148410
148846
  __export(claim_store_exports, {
148411
148847
  ClaimStore: () => ClaimStore
148412
148848
  });
148413
- import { createHash as createHash12, randomUUID as randomUUID12 } from "crypto";
148849
+ import { createHash as createHash12, randomUUID as randomUUID13 } from "crypto";
148414
148850
  function optionalText3(value) {
148415
148851
  return typeof value === "string" && value ? value : void 0;
148416
148852
  }
@@ -148594,7 +149030,7 @@ var init_claim_store = __esm({
148594
149030
  locator, capturedHash, evidenceKey, createdAt
148595
149031
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
148596
149032
  `).run(
148597
- randomUUID12(),
149033
+ randomUUID13(),
148598
149034
  input.claimId,
148599
149035
  input.evidenceKind,
148600
149036
  input.evidenceId,
@@ -148616,7 +149052,7 @@ var init_claim_store = __esm({
148616
149052
  }
148617
149053
  recordEvent(input) {
148618
149054
  const event = {
148619
- id: randomUUID12(),
149055
+ id: randomUUID13(),
148620
149056
  ...input,
148621
149057
  ...input.detail ? { detail: sanitizeCredentials(input.detail) } : {},
148622
149058
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
@@ -148661,7 +149097,7 @@ __export(claims_exports, {
148661
149097
  supersedeClaim: () => supersedeClaim,
148662
149098
  writeClaim: () => writeClaim
148663
149099
  });
148664
- import { createHash as createHash13, randomUUID as randomUUID13 } from "crypto";
149100
+ import { createHash as createHash13, randomUUID as randomUUID14 } from "crypto";
148665
149101
  function compactText2(value, field) {
148666
149102
  if (typeof value !== "string") throw new Error("Claim " + field + " must be text");
148667
149103
  const sanitized = sanitizeCredentials(value).trim().replace(/\s+/g, " ");
@@ -148747,7 +149183,7 @@ function normalizeClaimInput(input) {
148747
149183
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
148748
149184
  return {
148749
149185
  claim: {
148750
- id: randomUUID13(),
149186
+ id: randomUUID14(),
148751
149187
  projectId,
148752
149188
  subject,
148753
149189
  predicate,
@@ -149832,7 +150268,7 @@ var init_workflow_sync = __esm({
149832
150268
  });
149833
150269
 
149834
150270
  // src/knowledge/workflow-store.ts
149835
- import { randomUUID as randomUUID14 } from "crypto";
150271
+ import { randomUUID as randomUUID15 } from "crypto";
149836
150272
  function parseJson(value, fallback) {
149837
150273
  if (typeof value !== "string" || !value) return fallback;
149838
150274
  try {
@@ -149932,7 +150368,7 @@ var init_workflow_store = __esm({
149932
150368
  }
149933
150369
  recordRun(input) {
149934
150370
  const run = {
149935
- id: randomUUID14(),
150371
+ id: randomUUID15(),
149936
150372
  workflowId: input.workflowId,
149937
150373
  projectId: input.projectId,
149938
150374
  task: input.task.trim(),
@@ -150000,7 +150436,7 @@ var init_outcome_types = __esm({
150000
150436
  });
150001
150437
 
150002
150438
  // src/knowledge/outcome-store.ts
150003
- import { randomUUID as randomUUID15 } from "crypto";
150439
+ import { randomUUID as randomUUID16 } from "crypto";
150004
150440
  function optionalText5(value) {
150005
150441
  return typeof value === "string" && value.trim() ? value : void 0;
150006
150442
  }
@@ -150044,7 +150480,7 @@ var init_outcome_store = __esm({
150044
150480
  }
150045
150481
  record(input) {
150046
150482
  const signal = {
150047
- id: randomUUID15(),
150483
+ id: randomUUID16(),
150048
150484
  projectId: text(input.projectId, "project id"),
150049
150485
  candidateKind: oneOf(input.candidateKind, MEMORY_OUTCOME_CANDIDATE_KINDS, "candidate kind"),
150050
150486
  candidateId: text(input.candidateId, "candidate id"),
@@ -150878,6 +151314,15 @@ function observationId(payload) {
150878
151314
  const value = payload.observationId;
150879
151315
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
150880
151316
  }
151317
+ async function automaticCleanupEnabled(projectRoot) {
151318
+ if (!projectRoot) return true;
151319
+ try {
151320
+ const { getResolvedConfig: getResolvedConfig2 } = await Promise.resolve().then(() => (init_resolved_config(), resolved_config_exports));
151321
+ return getResolvedConfig2({ projectRoot }).memory.autoCleanup !== false;
151322
+ } catch {
151323
+ return true;
151324
+ }
151325
+ }
150881
151326
  function workspaceMode(payload) {
150882
151327
  return payload.workspaceMode === "local" || payload.workspaceMode === "versioned" ? payload.workspaceMode : void 0;
150883
151328
  }
@@ -150966,6 +151411,9 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
150966
151411
  if (job.projectId !== projectId) {
150967
151412
  return { action: "reschedule", delayMs: VECTOR_RETRY_DELAY_MS };
150968
151413
  }
151414
+ if ((job.kind === "retention-archive" || job.kind === "consolidation" || job.kind === "long-term-maintenance") && !await automaticCleanupEnabled(projectRoot)) {
151415
+ return { action: "complete" };
151416
+ }
150969
151417
  if (job.kind === "media-video-generation") {
150970
151418
  const { runMiniMaxVideoGenerationJob: runMiniMaxVideoGenerationJob2 } = await Promise.resolve().then(() => (init_video_jobs(), video_jobs_exports));
150971
151419
  return runMiniMaxVideoGenerationJob2(job, { dataDir: projectDir2, projectId });
@@ -151058,6 +151506,33 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
151058
151506
  });
151059
151507
  return { action: "complete" };
151060
151508
  }
151509
+ if (job.kind === "observation-project") {
151510
+ if (!projectRoot) {
151511
+ throw new Error(`Observation projection requires a project root for ${projectId}`);
151512
+ }
151513
+ const id = observationId(job.payload);
151514
+ if (!id) return { action: "complete" };
151515
+ const [
151516
+ { CodeGraphStore: CodeGraphStore2 },
151517
+ { bindObservationToCode: bindObservationToCode2 },
151518
+ { EvidenceCardStore: EvidenceCardStore2 },
151519
+ { getObservationStore: getObservationStore2 }
151520
+ ] = await Promise.all([
151521
+ Promise.resolve().then(() => (init_store(), store_exports)),
151522
+ Promise.resolve().then(() => (init_binder(), binder_exports)),
151523
+ Promise.resolve().then(() => (init_evidence_store(), evidence_store_exports)),
151524
+ Promise.resolve().then(() => (init_obs_store(), obs_store_exports))
151525
+ ]);
151526
+ const observation = await getObservationStore2().getById(id);
151527
+ if (!observation || observation.projectId !== projectId) return { action: "complete" };
151528
+ const codeStore = new CodeGraphStore2();
151529
+ await codeStore.init(projectDir2);
151530
+ await bindObservationToCode2(codeStore, observation);
151531
+ const evidence = new EvidenceCardStore2();
151532
+ await evidence.init(projectDir2);
151533
+ evidence.upsertObservation(observation);
151534
+ return { action: "complete" };
151535
+ }
151061
151536
  if (job.kind === "observation-qualify") {
151062
151537
  const [
151063
151538
  { CodeGraphStore: CodeGraphStore2 },
@@ -151265,7 +151740,15 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
151265
151740
  const after = getVectorStatus2(projectId);
151266
151741
  if (after.missing === 0) {
151267
151742
  resolveSupersededVectorFailures(projectDir2, projectId);
151268
- return { action: "complete" };
151743
+ return {
151744
+ action: "complete",
151745
+ progress: {
151746
+ attempted: result.attempted,
151747
+ succeeded: result.succeeded,
151748
+ failed: result.failed,
151749
+ remaining: 0
151750
+ }
151751
+ };
151269
151752
  }
151270
151753
  if (result.failed > 0 && result.succeeded === 0) {
151271
151754
  const streak = vectorBackfillFailureStreak(job.payload) + 1;
@@ -151280,6 +151763,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
151280
151763
  ...job.payload,
151281
151764
  vectorBackfillFailureStreak: streak
151282
151765
  },
151766
+ progress: {
151767
+ attempted: result.attempted,
151768
+ succeeded: result.succeeded,
151769
+ failed: result.failed,
151770
+ remaining: after.missing
151771
+ },
151283
151772
  lastError: result.lastError ?? `vector backfill made no progress (${result.failed}/${result.attempted} failed)`
151284
151773
  };
151285
151774
  }
@@ -151289,6 +151778,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
151289
151778
  action: "reschedule",
151290
151779
  delayMs: result.attempted === 0 ? VECTOR_RETRY_DELAY_MS : 0,
151291
151780
  resetAttempts: result.succeeded > 0,
151781
+ progress: {
151782
+ attempted: result.attempted,
151783
+ succeeded: result.succeeded,
151784
+ failed: result.failed,
151785
+ remaining: after.missing
151786
+ },
151292
151787
  ...result.succeeded > 0 ? {
151293
151788
  ...priorFailureStreak > 0 ? { payload } : {},
151294
151789
  ...result.failed > 0 && result.lastError ? { lastError: result.lastError } : priorFailureStreak > 0 ? { clearLastError: true } : {}
@@ -151615,10 +152110,22 @@ function resetObservationRuntime() {
151615
152110
  loadedObservationStore = null;
151616
152111
  embeddingWriteMode = "background";
151617
152112
  embeddingWorkerProjectRoot = void 0;
151618
- vectorMissingIds.clear();
152113
+ clearVectorMissingIds();
151619
152114
  vectorSchemaUpgradePromise = null;
151620
152115
  embeddingFailureLogTimestamps.clear();
151621
152116
  }
152117
+ function markVectorMissing(observationId2, projectId) {
152118
+ vectorMissingIds.add(observationId2);
152119
+ vectorMissingProjectIds.set(observationId2, projectId);
152120
+ }
152121
+ function clearVectorMissing(observationId2) {
152122
+ vectorMissingIds.delete(observationId2);
152123
+ vectorMissingProjectIds.delete(observationId2);
152124
+ }
152125
+ function clearVectorMissingIds() {
152126
+ vectorMissingIds.clear();
152127
+ vectorMissingProjectIds.clear();
152128
+ }
151622
152129
  function logEmbeddingFailureOnce(key, message) {
151623
152130
  const now3 = Date.now();
151624
152131
  const last = embeddingFailureLogTimestamps.get(key) ?? 0;
@@ -151685,24 +152192,40 @@ function queueVectorBackfill(projectId, options = {}) {
151685
152192
  });
151686
152193
  }
151687
152194
  async function bindObservationCodeRefsBestEffort(observation) {
151688
- if (!projectDir) return;
152195
+ if (!projectDir) return true;
151689
152196
  try {
151690
152197
  const { CodeGraphStore: CodeGraphStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
151691
152198
  const { bindObservationToCode: bindObservationToCode2 } = await Promise.resolve().then(() => (init_binder(), binder_exports));
151692
152199
  const codeStore = new CodeGraphStore2();
151693
152200
  await codeStore.init(projectDir);
151694
152201
  await bindObservationToCode2(codeStore, observation);
152202
+ return true;
151695
152203
  } catch {
152204
+ return false;
151696
152205
  }
151697
152206
  }
151698
152207
  async function persistEvidenceCard(observation) {
151699
- if (!projectDir) return;
152208
+ if (!projectDir) return true;
151700
152209
  try {
151701
152210
  const evidence = new EvidenceCardStore();
151702
152211
  await evidence.init(projectDir);
151703
152212
  evidence.upsertObservation(observation);
152213
+ return true;
151704
152214
  } catch (error) {
151705
152215
  console.error(`[memorix] Evidence card projection failed for obs-${observation.id}: ${error instanceof Error ? error.message : String(error)}`);
152216
+ return false;
152217
+ }
152218
+ }
152219
+ async function acknowledgeObservationProjection(observation) {
152220
+ if (!projectDir) return;
152221
+ try {
152222
+ const { MaintenanceJobStore: MaintenanceJobStore2 } = await Promise.resolve().then(() => (init_maintenance_jobs(), maintenance_jobs_exports));
152223
+ new MaintenanceJobStore2(projectDir).acknowledgePending(
152224
+ observation.projectId,
152225
+ "observation-project",
152226
+ "observation-project:" + observation.id
152227
+ );
152228
+ } catch {
151706
152229
  }
151707
152230
  }
151708
152231
  function queueClaimDerivation(observation) {
@@ -151731,6 +152254,41 @@ function queueObservationQualification(observation) {
151731
152254
  } catch {
151732
152255
  }
151733
152256
  }
152257
+ async function enqueueObservationDerivedWork(tx, observation) {
152258
+ if (!tx.enqueueMaintenanceJob) return false;
152259
+ if (!isEmbeddingExplicitlyDisabled()) {
152260
+ await tx.enqueueMaintenanceJob({
152261
+ projectId: observation.projectId,
152262
+ kind: "vector-backfill",
152263
+ dedupeKey: "vector-backfill",
152264
+ payload: { limit: 12 }
152265
+ });
152266
+ }
152267
+ if (observation.admissionState === "candidate") {
152268
+ await tx.enqueueMaintenanceJob({
152269
+ projectId: observation.projectId,
152270
+ kind: "observation-qualify",
152271
+ dedupeKey: "observation-qualify",
152272
+ payload: { source: "automatic-capture:" + observation.id, limit: 100 }
152273
+ });
152274
+ }
152275
+ const claimSource = observation.sourceDetail === "explicit" || observation.source === "git" || observation.sourceDetail === "git-ingest";
152276
+ if (claimSource && resolveObservationVisibility(observation) === "project") {
152277
+ await tx.enqueueMaintenanceJob({
152278
+ projectId: observation.projectId,
152279
+ kind: "claim-derive",
152280
+ dedupeKey: "claim-derive:" + observation.id,
152281
+ payload: { observationId: observation.id }
152282
+ });
152283
+ }
152284
+ await tx.enqueueMaintenanceJob({
152285
+ projectId: observation.projectId,
152286
+ kind: "observation-project",
152287
+ dedupeKey: "observation-project:" + observation.id,
152288
+ payload: { observationId: observation.id }
152289
+ });
152290
+ return true;
152291
+ }
151734
152292
  function isVectorCompatibleWithCurrentIndex(embedding) {
151735
152293
  if (!embedding) return false;
151736
152294
  const vectorDimensions = getVectorDimensions();
@@ -151738,10 +152296,13 @@ function isVectorCompatibleWithCurrentIndex(embedding) {
151738
152296
  }
151739
152297
  async function upgradeVectorSchemaAfterFirstEmbedding(embedding) {
151740
152298
  if (isVectorCompatibleWithCurrentIndex(embedding)) return true;
151741
- if (getVectorDimensions() !== null || !embedding.every(Number.isFinite)) return false;
152299
+ if (!embedding.every(Number.isFinite)) return false;
151742
152300
  const targetProjectDir = projectDir;
151743
152301
  if (!vectorSchemaUpgradePromise) {
151744
- vectorSchemaUpgradePromise = reindexObservations().then(() => projectDir === targetProjectDir && isVectorCompatibleWithCurrentIndex(embedding)).catch(() => false).finally(() => {
152302
+ vectorSchemaUpgradePromise = getDb().then(async () => {
152303
+ if (getVectorDimensions() === null && observations.length > 0) await reindexObservations();
152304
+ return projectDir === targetProjectDir && isVectorCompatibleWithCurrentIndex(embedding);
152305
+ }).catch(() => false).finally(() => {
151745
152306
  vectorSchemaUpgradePromise = null;
151746
152307
  });
151747
152308
  }
@@ -151781,9 +152342,9 @@ async function initObservations(dir, options = {}) {
151781
152342
  }
151782
152343
  function scheduleObservationEmbedding(input) {
151783
152344
  const { observationId: observationId2, projectId, searchableText, doc } = input;
151784
- vectorMissingIds.add(observationId2);
152345
+ markVectorMissing(observationId2, projectId);
151785
152346
  if (isEmbeddingExplicitlyDisabled()) {
151786
- vectorMissingIds.delete(observationId2);
152347
+ clearVectorMissing(observationId2);
151787
152348
  return;
151788
152349
  }
151789
152350
  if (embeddingWriteMode === "deferred") {
@@ -151818,13 +152379,13 @@ function scheduleObservationEmbedding(input) {
151818
152379
  vector: embedding
151819
152380
  });
151820
152381
  }
151821
- vectorMissingIds.delete(observationId2);
152382
+ clearVectorMissing(observationId2);
151822
152383
  } catch {
151823
152384
  console.error(`[memorix] Embedding index update failed for obs-${observationId2} (kept in backfill queue)`);
151824
152385
  queueVectorBackfill(projectId);
151825
152386
  }
151826
152387
  } else if (isEmbeddingExplicitlyDisabled()) {
151827
- vectorMissingIds.delete(observationId2);
152388
+ clearVectorMissing(observationId2);
151828
152389
  } else {
151829
152390
  queueVectorBackfill(projectId);
151830
152391
  logEmbeddingFailureOnce(
@@ -151906,7 +152467,6 @@ async function storeObservation(input) {
151906
152467
  throw new Error("Cannot update a memory outside this session's write scope.");
151907
152468
  }
151908
152469
  const observation2 = await upsertObservation(existing, input, now3);
151909
- await input.onPersisted?.(observation2);
151910
152470
  return { observation: observation2, upserted: true };
151911
152471
  }
151912
152472
  }
@@ -151933,6 +152493,7 @@ async function storeObservation(input) {
151933
152493
  let upsertedInsideLock = false;
151934
152494
  let reloadCacheAfterCommit = false;
151935
152495
  let persistedCallbackInvoked = false;
152496
+ let derivedJobsCommitted = false;
151936
152497
  const assignAndPersist = async () => {
151937
152498
  if (projectDir) {
151938
152499
  const store = getObservationStore();
@@ -151988,6 +152549,7 @@ async function storeObservation(input) {
151988
152549
  writeGeneration: transactionGeneration + 1
151989
152550
  };
151990
152551
  await tx.insert(observation);
152552
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, observation);
151991
152553
  await input.onPersisted?.(observation);
151992
152554
  persistedCallbackInvoked = true;
151993
152555
  await tx.saveIdCounter(id + 1);
@@ -152086,15 +152648,17 @@ async function storeObservation(input) {
152086
152648
  await assignAndPersist();
152087
152649
  if (upsertedInsideLock) {
152088
152650
  const updated = await upsertObservation(observation, input, now3);
152089
- await input.onPersisted?.(updated);
152090
152651
  return { observation: updated, upserted: true };
152091
152652
  }
152092
152653
  if (!persistedCallbackInvoked) await input.onPersisted?.(observation);
152093
- await bindObservationCodeRefsBestEffort(observation);
152094
- await persistEvidenceCard(observation);
152095
- queueObservationQualification(observation);
152096
- if (resolveObservationVisibility(observation) === "project") {
152097
- queueClaimDerivation(observation);
152654
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(observation);
152655
+ const evidenceProjected = await persistEvidenceCard(observation);
152656
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(observation);
152657
+ if (!derivedJobsCommitted) {
152658
+ queueObservationQualification(observation);
152659
+ if (resolveObservationVisibility(observation) === "project") {
152660
+ queueClaimDerivation(observation);
152661
+ }
152098
152662
  }
152099
152663
  scheduleObservationEmbedding({
152100
152664
  observationId: observation.id,
@@ -152116,86 +152680,115 @@ async function upsertObservation(existing, input, now3) {
152116
152680
  }
152117
152681
  const fullText = [input.title, input.narrative, ...input.facts ?? [], ...enrichedFiles, ...enrichedConcepts].join(" ");
152118
152682
  const tokens = countTextTokens(fullText);
152119
- existing.entityName = input.entityName;
152120
- existing.type = input.type;
152121
- existing.title = input.title;
152122
- existing.narrative = input.narrative;
152123
- existing.facts = input.facts ?? [];
152124
- existing.attachments = input.attachments;
152125
- existing.filesModified = enrichedFiles;
152126
- existing.concepts = enrichedConcepts;
152127
- existing.tokens = tokens;
152128
- existing.updatedAt = now3;
152129
- existing.hasCausalLanguage = extracted.hasCausalLanguage;
152130
- existing.revisionCount = (existing.revisionCount ?? 1) + 1;
152131
- existing.status = "active";
152132
- if (input.sessionId) existing.sessionId = input.sessionId;
152133
- if (input.progress) existing.progress = input.progress;
152134
- if (input.sourceDetail !== void 0) existing.sourceDetail = input.sourceDetail;
152135
- if (input.valueCategory !== void 0) existing.valueCategory = input.valueCategory;
152136
- if (input.admissionState !== void 0) existing.admissionState = input.admissionState;
152137
- if (input.admissionReason !== void 0) existing.admissionReason = sanitizeCredentials(input.admissionReason);
152138
- if (input.visibility !== void 0) existing.visibility = input.visibility;
152139
- if (input.sharedWithAgentIds !== void 0) existing.sharedWithAgentIds = input.sharedWithAgentIds;
152683
+ const applyUpdate = (current) => ({
152684
+ ...current,
152685
+ entityName: input.entityName,
152686
+ type: input.type,
152687
+ title: input.title,
152688
+ narrative: input.narrative,
152689
+ facts: input.facts ?? [],
152690
+ attachments: input.attachments,
152691
+ filesModified: enrichedFiles,
152692
+ concepts: enrichedConcepts,
152693
+ tokens,
152694
+ updatedAt: now3,
152695
+ hasCausalLanguage: extracted.hasCausalLanguage,
152696
+ revisionCount: (current.revisionCount ?? 1) + 1,
152697
+ status: "active",
152698
+ ...input.sessionId ? { sessionId: input.sessionId } : {},
152699
+ ...input.progress ? { progress: input.progress } : {},
152700
+ ...input.sourceDetail !== void 0 ? { sourceDetail: input.sourceDetail } : {},
152701
+ ...input.valueCategory !== void 0 ? { valueCategory: input.valueCategory } : {},
152702
+ ...input.admissionState !== void 0 ? { admissionState: input.admissionState } : {},
152703
+ ...input.admissionReason !== void 0 ? { admissionReason: sanitizeCredentials(input.admissionReason) } : {},
152704
+ ...input.visibility !== void 0 ? { visibility: input.visibility } : {},
152705
+ ...input.sharedWithAgentIds !== void 0 ? { sharedWithAgentIds: input.sharedWithAgentIds } : {}
152706
+ });
152707
+ let updated = applyUpdate(existing);
152708
+ let derivedJobsCommitted = false;
152709
+ if (projectDir) {
152710
+ const store = getObservationStore();
152711
+ await store.atomic(async (tx) => {
152712
+ const current = await tx.getById(existing.id);
152713
+ if (!current || current.projectId !== existing.projectId) {
152714
+ throw new Error("Topic observation changed before update");
152715
+ }
152716
+ updated = applyUpdate(current);
152717
+ updated.writeGeneration = await tx.getGeneration() + 1;
152718
+ await tx.update(updated);
152719
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, updated);
152720
+ await input.onPersisted?.(updated);
152721
+ });
152722
+ updated.writeGeneration = store.getGeneration();
152723
+ } else {
152724
+ await input.onPersisted?.(updated);
152725
+ }
152726
+ if (corpusLoaded) {
152727
+ const cacheIndex = observations.findIndex((observation) => observation.id === updated.id);
152728
+ if (cacheIndex >= 0) observations[cacheIndex] = updated;
152729
+ }
152140
152730
  const doc = {
152141
- id: makeOramaObservationId(existing.projectId, existing.id),
152142
- observationId: existing.id,
152143
- entityName: existing.entityName,
152144
- type: existing.type,
152145
- title: existing.title,
152146
- narrative: existing.narrative,
152147
- facts: existing.facts.join("\n"),
152731
+ id: makeOramaObservationId(updated.projectId, updated.id),
152732
+ observationId: updated.id,
152733
+ entityName: updated.entityName,
152734
+ type: updated.type,
152735
+ title: updated.title,
152736
+ narrative: updated.narrative,
152737
+ facts: updated.facts.join("\n"),
152148
152738
  filesModified: enrichedFiles.join("\n"),
152149
152739
  concepts: enrichedConcepts.map((c) => c.replace(/-/g, " ")).join(", "),
152150
- attachments: formatAttachmentProvenance(existing.attachments),
152740
+ attachments: formatAttachmentProvenance(updated.attachments),
152151
152741
  tokens,
152152
- createdAt: existing.createdAt,
152153
- projectId: existing.projectId,
152742
+ createdAt: updated.createdAt,
152743
+ projectId: updated.projectId,
152154
152744
  accessCount: 0,
152155
152745
  lastAccessedAt: "",
152156
152746
  status: "active",
152157
- source: existing.source ?? "agent",
152158
- sourceDetail: existing.sourceDetail ?? "",
152159
- valueCategory: existing.valueCategory ?? "",
152160
- admissionState: existing.admissionState ?? "",
152161
- admissionReason: existing.admissionReason ?? "",
152162
- visibility: existing.visibility ?? "project",
152163
- createdByAgentId: existing.createdByAgentId ?? "",
152164
- sharedWithAgentIds: JSON.stringify(existing.sharedWithAgentIds ?? [])
152165
- };
152166
- const oramaId = makeOramaObservationId(existing.projectId, existing.id);
152167
- try {
152168
- const { removeObservation: removeObservation2 } = await Promise.resolve().then(() => (init_orama_store(), orama_store_exports));
152169
- await removeObservation2(oramaId);
152170
- } catch {
152171
- }
152172
- try {
152173
- await insertObservation(doc);
152174
- } catch {
152747
+ source: updated.source ?? "agent",
152748
+ sourceDetail: updated.sourceDetail ?? "",
152749
+ valueCategory: updated.valueCategory ?? "",
152750
+ admissionState: updated.admissionState ?? "",
152751
+ admissionReason: updated.admissionReason ?? "",
152752
+ visibility: updated.visibility ?? "project",
152753
+ createdByAgentId: updated.createdByAgentId ?? "",
152754
+ sharedWithAgentIds: JSON.stringify(updated.sharedWithAgentIds ?? [])
152755
+ };
152756
+ if (corpusLoaded) {
152757
+ const oramaId = makeOramaObservationId(updated.projectId, updated.id);
152175
152758
  try {
152176
- const { removeObservation: removeObs } = await Promise.resolve().then(() => (init_orama_store(), orama_store_exports));
152177
- await removeObs(oramaId);
152759
+ try {
152760
+ await removeObservation(oramaId);
152761
+ } catch {
152762
+ }
152178
152763
  await insertObservation(doc);
152179
152764
  } catch {
152765
+ try {
152766
+ try {
152767
+ await removeObservation(oramaId);
152768
+ } catch {
152769
+ }
152770
+ await insertObservation(doc);
152771
+ } catch (error) {
152772
+ console.error(`[memorix] Observation index projection failed for obs-${updated.id}: ${sanitizeCredentials(error instanceof Error ? error.message : String(error))}`);
152773
+ }
152180
152774
  }
152181
152775
  }
152182
- if (projectDir) {
152183
- const store = getObservationStore();
152184
- await store.update(existing);
152185
- }
152186
- await bindObservationCodeRefsBestEffort(existing);
152187
- await persistEvidenceCard(existing);
152188
- queueObservationQualification(existing);
152189
- if (resolveObservationVisibility(existing) === "project") {
152190
- queueClaimDerivation(existing);
152776
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(updated);
152777
+ const evidenceProjected = await persistEvidenceCard(updated);
152778
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(updated);
152779
+ if (!derivedJobsCommitted) {
152780
+ queueObservationQualification(updated);
152781
+ if (resolveObservationVisibility(updated) === "project") {
152782
+ queueClaimDerivation(updated);
152783
+ }
152191
152784
  }
152192
152785
  scheduleObservationEmbedding({
152193
- observationId: existing.id,
152194
- projectId: existing.projectId,
152786
+ observationId: updated.id,
152787
+ projectId: updated.projectId,
152195
152788
  searchableText: [input.title, input.narrative, ...input.facts ?? []].join(" "),
152196
152789
  doc
152197
152790
  });
152198
- return existing;
152791
+ return updated;
152199
152792
  }
152200
152793
  function getObservation(id, projectId) {
152201
152794
  return observations.find((o) => o.id === id && (projectId ? o.projectId === projectId : true));
@@ -152384,7 +152977,7 @@ async function reindexObservations() {
152384
152977
  if (observations.length === 0) return 0;
152385
152978
  await resetDb();
152386
152979
  searchIndexPrepared = false;
152387
- vectorMissingIds.clear();
152980
+ clearVectorMissingIds();
152388
152981
  let embeddings = observations.map(() => null);
152389
152982
  const provider2 = await getEmbeddingProvider();
152390
152983
  const canBatchEmbedAtStartup = provider2 !== null && !provider2.name.startsWith("api-");
@@ -152449,7 +153042,7 @@ async function reindexObservations() {
152449
153042
  };
152450
153043
  await insertObservation(doc);
152451
153044
  if (!compatibleEmbedding && !isEmbeddingExplicitlyDisabled()) {
152452
- vectorMissingIds.add(obs.id);
153045
+ markVectorMissing(obs.id, obs.projectId);
152453
153046
  }
152454
153047
  count2++;
152455
153048
  } catch (err) {
@@ -152466,7 +153059,17 @@ async function prepareSearchIndex(options = {}) {
152466
153059
  if (!isEmbeddingExplicitlyDisabled()) {
152467
153060
  const store = getObservationStore();
152468
153061
  const projects = await store.listProjectIds?.() ?? [];
152469
- for (const projectId of projects) queueVectorBackfill(projectId);
153062
+ await getDb({ allowNetworkProbe: false }).catch(() => void 0);
153063
+ const persistedIds = projectDir ? await getPersistentSemanticVectorIds(projectDir).catch(() => null) : null;
153064
+ for (const projectId of projects) {
153065
+ const projectObservations = await store.loadByProject(projectId);
153066
+ for (const observation of projectObservations) {
153067
+ if (!persistedIds?.has(observation.id)) markVectorMissing(observation.id, observation.projectId);
153068
+ }
153069
+ if (projectObservations.some((observation) => !persistedIds?.has(observation.id))) {
153070
+ queueVectorBackfill(projectId);
153071
+ }
153072
+ }
152470
153073
  }
152471
153074
  return 0;
152472
153075
  }
@@ -152480,13 +153083,13 @@ async function prepareSearchIndex(options = {}) {
152480
153083
  const hydratedProjectDir = projectDir;
152481
153084
  const queueMissingVectors = async () => {
152482
153085
  if (!hydratedProjectDir || projectDir !== hydratedProjectDir) return;
152483
- vectorMissingIds.clear();
153086
+ clearVectorMissingIds();
152484
153087
  if (!isEmbeddingExplicitlyDisabled()) {
152485
153088
  const persistedSemanticIds = await getPersistentSemanticVectorIds(hydratedProjectDir).catch(() => null);
152486
153089
  const projectsWithMissingVectors = /* @__PURE__ */ new Set();
152487
153090
  for (const obs of observations) {
152488
153091
  if (!hasObservationVector(obs.projectId, obs.id) && !persistedSemanticIds?.has(obs.id)) {
152489
- vectorMissingIds.add(obs.id);
153092
+ markVectorMissing(obs.id, obs.projectId);
152490
153093
  projectsWithMissingVectors.add(obs.projectId);
152491
153094
  }
152492
153095
  }
@@ -152504,6 +153107,9 @@ async function prepareSearchIndex(options = {}) {
152504
153107
  }
152505
153108
  function getVectorMissingIds(projectId) {
152506
153109
  if (!projectId) return [...vectorMissingIds];
153110
+ if (!corpusLoaded) {
153111
+ return [...vectorMissingIds].filter((id) => vectorMissingProjectIds.get(id) === projectId);
153112
+ }
152507
153113
  const observationById = new Map(observations.map((observation) => [observation.id, observation]));
152508
153114
  return [...vectorMissingIds].filter((id) => observationById.get(id)?.projectId === projectId);
152509
153115
  }
@@ -152526,7 +153132,7 @@ function getSearchIndexStatus(projectId) {
152526
153132
  };
152527
153133
  }
152528
153134
  async function probeSearchIndex(projectId) {
152529
- await searchObservations({
153135
+ const result = await searchObservationsDetailed({
152530
153136
  query: "semantic memory retrieval status",
152531
153137
  projectId,
152532
153138
  reader: { projectId },
@@ -152534,14 +153140,15 @@ async function probeSearchIndex(projectId) {
152534
153140
  status: "all",
152535
153141
  trackAccess: false
152536
153142
  });
152537
- return getLastSearchMode(projectId);
153143
+ return result.diagnostics.mode;
152538
153144
  }
152539
153145
  async function backfillVectorEmbeddings(options = {}) {
152540
153146
  if (vectorBackfillRunning) {
152541
153147
  return { attempted: 0, succeeded: 0, failed: 0 };
152542
153148
  }
152543
153149
  vectorBackfillRunning = true;
152544
- const observationById = new Map(observations.map((observation) => [observation.id, observation]));
153150
+ const sourceObservations = corpusLoaded ? observations : options.projectId ? await getObservationStore().loadByProject(options.projectId, { status: "active" }) : await getObservationStore().loadAll();
153151
+ const observationById = new Map(sourceObservations.map((observation) => [observation.id, observation]));
152545
153152
  const limit2 = Number.isFinite(options.limit) ? Math.max(1, Math.floor(options.limit)) : Number.POSITIVE_INFINITY;
152546
153153
  const ids = [...vectorMissingIds].filter((id) => !options.projectId || observationById.get(id)?.projectId === options.projectId).slice(0, limit2);
152547
153154
  let succeeded = 0;
@@ -152554,7 +153161,7 @@ async function backfillVectorEmbeddings(options = {}) {
152554
153161
  for (const id of ids) {
152555
153162
  const observation = observationById.get(id);
152556
153163
  if (!observation) {
152557
- vectorMissingIds.delete(id);
153164
+ clearVectorMissing(id);
152558
153165
  continue;
152559
153166
  }
152560
153167
  candidates.push({
@@ -152572,7 +153179,7 @@ async function backfillVectorEmbeddings(options = {}) {
152572
153179
  const provider2 = await getEmbeddingProvider();
152573
153180
  if (!provider2) {
152574
153181
  if (isEmbeddingExplicitlyDisabled()) {
152575
- for (const candidate of candidates) vectorMissingIds.delete(candidate.id);
153182
+ for (const candidate of candidates) clearVectorMissing(candidate.id);
152576
153183
  } else {
152577
153184
  recordFailure("embedding provider unavailable");
152578
153185
  failed += candidates.length;
@@ -152649,7 +153256,7 @@ async function backfillVectorEmbeddings(options = {}) {
152649
153256
  vector: embedding
152650
153257
  });
152651
153258
  }
152652
- vectorMissingIds.delete(id);
153259
+ clearVectorMissing(id);
152653
153260
  succeeded++;
152654
153261
  } catch (error) {
152655
153262
  recordFailure(vectorBackfillError(error));
@@ -152674,7 +153281,7 @@ async function backfillVectorEmbeddings(options = {}) {
152674
153281
  ...lastFailure ? { lastError: lastFailure } : {}
152675
153282
  };
152676
153283
  }
152677
- 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;
153284
+ 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;
152678
153285
  var init_observations = __esm({
152679
153286
  "src/memory/observations.ts"() {
152680
153287
  "use strict";
@@ -152699,6 +153306,7 @@ var init_observations = __esm({
152699
153306
  loadedObservationStore = null;
152700
153307
  DEFAULT_ORAMA_HYDRATION_THRESHOLD = 1e4;
152701
153308
  vectorMissingIds = /* @__PURE__ */ new Set();
153309
+ vectorMissingProjectIds = /* @__PURE__ */ new Map();
152702
153310
  vectorBackfillRunning = false;
152703
153311
  vectorSchemaUpgradePromise = null;
152704
153312
  lastVectorBackfill = null;