memorix 1.10.3 → 1.10.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/CHANGELOG.md +88 -1
  2. package/dist/cli/index.js +2300 -1343
  3. package/dist/index.js +1947 -1139
  4. package/dist/{maintenance-jobs-DVRF-46r.d.ts → maintenance-jobs-DweoCoTT.d.ts} +25 -15
  5. package/dist/maintenance-runner.d.ts +1 -1
  6. package/dist/maintenance-runner.js +915 -221
  7. package/dist/media-audio-runner.js +906 -213
  8. package/dist/media-video-runner.js +914 -221
  9. package/dist/memcode-runtime/CHANGELOG.md +88 -1
  10. package/dist/sdk.js +10153 -9360
  11. package/dist/vector-backfill-runner.d.ts +1 -1
  12. package/dist/vector-backfill-runner.js +914 -221
  13. package/docs/AGENT_OPERATOR_PLAYBOOK.md +7 -0
  14. package/docs/ARCHITECTURE.md +238 -0
  15. package/docs/CONFIGURATION.md +17 -0
  16. package/docs/DESIGN_DECISIONS.md +37 -0
  17. package/docs/DEVELOPMENT.md +8 -1
  18. package/docs/MODULES.md +7 -1
  19. package/docs/PERFORMANCE.md +21 -0
  20. package/docs/README.md +3 -1
  21. package/docs/ROADMAP-1.9.12-2.0.md +18 -2
  22. package/package.json +1 -1
  23. package/plugins/antigravity/memorix/plugin.json +1 -1
  24. package/plugins/claude/memorix/.claude-plugin/plugin.json +1 -1
  25. package/plugins/codebuddy/memorix/.codebuddy-plugin/plugin.json +1 -1
  26. package/plugins/codex/memorix/.codex-plugin/plugin.json +1 -1
  27. package/plugins/copilot/memorix/plugin.json +1 -1
  28. package/plugins/gemini/memorix/gemini-extension.json +1 -1
  29. package/plugins/hermes/memorix/plugin.yaml +1 -1
  30. package/plugins/omp/memorix/package.json +1 -1
  31. package/plugins/openclaw/memorix/.codex-plugin/plugin.json +1 -1
  32. package/plugins/pi/memorix/package.json +1 -1
  33. package/server.json +2 -2
  34. package/src/cli/command-guide.ts +3 -1
  35. package/src/cli/commands/http-session-stream-watch.ts +138 -0
  36. package/src/cli/commands/memory.ts +3 -1
  37. package/src/cli/commands/project-detection-cache.ts +61 -0
  38. package/src/cli/commands/serve-http.ts +63 -13
  39. package/src/cli/index.ts +1 -1
  40. package/src/cli/tui/chat-service.ts +6 -9
  41. package/src/cli/tui/data.ts +2 -2
  42. package/src/codegraph/auto-context.ts +9 -2
  43. package/src/codegraph/derived-view.ts +63 -0
  44. package/src/compact/engine.ts +10 -33
  45. package/src/config/resolved-config.ts +11 -0
  46. package/src/config/retrieval-strategy.ts +22 -0
  47. package/src/config/toml-loader.ts +5 -0
  48. package/src/config/yaml-loader.ts +7 -0
  49. package/src/core/derived-view-registry.ts +33 -0
  50. package/src/core/derived-view.ts +15 -0
  51. package/src/core/maintenance-result.ts +33 -0
  52. package/src/core/retrieval-contracts.ts +57 -0
  53. package/src/core/retrieval-facade.ts +18 -0
  54. package/src/core/retrieval-policy.ts +44 -0
  55. package/src/core/runtime-context.ts +42 -0
  56. package/src/embedding/api-provider.ts +32 -10
  57. package/src/embedding/ollama-embed.ts +118 -0
  58. package/src/knowledge/workset.ts +0 -2
  59. package/src/memory/consolidation.ts +3 -2
  60. package/src/memory/feedback-model.ts +1 -4
  61. package/src/memory/observations.ts +192 -92
  62. package/src/runtime/control-plane-maintenance.ts +1 -0
  63. package/src/runtime/isolated-maintenance.ts +1 -0
  64. package/src/runtime/maintenance-jobs.ts +123 -32
  65. package/src/runtime/project-maintenance.ts +69 -1
  66. package/src/sdk.ts +3 -2
  67. package/src/search/fts-view.ts +53 -0
  68. package/src/search/orama-view.ts +40 -0
  69. package/src/search/retrieval-facade.ts +38 -0
  70. package/src/search/semantic-index.ts +51 -6
  71. package/src/search/semantic-view.ts +34 -0
  72. package/src/server.ts +19 -7
  73. package/src/store/obs-store.ts +15 -0
  74. package/src/store/orama-store.ts +158 -68
  75. package/src/store/sqlite-db.ts +22 -0
  76. package/src/store/sqlite-store.ts +27 -0
@@ -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, {
@@ -2176,6 +2226,10 @@ function getResolvedConfig(options = {}) {
2176
2226
  apiKey: first(process.env.MEMORIX_EMBEDDING_API_KEY, toml.embedding?.api_key, yaml.embedding?.apiKey, legacy.embeddingApi?.apiKey, openRouterEmbeddingApiKey, requestyEmbeddingApiKey),
2177
2227
  dimensions: firstNumber(parseNumber(process.env.MEMORIX_EMBEDDING_DIMENSIONS), toml.embedding?.dimensions, yaml.embedding?.dimensions, legacy.embeddingApi?.dimensions)
2178
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
+ },
2179
2233
  rerank: resolveRerankLane({
2180
2234
  toml,
2181
2235
  yaml,
@@ -2297,6 +2351,8 @@ function getEnvSourceNames() {
2297
2351
  "MEMORIX_EMBEDDING_BASE_URL",
2298
2352
  "MEMORIX_EMBEDDING_MODEL",
2299
2353
  "MEMORIX_EMBEDDING_DIMENSIONS",
2354
+ "MEMORIX_RETRIEVAL_CJK",
2355
+ "MEMORIX_RETRIEVAL_ASCII",
2300
2356
  "MEMORIX_RERANK_PROVIDER",
2301
2357
  "MEMORIX_RERANK_MODEL",
2302
2358
  "MEMORIX_RERANK_BASE_URL",
@@ -2405,6 +2461,7 @@ var init_resolved_config = __esm({
2405
2461
  init_toml_loader();
2406
2462
  init_yaml_loader();
2407
2463
  init_dotenv_loader();
2464
+ init_retrieval_strategy();
2408
2465
  }
2409
2466
  });
2410
2467
 
@@ -3275,6 +3332,7 @@ var sqlite_store_exports = {};
3275
3332
  __export(sqlite_store_exports, {
3276
3333
  SqliteBackend: () => SqliteBackend
3277
3334
  });
3335
+ import { randomUUID as randomUUID2 } from "crypto";
3278
3336
  import path6 from "path";
3279
3337
  import fs3 from "fs";
3280
3338
  function obsToRow(obs) {
@@ -3663,6 +3721,32 @@ var init_sqlite_store = __esm({
3663
3721
  }, "Observation atomic write");
3664
3722
  try {
3665
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
+ },
3666
3750
  loadAll: async () => this.rawLoadAll(),
3667
3751
  getById: async (id) => this.rawGetById(id),
3668
3752
  findByTopicKey: async (projectId, topicKey) => this.rawFindByTopicKey(projectId, topicKey),
@@ -3733,6 +3817,7 @@ __export(obs_store_exports, {
3733
3817
  DegradedBackend: () => DegradedBackend,
3734
3818
  createObservationStore: () => createObservationStore,
3735
3819
  getObservationStore: () => getObservationStore,
3820
+ getObservationStoreDataDir: () => getObservationStoreDataDir,
3736
3821
  initObservationStore: () => initObservationStore,
3737
3822
  resetObservationStore: () => resetObservationStore,
3738
3823
  setObservationStore: () => setObservationStore
@@ -3743,6 +3828,12 @@ function getObservationStore() {
3743
3828
  }
3744
3829
  return _store;
3745
3830
  }
3831
+ function getObservationStoreDataDir() {
3832
+ if (!_store || !_storeDataDir) {
3833
+ throw new Error("[memorix] ObservationStore data directory is not bound");
3834
+ }
3835
+ return _storeDataDir;
3836
+ }
3746
3837
  function setObservationStore(store) {
3747
3838
  _store = store;
3748
3839
  }
@@ -4337,6 +4428,96 @@ var init_transformers_provider = __esm({
4337
4428
  }
4338
4429
  });
4339
4430
 
4431
+ // src/embedding/ollama-embed.ts
4432
+ async function routeOllamaEmbedding(url, body, fetchImpl = fetch, probeOptions) {
4433
+ const parsed = parseUrl(url);
4434
+ if (!parsed) return { url, body, rewritten: false };
4435
+ const openAIRoute = parsed.pathname.endsWith("/v1/embeddings");
4436
+ const nativeRoute = parsed.pathname.endsWith("/api/embed");
4437
+ if (!openAIRoute && !nativeRoute) return { url, body, rewritten: false };
4438
+ if (!await originServesOllama(parsed.origin, fetchImpl, probeOptions)) return { url, body, rewritten: false };
4439
+ if (nativeRoute) return { url, body, rewritten: true };
4440
+ parsed.pathname = parsed.pathname.replace(/\/v1\/embeddings$/, "/api/embed");
4441
+ return { url: parsed.toString(), body: withEmbeddingKeepAlive(body), rewritten: true };
4442
+ }
4443
+ async function originServesOllama(origin, fetchImpl = fetch, probeOptions) {
4444
+ const cached = ollamaOrigins.get(origin);
4445
+ if (cached != null) return cached;
4446
+ if (probeOptions?.signal?.aborted) return false;
4447
+ try {
4448
+ const response = await fetchImpl(`${origin}/api/version`, {
4449
+ method: "GET",
4450
+ signal: buildProbeSignal(probeOptions)
4451
+ });
4452
+ if (!response.ok) {
4453
+ ollamaOrigins.set(origin, false);
4454
+ return false;
4455
+ }
4456
+ const detected = isOllamaVersionPayload(await response.json());
4457
+ ollamaOrigins.set(origin, detected);
4458
+ return detected;
4459
+ } catch (err) {
4460
+ if (isAbortError(err) || probeOptions?.signal?.aborted) return false;
4461
+ ollamaOrigins.set(origin, false);
4462
+ return false;
4463
+ }
4464
+ }
4465
+ function mapOllamaEmbeddingResponse(payload) {
4466
+ if (!payload || typeof payload !== "object") return payload;
4467
+ const record80 = payload;
4468
+ if (Array.isArray(record80.data) || !Array.isArray(record80.embeddings)) return payload;
4469
+ const embeddings = record80.embeddings.filter((item) => Array.isArray(item));
4470
+ return {
4471
+ ...record80,
4472
+ object: "list",
4473
+ data: embeddings.map((embedding, index) => ({
4474
+ object: "embedding",
4475
+ index,
4476
+ embedding
4477
+ }))
4478
+ };
4479
+ }
4480
+ function withEmbeddingKeepAlive(body) {
4481
+ if (body.keep_alive != null && body.keep_alive !== "") return body;
4482
+ return { ...body, keep_alive: OLLAMA_EMBED_KEEP_ALIVE };
4483
+ }
4484
+ function isOllamaVersionPayload(payload) {
4485
+ if (!payload || typeof payload !== "object") return false;
4486
+ const version = payload.version;
4487
+ return typeof version === "string" && /^\d+\.\d+\.\d+/.test(version);
4488
+ }
4489
+ function parseUrl(url) {
4490
+ try {
4491
+ return new URL(url);
4492
+ } catch {
4493
+ return null;
4494
+ }
4495
+ }
4496
+ function buildProbeSignal(probeOptions) {
4497
+ const timeoutMs = Math.max(
4498
+ 1,
4499
+ Math.min(
4500
+ typeof probeOptions?.probeTimeoutMs === "number" && Number.isFinite(probeOptions.probeTimeoutMs) ? Math.floor(probeOptions.probeTimeoutMs) : 1e3,
4501
+ 6e4
4502
+ )
4503
+ );
4504
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
4505
+ if (probeOptions?.signal) return AbortSignal.any([probeOptions.signal, timeoutSignal]);
4506
+ return timeoutSignal;
4507
+ }
4508
+ function isAbortError(err) {
4509
+ return err instanceof Error && err.name === "AbortError";
4510
+ }
4511
+ var OLLAMA_EMBED_KEEP_ALIVE, ollamaOrigins;
4512
+ var init_ollama_embed = __esm({
4513
+ "src/embedding/ollama-embed.ts"() {
4514
+ "use strict";
4515
+ init_esm_shims();
4516
+ OLLAMA_EMBED_KEEP_ALIVE = "5m";
4517
+ ollamaOrigins = /* @__PURE__ */ new Map();
4518
+ }
4519
+ });
4520
+
4340
4521
  // src/embedding/api-provider.ts
4341
4522
  var api_provider_exports = {};
4342
4523
  __export(api_provider_exports, {
@@ -4725,8 +4906,8 @@ async function loadCacheJsonl(filePath) {
4725
4906
  loaded = cache3.size;
4726
4907
  } catch {
4727
4908
  }
4728
- if (onDiskCount % 250 === 0) {
4729
- await new Promise((resolve2) => setImmediate(resolve2));
4909
+ if (onDiskCount % CACHE_LOAD_YIELD_EVERY === 0) {
4910
+ await new Promise((resolve2) => setTimeout(resolve2, 0));
4730
4911
  }
4731
4912
  }
4732
4913
  diskCacheEntryCount = onDiskCount;
@@ -5038,8 +5219,18 @@ function parseBatchLimit(error) {
5038
5219
  return null;
5039
5220
  }
5040
5221
  async function fetchWithRetry(url, apiKey, body, options = {}, attempt = 0, nativeGemini = false) {
5041
- const controller = new AbortController();
5042
5222
  const timeoutMs = typeof options.timeoutMs === "number" && Number.isFinite(options.timeoutMs) ? Math.max(100, Math.min(Math.floor(options.timeoutMs), 6e4)) : 1e4;
5223
+ let rewritten = false;
5224
+ if (!nativeGemini) {
5225
+ const routed = await routeOllamaEmbedding(url, body, fetch, {
5226
+ signal: options.signal,
5227
+ probeTimeoutMs: Math.min(1e3, timeoutMs)
5228
+ });
5229
+ url = routed.url;
5230
+ body = routed.body;
5231
+ rewritten = routed.rewritten;
5232
+ }
5233
+ const controller = new AbortController();
5043
5234
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
5044
5235
  const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;
5045
5236
  let response;
@@ -5055,14 +5246,21 @@ async function fetchWithRetry(url, apiKey, body, options = {}, attempt = 0, nati
5055
5246
  if (err instanceof Error && (err.name === "AbortError" || controller.signal.aborted || options.signal?.aborted)) {
5056
5247
  throw new Error(`Embedding API timeout after ${timeoutMs}ms: ${url}`);
5057
5248
  }
5249
+ if (options.retry !== false && attempt < MAX_RETRIES2) {
5250
+ const delay3 = BASE_DELAY_MS * Math.pow(2, attempt);
5251
+ console.error(`[memorix] Embedding transport failure, retry ${attempt + 1}/${MAX_RETRIES2} in ${delay3}ms`);
5252
+ await waitForRetry(delay3, options.signal);
5253
+ return fetchWithRetry(url, apiKey, body, options, attempt + 1, nativeGemini);
5254
+ }
5058
5255
  throw err;
5059
5256
  }
5060
5257
  try {
5061
5258
  if (response.ok) {
5062
- return await raceWithAbort(
5259
+ const payload = await raceWithAbort(
5063
5260
  response.json(),
5064
5261
  signal
5065
5262
  );
5263
+ return rewritten ? mapOllamaEmbeddingResponse(payload) : payload;
5066
5264
  }
5067
5265
  if (options.retry !== false && (response.status === 429 || response.status >= 500) && attempt < MAX_RETRIES2) {
5068
5266
  const delay3 = BASE_DELAY_MS * Math.pow(2, attempt);
@@ -5133,12 +5331,13 @@ async function waitForRetry(waitMs, signal) {
5133
5331
  abortSignal.addEventListener("abort", onAbort, { once: true });
5134
5332
  });
5135
5333
  }
5136
- 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;
5334
+ 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;
5137
5335
  var init_api_provider = __esm({
5138
5336
  "src/embedding/api-provider.ts"() {
5139
5337
  "use strict";
5140
5338
  init_esm_shims();
5141
5339
  init_provider2();
5340
+ init_ollama_embed();
5142
5341
  cache3 = /* @__PURE__ */ new Map();
5143
5342
  MAX_CACHE_ENTRIES = 2e5;
5144
5343
  MAX_CACHE_PAYLOAD_BYTES = 256 * 1024 * 1024;
@@ -5161,6 +5360,7 @@ var init_api_provider = __esm({
5161
5360
  DASHSCOPE_MAX_BATCH_SIZE = 10;
5162
5361
  MAX_RETRIES2 = 3;
5163
5362
  BASE_DELAY_MS = 500;
5363
+ CACHE_LOAD_YIELD_EVERY = 32;
5164
5364
  EmbeddingAPIError = class extends Error {
5165
5365
  status;
5166
5366
  constructor(status, detail) {
@@ -5212,7 +5412,7 @@ var init_api_provider = __esm({
5212
5412
  console.error(`[memorix] Dimension shortening: ${config.requestedDimensions}d requested`);
5213
5413
  }
5214
5414
  if (allowNetworkProbe) {
5215
- startDiskCacheLoad();
5415
+ setImmediate(startDiskCacheLoad);
5216
5416
  }
5217
5417
  return new _APIEmbeddingProvider(config, probeDimensions);
5218
5418
  }
@@ -5284,10 +5484,8 @@ var init_api_provider = __esm({
5284
5484
  return this.embedInput({ modality: "text", text: normalized }, { intent: "document", ...options });
5285
5485
  }
5286
5486
  const hash4 = textHash2(normalized, this.cacheKeyNamespace);
5287
- if (diskCacheLoaded) {
5288
- const cached = cache3.get(hash4);
5289
- if (cached) return cached;
5290
- }
5487
+ const cached = cache3.get(hash4);
5488
+ if (cached) return cached;
5291
5489
  const apiCall = async () => {
5292
5490
  const body = {
5293
5491
  model: this.config.model,
@@ -5312,8 +5510,8 @@ var init_api_provider = __esm({
5312
5510
  let embedding;
5313
5511
  if (!diskCacheLoaded && diskCacheLoadPromise) {
5314
5512
  const cacheRace = diskCacheLoadPromise.then(() => {
5315
- const cached = cache3.get(hash4);
5316
- if (cached) return cached;
5513
+ const cached2 = cache3.get(hash4);
5514
+ if (cached2) return cached2;
5317
5515
  return null;
5318
5516
  });
5319
5517
  const result = await Promise.race([
@@ -6422,6 +6620,9 @@ async function loadLanceDb() {
6422
6620
  return null;
6423
6621
  }
6424
6622
  }
6623
+ async function isSemanticIndexAvailable() {
6624
+ return await loadLanceDb() !== null;
6625
+ }
6425
6626
  function semanticIndexEnabled() {
6426
6627
  return process.env.MEMORIX_SEMANTIC_INDEX !== "off" && process.env.MEMORIX_SEMANTIC_INDEX !== "orama";
6427
6628
  }
@@ -6435,6 +6636,9 @@ async function openState(dataDir, profile) {
6435
6636
  const table = names.includes(name) ? await connection.openTable(name) : null;
6436
6637
  return { key: stateKey(dataDir, profile), dataDir, profile, connection, table };
6437
6638
  }
6639
+ function semanticVectorKey(projectId, observationId2) {
6640
+ return `${projectId}:${Math.trunc(observationId2)}`;
6641
+ }
6438
6642
  function toLanceRow(record80) {
6439
6643
  return {
6440
6644
  observation_id: record80.observationId,
@@ -6505,7 +6709,7 @@ async function mergeVectors(dataDir, profile, records) {
6505
6709
  const state = await getState(dataDir, profile, records);
6506
6710
  if (!state?.table) return;
6507
6711
  const rows = records.map(toLanceRow);
6508
- await state.table.mergeInsert("observation_id").whenMatchedUpdateAll().whenNotMatchedInsertAll().execute(rows);
6712
+ await state.table.mergeInsert(["project_id", "observation_id"]).whenMatchedUpdateAll().whenNotMatchedInsertAll().execute(rows);
6509
6713
  const key = stateKey(dataDir, profile);
6510
6714
  const mutationCount = (mutationCounts.get(key) ?? 0) + 1;
6511
6715
  if (mutationCount >= semanticOptimizeEvery()) {
@@ -6545,11 +6749,34 @@ function upsertSemanticVector(dataDir, profile, record80) {
6545
6749
  function upsertSemanticVectors(dataDir, profile, records) {
6546
6750
  return queueOperation(stateKey(dataDir, profile), () => mergeVectors(dataDir, profile, records));
6547
6751
  }
6548
- async function listSemanticVectorIds(dataDir, profile) {
6752
+ async function listSemanticVectorKeys(dataDir, profile) {
6549
6753
  const state = await getState(dataDir, profile);
6550
6754
  if (!state?.table) return null;
6551
- const rows = await state.table.query().select(["observation_id"]).toArray();
6552
- return new Set(rows.map((row) => Number(row.observation_id)).filter(Number.isSafeInteger));
6755
+ const rows = await state.table.query().select(["observation_id", "project_id"]).toArray();
6756
+ const keys = /* @__PURE__ */ new Set();
6757
+ for (const row of rows) {
6758
+ const observationId2 = Number(row.observation_id);
6759
+ const projectId = String(row.project_id ?? "");
6760
+ if (!Number.isSafeInteger(observationId2) || !projectId) continue;
6761
+ keys.add(semanticVectorKey(projectId, observationId2));
6762
+ }
6763
+ return keys;
6764
+ }
6765
+ async function getSemanticIndexStats(dataDir, profile) {
6766
+ const state = await getState(dataDir, profile);
6767
+ if (!state?.table) return null;
6768
+ return {
6769
+ rowCount: await state.table.countRows(),
6770
+ version: typeof state.table.version === "function" ? await state.table.version() : 0
6771
+ };
6772
+ }
6773
+ function optimizeSemanticIndex(dataDir, profile) {
6774
+ const key = stateKey(dataDir, profile);
6775
+ return queueOperation(key, async () => {
6776
+ const state = await getState(dataDir, profile);
6777
+ if (state) await optimizeState(state);
6778
+ mutationCounts.set(key, 0);
6779
+ });
6553
6780
  }
6554
6781
  function resolveIndexThreshold() {
6555
6782
  const raw = Number.parseInt(process.env.MEMORIX_SEMANTIC_INDEX_THRESHOLD ?? "", 10);
@@ -6602,6 +6829,20 @@ async function searchSemanticVectors(options) {
6602
6829
  distance: Number(row._distance ?? Number.POSITIVE_INFINITY)
6603
6830
  })).filter((row) => Number.isFinite(row.distance));
6604
6831
  }
6832
+ async function closeSemanticIndexProfile(dataDir, profile) {
6833
+ const key = stateKey(dataDir, profile);
6834
+ await flushPendingVectorBatch(key);
6835
+ await writeQueues.get(key);
6836
+ const state = await statePromises.get(key)?.catch(() => null);
6837
+ try {
6838
+ state?.connection?.close?.();
6839
+ } catch {
6840
+ }
6841
+ statePromises.delete(key);
6842
+ writeQueues.delete(key);
6843
+ indexBuilds.delete(key);
6844
+ mutationCounts.delete(key);
6845
+ }
6605
6846
  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;
6606
6847
  var init_semantic_index = __esm({
6607
6848
  "src/search/semantic-index.ts"() {
@@ -6624,6 +6865,59 @@ var init_semantic_index = __esm({
6624
6865
  }
6625
6866
  });
6626
6867
 
6868
+ // src/search/semantic-view.ts
6869
+ function createSemanticDerivedView(dataDir, profile) {
6870
+ return {
6871
+ async status() {
6872
+ if (!await isSemanticIndexAvailable()) return { state: "unavailable" };
6873
+ const stats = await getSemanticIndexStats(dataDir, profile);
6874
+ return stats ? { state: "ready", generation: stats.version, rowCount: stats.rowCount } : { state: "missing" };
6875
+ },
6876
+ async refresh(records) {
6877
+ if (records.length === 1) await upsertSemanticVector(dataDir, profile, records[0]);
6878
+ else await upsertSemanticVectors(dataDir, profile, records);
6879
+ },
6880
+ rebuild: () => ensureSemanticIndex(dataDir, profile),
6881
+ compact: () => optimizeSemanticIndex(dataDir, profile),
6882
+ close: () => closeSemanticIndexProfile(dataDir, profile)
6883
+ };
6884
+ }
6885
+ var init_semantic_view = __esm({
6886
+ "src/search/semantic-view.ts"() {
6887
+ "use strict";
6888
+ init_esm_shims();
6889
+ init_semantic_index();
6890
+ }
6891
+ });
6892
+
6893
+ // src/core/retrieval-contracts.ts
6894
+ function createRetrievalPlan(options) {
6895
+ const requestedLimit = Number.isFinite(options.limit) ? Math.floor(options.limit ?? 20) : 20;
6896
+ const requestedTokens = Number.isFinite(options.maxTokens) ? Math.floor(options.maxTokens ?? 0) : 0;
6897
+ return {
6898
+ query: options.query.trim(),
6899
+ quality: options.quality ?? "balanced",
6900
+ limit: Math.max(1, Math.min(1e4, requestedLimit)),
6901
+ ...options.projectId ? { projectId: options.projectId } : {},
6902
+ status: options.status ?? "active",
6903
+ ...options.source ? { source: options.source } : {},
6904
+ ...options.type ? { type: options.type } : {},
6905
+ ...options.since ? { since: options.since } : {},
6906
+ ...options.until ? { until: options.until } : {},
6907
+ maxTokens: Math.max(0, requestedTokens),
6908
+ trackAccess: options.trackAccess !== false,
6909
+ reader: options.reader,
6910
+ surfacedIds: [...options.surfacedIds ?? []],
6911
+ signal: options.signal
6912
+ };
6913
+ }
6914
+ var init_retrieval_contracts = __esm({
6915
+ "src/core/retrieval-contracts.ts"() {
6916
+ "use strict";
6917
+ init_esm_shims();
6918
+ }
6919
+ });
6920
+
6627
6921
  // src/memory/secret-filter.ts
6628
6922
  function applyRedaction(text2) {
6629
6923
  if (!text2) return text2;
@@ -6686,6 +6980,37 @@ var init_derived_view_receipt = __esm({
6686
6980
  }
6687
6981
  });
6688
6982
 
6983
+ // src/core/derived-view-registry.ts
6984
+ var DerivedViewRegistry;
6985
+ var init_derived_view_registry = __esm({
6986
+ "src/core/derived-view-registry.ts"() {
6987
+ "use strict";
6988
+ init_esm_shims();
6989
+ DerivedViewRegistry = class {
6990
+ readers = /* @__PURE__ */ new Map();
6991
+ register(name, reader) {
6992
+ const normalized = name.trim();
6993
+ if (!normalized) throw new Error("Derived view name must not be empty");
6994
+ this.readers.set(normalized, reader);
6995
+ return () => {
6996
+ if (this.readers.get(normalized) === reader) this.readers.delete(normalized);
6997
+ };
6998
+ }
6999
+ snapshot() {
7000
+ const result = {};
7001
+ for (const [name, reader] of this.readers) {
7002
+ try {
7003
+ result[name] = reader();
7004
+ } catch {
7005
+ result[name] = { state: "degraded", reason: "derived view reader failed" };
7006
+ }
7007
+ }
7008
+ return result;
7009
+ }
7010
+ };
7011
+ }
7012
+ });
7013
+
6689
7014
  // src/project/aliases.ts
6690
7015
  var aliases_exports = {};
6691
7016
  __export(aliases_exports, {
@@ -7284,6 +7609,7 @@ var orama_store_exports = {};
7284
7609
  __export(orama_store_exports, {
7285
7610
  _classifyQueryTier: () => classifyQueryTier,
7286
7611
  batchGenerateEmbeddings: () => batchGenerateEmbeddings,
7612
+ countIndexedDocuments: () => countIndexedDocuments,
7287
7613
  createSearchTokenizer: () => createSearchTokenizer,
7288
7614
  generateEmbedding: () => generateEmbedding,
7289
7615
  generateEmbeddingInput: () => generateEmbeddingInput,
@@ -7309,6 +7635,7 @@ __export(orama_store_exports, {
7309
7635
  resetDb: () => resetDb,
7310
7636
  resolveSearchFuzzyTolerance: () => resolveSearchFuzzyTolerance,
7311
7637
  searchObservations: () => searchObservations,
7638
+ searchObservationsDetailed: () => searchObservationsDetailed,
7312
7639
  updateObservationMetadata: () => updateObservationMetadata
7313
7640
  });
7314
7641
  import { components, create, insert as insert2, insertMultiple, search, remove as remove2, update, count, getByID } from "@orama/orama";
@@ -7335,15 +7662,17 @@ function getLastSearchDiagnostics(projectId) {
7335
7662
  return diagnostics ? { ...diagnostics } : void 0;
7336
7663
  }
7337
7664
  function getSearchDerivedViews() {
7338
- const views = {};
7665
+ return searchDerivedViewRegistry.snapshot();
7666
+ }
7667
+ function readFtsDerivedViewReceipt() {
7339
7668
  const store = getOptionalObservationStore();
7340
7669
  if (store) {
7341
7670
  try {
7342
7671
  const generation = store.getGeneration();
7343
7672
  if (store.hasLexicalIndex?.()) {
7344
- views.fts = { generation, freshness: "current", rebuildStatus: "idle" };
7673
+ return { generation, freshness: "current", rebuildStatus: "idle" };
7345
7674
  } else {
7346
- views.fts = {
7675
+ return {
7347
7676
  generation,
7348
7677
  freshness: "unknown",
7349
7678
  rebuildStatus: "unavailable",
@@ -7353,32 +7682,34 @@ function getSearchDerivedViews() {
7353
7682
  };
7354
7683
  }
7355
7684
  } catch (error) {
7356
- views.fts = {
7685
+ return {
7357
7686
  freshness: "unknown",
7358
7687
  rebuildStatus: "failed",
7359
7688
  failureReason: sanitizeDerivedViewFailureReason(error instanceof Error ? error.message : String(error))
7360
7689
  };
7361
7690
  }
7362
- } else {
7363
- views.fts = {
7364
- freshness: "unknown",
7365
- rebuildStatus: "unavailable",
7366
- failureReason: "observation store is not initialized"
7367
- };
7368
7691
  }
7369
- views.orama = db ? { generation: dbGeneration, freshness: "current", rebuildStatus: "idle" } : {
7692
+ return {
7693
+ freshness: "unknown",
7694
+ rebuildStatus: "unavailable",
7695
+ failureReason: "observation store is not initialized"
7696
+ };
7697
+ }
7698
+ function readOramaDerivedViewReceipt() {
7699
+ return db ? { generation: dbGeneration, freshness: "current", rebuildStatus: "idle" } : {
7370
7700
  generation: dbGeneration,
7371
7701
  freshness: "unknown",
7372
7702
  rebuildStatus: "unavailable",
7373
7703
  failureReason: "Orama index is not initialized"
7374
7704
  };
7705
+ }
7706
+ function readEmbeddingDerivedViewReceipt() {
7375
7707
  let embeddingHealth;
7376
7708
  try {
7377
7709
  embeddingHealth = getEmbeddingRuntimeHealth?.();
7378
7710
  } catch {
7379
7711
  }
7380
- views.embedding = embeddingHealthReceipt(embeddingHealth, embeddingEnabled);
7381
- return views;
7712
+ return embeddingHealthReceipt(embeddingHealth, embeddingEnabled);
7382
7713
  }
7383
7714
  function rememberSearchDiagnostics(key, value) {
7384
7715
  if (!lastSearchDiagnosticsByProject.has(key) && lastSearchDiagnosticsByProject.size >= MAX_SEARCH_MODE_KEYS) {
@@ -7497,6 +7828,48 @@ async function searchPersistentLexically(options, projectIds, limit2) {
7497
7828
  return null;
7498
7829
  }
7499
7830
  }
7831
+ async function searchLanceInVectorOrder(options, projectIds, limit2, queryVector, provider2) {
7832
+ try {
7833
+ const { getObservationDataDir: getObservationDataDir2 } = await Promise.resolve().then(() => (init_observations(), observations_exports));
7834
+ const dataDir = getObservationDataDir2();
7835
+ if (!dataDir) return null;
7836
+ const vectorHits = await searchSemanticVectors({
7837
+ dataDir,
7838
+ profile: createSemanticIndexProfile(provider2),
7839
+ vector: queryVector,
7840
+ projectId: projectIds ?? options.projectId,
7841
+ status: "all",
7842
+ limit: Math.min(1e4, Math.max(limit2, 1) * 4)
7843
+ });
7844
+ if (!vectorHits || vectorHits.length === 0) return null;
7845
+ const store = getObservationStore();
7846
+ const hits = [];
7847
+ const seen = /* @__PURE__ */ new Set();
7848
+ for (const hit of vectorHits) {
7849
+ if (projectIds ? !projectIds.includes(hit.projectId) : options.projectId && hit.projectId !== options.projectId) continue;
7850
+ const key = semanticVectorKey(hit.projectId, hit.observationId);
7851
+ if (seen.has(key)) continue;
7852
+ seen.add(key);
7853
+ const observation = await store.getById(hit.observationId);
7854
+ if (!observation || observation.projectId !== hit.projectId) continue;
7855
+ if (projectIds && !projectIds.includes(observation.projectId)) continue;
7856
+ if (options.status !== "all" && (observation.status ?? "active") !== (options.status ?? "active")) continue;
7857
+ if (options.type && observation.type !== options.type) continue;
7858
+ if (options.source && observation.source !== options.source) continue;
7859
+ const document2 = observationToSearchDocument(observation);
7860
+ hits.push({
7861
+ id: document2.id,
7862
+ score: 1 / (1 + hits.length),
7863
+ document: document2
7864
+ });
7865
+ if (hits.length >= limit2) break;
7866
+ }
7867
+ if (hits.length === 0) return null;
7868
+ return { count: hits.length, hits };
7869
+ } catch {
7870
+ return null;
7871
+ }
7872
+ }
7500
7873
  async function searchPersistentSemantically(options, projectIds, limit2, queryVector, provider2) {
7501
7874
  try {
7502
7875
  const { getObservationDataDir: getObservationDataDir2 } = await Promise.resolve().then(() => (init_observations(), observations_exports));
@@ -7524,14 +7897,15 @@ async function searchPersistentSemantically(options, projectIds, limit2, queryVe
7524
7897
  documents.set(makeEntryKey(hit.document.projectId, hit.document.observationId), hit.document);
7525
7898
  }
7526
7899
  const vectorObservations = await Promise.all(vectorHits.map(async (hit) => {
7900
+ if (projectIds ? !projectIds.includes(hit.projectId) : options.projectId && hit.projectId !== options.projectId) return null;
7527
7901
  const observation = await store.getById(hit.observationId);
7528
- if (!observation) return null;
7902
+ if (!observation || observation.projectId !== hit.projectId) return null;
7529
7903
  if (projectIds && !projectIds.includes(observation.projectId)) return null;
7530
7904
  if (options.status !== "all" && (observation.status ?? "active") !== (options.status ?? "active")) return null;
7531
7905
  if (options.type && observation.type !== options.type) return null;
7532
7906
  if (options.source && observation.source !== options.source) return null;
7533
7907
  addObservation(observation);
7534
- vectorDocumentKeys.set(hit.observationId, makeEntryKey(observation.projectId, observation.id));
7908
+ vectorDocumentKeys.set(semanticVectorKey(hit.projectId, hit.observationId), makeEntryKey(observation.projectId, observation.id));
7535
7909
  return observation;
7536
7910
  }));
7537
7911
  const RRF_K = 60;
@@ -7541,7 +7915,8 @@ async function searchPersistentSemantically(options, projectIds, limit2, queryVe
7541
7915
  scores.set(key, (scores.get(key) ?? 0) + 0.6 / (RRF_K + index + 1));
7542
7916
  }
7543
7917
  for (const [index, hit] of vectorHits.entries()) {
7544
- const key = vectorDocumentKeys.get(hit.observationId) ?? makeEntryKey(hit.projectId, hit.observationId);
7918
+ const key = vectorDocumentKeys.get(semanticVectorKey(hit.projectId, hit.observationId));
7919
+ if (!key) continue;
7545
7920
  if (!documents.has(key)) continue;
7546
7921
  scores.set(key, (scores.get(key) ?? 0) + 0.4 / (RRF_K + index + 1));
7547
7922
  }
@@ -7554,8 +7929,8 @@ async function searchPersistentSemantically(options, projectIds, limit2, queryVe
7554
7929
  return {
7555
7930
  count: vectorHits.length,
7556
7931
  hits: vectorHits.map((hit, index) => {
7557
- const key = vectorDocumentKeys.get(hit.observationId) ?? makeEntryKey(hit.projectId, hit.observationId);
7558
- const document2 = documents.get(key);
7932
+ const key = vectorDocumentKeys.get(semanticVectorKey(hit.projectId, hit.observationId));
7933
+ const document2 = key ? documents.get(key) : void 0;
7559
7934
  return document2 ? { id: document2.id, score: 0.4 / (RRF_K + index + 1), document: document2 } : null;
7560
7935
  }).filter((hit) => hit !== null).slice(0, limit2)
7561
7936
  };
@@ -7661,6 +8036,9 @@ async function getDb(options = {}) {
7661
8036
  }
7662
8037
  }
7663
8038
  }
8039
+ async function countIndexedDocuments(database) {
8040
+ return count(database ?? await getDb({ allowNetworkProbe: false }));
8041
+ }
7664
8042
  async function resetDb() {
7665
8043
  dbGeneration++;
7666
8044
  db = null;
@@ -7683,14 +8061,14 @@ function getActiveSemanticIndexProfile() {
7683
8061
  }
7684
8062
  async function getPersistentSemanticVectorIds(dataDir) {
7685
8063
  if (!indexEmbeddingProvider) return null;
7686
- return listSemanticVectorIds(dataDir, createSemanticIndexProfile(indexEmbeddingProvider));
8064
+ return listSemanticVectorKeys(dataDir, createSemanticIndexProfile(indexEmbeddingProvider));
7687
8065
  }
7688
8066
  async function queueSemanticVector(dataDir, record80) {
7689
8067
  const provider2 = indexEmbeddingProvider ?? await getEmbeddingProvider();
7690
8068
  const profile = provider2 ? createSemanticIndexProfile(provider2) : null;
7691
8069
  if (!profile) return;
7692
8070
  try {
7693
- await upsertSemanticVector(dataDir, profile, record80);
8071
+ await createSemanticDerivedView(dataDir, profile).refresh([record80]);
7694
8072
  } catch {
7695
8073
  }
7696
8074
  }
@@ -7752,7 +8130,7 @@ function isCompatibleCachedVector(vector) {
7752
8130
  async function attachCachedVectors(database, observations2) {
7753
8131
  const semanticDataDir = (await Promise.resolve().then(() => (init_observations(), observations_exports))).getObservationDataDir();
7754
8132
  const semanticProfile = getActiveSemanticIndexProfile();
7755
- const persistedSemanticIds = semanticDataDir && semanticProfile ? await listSemanticVectorIds(semanticDataDir, semanticProfile).catch(() => null) : null;
8133
+ const persistedSemanticIds = semanticDataDir && semanticProfile ? await listSemanticVectorKeys(semanticDataDir, semanticProfile).catch(() => null) : null;
7756
8134
  const batchSize = 200;
7757
8135
  for (let start = 0; start < observations2.length; start += batchSize) {
7758
8136
  const batch = observations2.slice(start, start + batchSize);
@@ -7763,7 +8141,7 @@ async function attachCachedVectors(database, observations2) {
7763
8141
  const vector = cachedVectors[index];
7764
8142
  if (!isCompatibleCachedVector(vector)) continue;
7765
8143
  const observation = batch[index];
7766
- if (semanticDataDir && semanticProfile && !persistedSemanticIds?.has(observation.id)) {
8144
+ if (semanticDataDir && semanticProfile && !persistedSemanticIds?.has(semanticVectorKey(observation.projectId, observation.id))) {
7767
8145
  semanticRecords.push({
7768
8146
  observationId: observation.id,
7769
8147
  projectId: observation.projectId,
@@ -7781,7 +8159,7 @@ async function attachCachedVectors(database, observations2) {
7781
8159
  }
7782
8160
  }
7783
8161
  if (semanticDataDir && semanticProfile && semanticRecords.length > 0) {
7784
- void upsertSemanticVectors(semanticDataDir, semanticProfile, semanticRecords).catch(() => {
8162
+ void createSemanticDerivedView(semanticDataDir, semanticProfile).refresh(semanticRecords).catch(() => {
7785
8163
  });
7786
8164
  }
7787
8165
  await new Promise((resolve2) => setImmediate(resolve2));
@@ -7892,7 +8270,9 @@ async function removeObservation(oramaId) {
7892
8270
  const database = await getDb();
7893
8271
  await remove2(database, oramaId);
7894
8272
  }
7895
- async function searchObservations(options) {
8273
+ async function searchObservationsDetailed(options) {
8274
+ const retrievalPlan = createRetrievalPlan(options);
8275
+ options = { ...options, ...retrievalPlan };
7896
8276
  const searchStartedAt = Date.now();
7897
8277
  const perf = !!process.env.MEMORIX_PERF;
7898
8278
  const t0 = perf ? performance.now() : 0;
@@ -7906,10 +8286,12 @@ async function searchObservations(options) {
7906
8286
  const modeKey = options.projectId ?? SEARCH_MODE_DEFAULT_KEY;
7907
8287
  const quality = options.quality ?? "balanced";
7908
8288
  const database = await getDb();
7909
- rememberSearchMode(
7910
- modeKey,
7911
- quality === "fast" ? "fulltext (fast profile)" : embeddingEnabled ? "hybrid" : "fulltext"
7912
- );
8289
+ let requestMode = quality === "fast" ? "fulltext (fast profile)" : embeddingEnabled ? "hybrid" : "fulltext";
8290
+ const setMode = (mode) => {
8291
+ requestMode = mode;
8292
+ rememberSearchMode(modeKey, mode);
8293
+ };
8294
+ setMode(requestMode);
7913
8295
  let projectIds = null;
7914
8296
  if (options.projectId) {
7915
8297
  try {
@@ -7930,7 +8312,7 @@ async function searchObservations(options) {
7930
8312
  filters["source"] = options.source;
7931
8313
  }
7932
8314
  const hasQuery = options.query && options.query.trim().length > 0;
7933
- const originalQuery = options.query;
8315
+ const originalQuery = retrievalPlan.query;
7934
8316
  const tier = quality === "fast" ? "fast" : hasQuery ? classifyQueryTier(originalQuery) : "fast";
7935
8317
  mark(`tier=${tier}`);
7936
8318
  if (quality === "thorough" && hasQuery) {
@@ -7984,10 +8366,7 @@ async function searchObservations(options) {
7984
8366
  embeddingUnavailable = true;
7985
8367
  fallbackUsed = true;
7986
8368
  fallbackReason = "embedding dimension mismatch; lexical search used";
7987
- rememberSearchMode(
7988
- modeKey,
7989
- `fulltext (embedding dimension mismatch: provider ${provider2.dimensions}d vs index ${activeVectorDimensions}d)`
7990
- );
8369
+ setMode(`fulltext (embedding dimension mismatch: provider ${provider2.dimensions}d vs index ${activeVectorDimensions}d)`);
7991
8370
  console.error(
7992
8371
  `[memorix] Embedding provider dimension mismatch (${provider2.dimensions}d provider vs ${activeVectorDimensions}d index); using fulltext search`
7993
8372
  );
@@ -8009,7 +8388,7 @@ async function searchObservations(options) {
8009
8388
  mark("embedding");
8010
8389
  const cjkRatio = (originalQuery.match(/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g) || []).length / originalQuery.length;
8011
8390
  const isCJKHeavy = cjkRatio > 0.3;
8012
- rememberSearchMode(modeKey, "hybrid");
8391
+ setMode("hybrid");
8013
8392
  searchParams = {
8014
8393
  ...searchParams,
8015
8394
  mode: "hybrid",
@@ -8032,32 +8411,41 @@ async function searchObservations(options) {
8032
8411
  embeddingUnavailable = true;
8033
8412
  fallbackUsed = true;
8034
8413
  fallbackReason = "embedding failed or timed out; lexical search used";
8035
- rememberSearchMode(modeKey, "fulltext (embedding unavailable)");
8414
+ setMode("fulltext (embedding unavailable)");
8036
8415
  console.error("[memorix] Embedding failed or timed out, falling back to fulltext search");
8037
8416
  }
8038
8417
  }
8039
8418
  mark("preSearch");
8040
8419
  let results;
8420
+ const retrieval = getResolvedConfig().retrieval;
8421
+ const wantLanceOrder = (isCjkHeavyQuery(originalQuery ?? "") ? retrieval.cjk : retrieval.ascii) === "vector";
8422
+ let lanceOrderUsed = false;
8423
+ let persistent = null;
8424
+ if (wantLanceOrder && queryVector && embeddingProviderForSearch) {
8425
+ persistent = await searchLanceInVectorOrder(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch);
8426
+ if (persistent) lanceOrderUsed = true;
8427
+ else {
8428
+ fallbackUsed = true;
8429
+ fallbackReason = fallbackReason ?? "lance vector index empty; hybrid search used";
8430
+ }
8431
+ }
8041
8432
  const persistentCorpusEligible = await shouldUsePersistentSearch(projectIds, options.projectId);
8042
8433
  const canUsePersistentLexical = persistentCorpusEligible && Boolean(hasQuery) && !queryVector && (quality === "fast" || tier === "fast" || !embeddingEnabled || embeddingUnavailable);
8043
- let persistent = persistentCorpusEligible && queryVector && embeddingProviderForSearch ? await searchPersistentSemantically(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch) : canUsePersistentLexical ? await searchPersistentLexically(options, projectIds, requestLimit) : null;
8434
+ if (!persistent) persistent = persistentCorpusEligible && queryVector && embeddingProviderForSearch ? await searchPersistentSemantically(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch) : canUsePersistentLexical ? await searchPersistentLexically(options, projectIds, requestLimit) : null;
8044
8435
  const durableStore = getOptionalObservationStore();
8045
8436
  if (!persistent && queryVector && durableStore?.hasLexicalIndex?.() && count(database) === 0) {
8046
8437
  persistent = await searchPersistentLexically(options, projectIds, requestLimit);
8047
8438
  }
8048
8439
  if (persistent) {
8049
8440
  results = persistent;
8050
- rememberSearchMode(
8051
- modeKey,
8052
- queryVector ? "hybrid" : quality === "fast" ? "fulltext (fast profile)" : "fulltext"
8053
- );
8441
+ setMode(lanceOrderUsed ? "vector" : queryVector ? "hybrid" : quality === "fast" ? "fulltext (fast profile)" : "fulltext");
8054
8442
  mark(queryVector ? "persistentHybridSearch" : "sqliteFtsSearch");
8055
8443
  } else {
8056
8444
  try {
8057
8445
  results = await search(database, searchParams);
8058
8446
  } catch (error) {
8059
8447
  if (queryVector && isVectorDimensionMismatchError(error)) {
8060
- rememberSearchMode(modeKey, "fulltext (embedding dimension mismatch)");
8448
+ setMode("fulltext (embedding dimension mismatch)");
8061
8449
  console.error("[memorix] Vector search dimension mismatch detected, retrying without embeddings");
8062
8450
  results = await search(database, stripVectorSearchParams(searchParams));
8063
8451
  } else {
@@ -8080,7 +8468,7 @@ async function searchObservations(options) {
8080
8468
  },
8081
8469
  similarity: 0.25
8082
8470
  };
8083
- rememberSearchMode(modeKey, "vector-only (hybrid empty fallback)");
8471
+ setMode("vector-only (hybrid empty fallback)");
8084
8472
  fallbackUsed = true;
8085
8473
  fallbackReason = "hybrid search returned no results; vector-only fallback used";
8086
8474
  results = await search(database, vectorOnlyParams);
@@ -8325,7 +8713,7 @@ async function searchObservations(options) {
8325
8713
  const rerankedTop = neural.map((row) => candidateMap.get(row.id)).filter((entry) => entry != null);
8326
8714
  if (rerankedTop.length > 0) {
8327
8715
  intermediate = [...rerankedTop, ...intermediate.slice(RERANK_TOP_K)];
8328
- rememberSearchMode(modeKey, (lastSearchModeByProject.get(modeKey) ?? "fulltext") + " + neural rerank");
8716
+ setMode(requestMode + " + neural rerank");
8329
8717
  mark("rerank(usedNeural=true)");
8330
8718
  }
8331
8719
  }
@@ -8342,7 +8730,7 @@ async function searchObservations(options) {
8342
8730
  );
8343
8731
  mark(`rerank(usedLLM=${usedLLM})`);
8344
8732
  if (usedLLM) {
8345
- rememberSearchMode(modeKey, (lastSearchModeByProject.get(modeKey) ?? "fulltext") + " + LLM rerank");
8733
+ setMode(requestMode + " + LLM rerank");
8346
8734
  const rerankedTop = reranked.map((row) => candidateMap.get(row.id)).filter((entry) => entry != null);
8347
8735
  if (rerankedTop.length > 0) {
8348
8736
  intermediate = [...rerankedTop, ...intermediate.slice(RERANK_TOP_K)];
@@ -8405,9 +8793,9 @@ async function searchObservations(options) {
8405
8793
  if (options.maxTokens && options.maxTokens > 0) {
8406
8794
  entries = applyTokenBudget(entries, options.maxTokens);
8407
8795
  }
8408
- rememberSearchDiagnostics(modeKey, {
8796
+ const diagnostics = {
8409
8797
  version: "1",
8410
- mode: getLastSearchMode(options.projectId),
8798
+ mode: requestMode,
8411
8799
  rawCandidateCount: results.hits.length,
8412
8800
  candidateCount,
8413
8801
  selectedCount: entries.length,
@@ -8416,14 +8804,25 @@ async function searchObservations(options) {
8416
8804
  fallbackUsed,
8417
8805
  ...fallbackReason ? { fallbackReason } : {},
8418
8806
  elapsedMs: Math.max(0, Date.now() - searchStartedAt)
8419
- });
8420
- if (options.trackAccess !== false) {
8421
- const returnedKeys = new Set(entries.map((entry) => makeEntryKey(entry.projectId, entry.id)));
8807
+ };
8808
+ rememberSearchDiagnostics(modeKey, diagnostics);
8809
+ const recordAccess = (selected) => {
8810
+ if (options.trackAccess === false || selected.length === 0) return;
8811
+ const returnedKeys = new Set(selected.map((entry) => makeEntryKey(entry.projectId, entry.id)));
8422
8812
  const hitDocs = results.hits.map((hit) => ({ id: hit.id, doc: hit.document })).filter(({ doc }) => returnedKeys.has(makeEntryKey(doc.projectId, doc.observationId)));
8423
8813
  recordAccessBatch(hitDocs).catch(() => {
8424
8814
  });
8815
+ };
8816
+ const derivedViews = getSearchDerivedViews();
8817
+ if (fallbackUsed && fallbackReason) {
8818
+ derivedViews.embedding = { freshness: "stale", rebuildStatus: "failed", failureReason: fallbackReason };
8425
8819
  }
8426
- return entries;
8820
+ return { entries, diagnostics, derivedViews, recordAccess };
8821
+ }
8822
+ async function searchObservations(options) {
8823
+ const result = await searchObservationsDetailed(options);
8824
+ result.recordAccess?.(result.entries);
8825
+ return result.entries;
8427
8826
  }
8428
8827
  async function getObservationsByIds(ids, projectId) {
8429
8828
  const database = await getDb();
@@ -8532,7 +8931,7 @@ function formatTime(isoDate) {
8532
8931
  return isoDate;
8533
8932
  }
8534
8933
  }
8535
- var db, dbInitPromise, dbGeneration, embeddingEnabled, embeddingDimensions, indexEmbeddingProvider, deferredCachedVectorHydration, NON_CJK_HYBRID_SIMILARITY, CJK_RUN, lastSearchModeByProject, lastSearchDiagnosticsByProject, SEARCH_MODE_DEFAULT_KEY, MAX_SEARCH_MODE_KEYS, COMMAND_LOG_TITLE, COMMAND_STYLE_TITLE, COMMAND_LIKE_QUERY2, COMMAND_INTENT_QUERY, NATURAL_LANGUAGE_MARKERS;
8934
+ var db, dbInitPromise, dbGeneration, embeddingEnabled, embeddingDimensions, indexEmbeddingProvider, deferredCachedVectorHydration, NON_CJK_HYBRID_SIMILARITY, CJK_RUN, lastSearchModeByProject, lastSearchDiagnosticsByProject, searchDerivedViewRegistry, SEARCH_MODE_DEFAULT_KEY, MAX_SEARCH_MODE_KEYS, COMMAND_LOG_TITLE, COMMAND_STYLE_TITLE, COMMAND_LIKE_QUERY2, COMMAND_INTENT_QUERY, NATURAL_LANGUAGE_MARKERS;
8536
8935
  var init_orama_store = __esm({
8537
8936
  "src/store/orama-store.ts"() {
8538
8937
  "use strict";
@@ -8548,8 +8947,13 @@ var init_orama_store = __esm({
8548
8947
  init_policy();
8549
8948
  init_timeout();
8550
8949
  init_obs_store();
8950
+ init_resolved_config();
8951
+ init_retrieval_strategy();
8952
+ init_semantic_view();
8953
+ init_retrieval_contracts();
8551
8954
  init_semantic_index();
8552
8955
  init_derived_view_receipt();
8956
+ init_derived_view_registry();
8553
8957
  db = null;
8554
8958
  dbInitPromise = null;
8555
8959
  dbGeneration = 0;
@@ -8561,8 +8965,12 @@ var init_orama_store = __esm({
8561
8965
  CJK_RUN = /[\u3400-\u4dbf\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]+/gu;
8562
8966
  lastSearchModeByProject = /* @__PURE__ */ new Map();
8563
8967
  lastSearchDiagnosticsByProject = /* @__PURE__ */ new Map();
8968
+ searchDerivedViewRegistry = new DerivedViewRegistry();
8564
8969
  SEARCH_MODE_DEFAULT_KEY = "__global__";
8565
8970
  MAX_SEARCH_MODE_KEYS = 4096;
8971
+ searchDerivedViewRegistry.register("fts", readFtsDerivedViewReceipt);
8972
+ searchDerivedViewRegistry.register("orama", readOramaDerivedViewReceipt);
8973
+ searchDerivedViewRegistry.register("embedding", readEmbeddingDerivedViewReceipt);
8566
8974
  COMMAND_LOG_TITLE = /^(Ran:|Command:|Executed:)\s/i;
8567
8975
  COMMAND_STYLE_TITLE = /(\bfindstr\b|\bSelect-String\b|\bGet-Content\b|\bnpx\s+vitest\b|\bnpx\s+tsc\b|\b2>&1\b)/i;
8568
8976
  COMMAND_LIKE_QUERY2 = /\b(git|npm|npx|pnpm|yarn|node|bash|powershell|curl|memorix)\b/i;
@@ -8674,6 +9082,24 @@ var init_entity_extractor = __esm({
8674
9082
  }
8675
9083
  });
8676
9084
 
9085
+ // src/core/maintenance-result.ts
9086
+ function assertMaintenanceProgress(progress) {
9087
+ if (!progress) return;
9088
+ const counts = [progress.attempted, progress.succeeded, progress.failed, progress.remaining];
9089
+ if (counts.some((count2) => !Number.isSafeInteger(count2) || count2 < 0)) {
9090
+ throw new Error("maintenance progress must contain non-negative safe integers");
9091
+ }
9092
+ if (progress.succeeded + progress.failed > progress.attempted) {
9093
+ throw new Error("maintenance progress outcomes exceed attempted work");
9094
+ }
9095
+ }
9096
+ var init_maintenance_result = __esm({
9097
+ "src/core/maintenance-result.ts"() {
9098
+ "use strict";
9099
+ init_esm_shims();
9100
+ }
9101
+ });
9102
+
8677
9103
  // src/runtime/maintenance-jobs.ts
8678
9104
  var maintenance_jobs_exports = {};
8679
9105
  __export(maintenance_jobs_exports, {
@@ -8683,7 +9109,7 @@ __export(maintenance_jobs_exports, {
8683
9109
  MaintenanceJobWorker: () => MaintenanceJobWorker,
8684
9110
  getMaintenanceRetryDelayMs: () => getMaintenanceRetryDelayMs
8685
9111
  });
8686
- import { randomUUID as randomUUID2 } from "crypto";
9112
+ import { randomUUID as randomUUID3 } from "crypto";
8687
9113
  function parsePayload(raw) {
8688
9114
  if (typeof raw !== "string" || !raw) return {};
8689
9115
  try {
@@ -8707,6 +9133,12 @@ function rowToJob(row) {
8707
9133
  ...row.lease_owner ? { leaseOwner: row.lease_owner } : {},
8708
9134
  ...row.lease_expires_at != null ? { leaseExpiresAt: Number(row.lease_expires_at) } : {},
8709
9135
  ...row.last_error ? { lastError: row.last_error } : {},
9136
+ ...Number(row.progress_recorded ?? 0) === 1 ? { progress: {
9137
+ attempted: Number(row.attempted ?? 0),
9138
+ succeeded: Number(row.succeeded ?? 0),
9139
+ failed: Number(row.failed ?? 0),
9140
+ remaining: Number(row.remaining ?? 0)
9141
+ } } : {},
8710
9142
  createdAt: Number(row.created_at),
8711
9143
  updatedAt: Number(row.updated_at),
8712
9144
  ...row.completed_at != null ? { completedAt: Number(row.completed_at) } : {}
@@ -8732,6 +9164,7 @@ var init_maintenance_jobs = __esm({
8732
9164
  "src/runtime/maintenance-jobs.ts"() {
8733
9165
  "use strict";
8734
9166
  init_esm_shims();
9167
+ init_maintenance_result();
8735
9168
  init_sqlite_db();
8736
9169
  init_secret_filter();
8737
9170
  MAINTENANCE_JOB_KINDS = [
@@ -8742,6 +9175,7 @@ var init_maintenance_jobs = __esm({
8742
9175
  "consolidation",
8743
9176
  "codegraph-refresh",
8744
9177
  "observation-qualify",
9178
+ "observation-project",
8745
9179
  "claim-derive",
8746
9180
  "claim-requalification",
8747
9181
  "knowledge-compile",
@@ -8780,6 +9214,16 @@ var init_maintenance_jobs = __esm({
8780
9214
  this.commit();
8781
9215
  return rowToJob(existing);
8782
9216
  }
9217
+ if (existing.status === "running") {
9218
+ this.db.prepare(`
9219
+ UPDATE maintenance_jobs
9220
+ SET rerun_requested = 1, payload_json = ?, updated_at = ?
9221
+ WHERE id = ?
9222
+ `).run(payloadJson, now3, existing.id);
9223
+ const updated2 = this.getRow(existing.id);
9224
+ this.commit();
9225
+ return rowToJob(updated2);
9226
+ }
8783
9227
  const nextRunAfter = Math.min(Number(existing.run_after), runAfter);
8784
9228
  this.db.prepare(`
8785
9229
  UPDATE maintenance_jobs
@@ -8810,7 +9254,7 @@ var init_maintenance_jobs = __esm({
8810
9254
  return rowToJob(revived);
8811
9255
  }
8812
9256
  }
8813
- const id = randomUUID2();
9257
+ const id = randomUUID3();
8814
9258
  this.db.prepare(`
8815
9259
  INSERT INTO maintenance_jobs (
8816
9260
  id, project_id, kind, dedupe_key, payload_json, status, attempts,
@@ -8907,8 +9351,10 @@ var init_maintenance_jobs = __esm({
8907
9351
  this.db.prepare(`
8908
9352
  UPDATE maintenance_jobs
8909
9353
  SET
8910
- status = CASE WHEN attempts >= max_attempts THEN 'failed' ELSE 'retry' END,
8911
- run_after = CASE WHEN attempts >= max_attempts THEN run_after ELSE ? END,
9354
+ status = CASE WHEN attempts >= max_attempts AND rerun_requested = 0 THEN 'failed' ELSE 'retry' END,
9355
+ run_after = CASE WHEN attempts >= max_attempts AND rerun_requested = 0 THEN run_after ELSE ? END,
9356
+ attempts = CASE WHEN rerun_requested = 1 AND attempts >= max_attempts THEN 0 ELSE attempts END,
9357
+ rerun_requested = 0,
8912
9358
  lease_owner = NULL,
8913
9359
  lease_expires_at = NULL,
8914
9360
  last_error = COALESCE(last_error, 'worker lease expired'),
@@ -8971,14 +9417,55 @@ var init_maintenance_jobs = __esm({
8971
9417
  `).run(expiresAt, now3, id, workerId);
8972
9418
  return Number(result.changes) > 0;
8973
9419
  }
8974
- complete(id, workerId, now3 = Date.now()) {
8975
- this.db.prepare(`
8976
- UPDATE maintenance_jobs
8977
- SET status = 'completed', lease_owner = NULL, lease_expires_at = NULL,
8978
- completed_at = ?, updated_at = ?
8979
- WHERE id = ? AND status = 'running' AND lease_owner = ?
8980
- `).run(now3, now3, id, workerId);
8981
- return this.get(id);
9420
+ complete(id, workerId, now3 = Date.now(), progress) {
9421
+ assertMaintenanceProgress(progress);
9422
+ this.begin();
9423
+ try {
9424
+ const current = this.db.prepare(`
9425
+ SELECT rerun_requested FROM maintenance_jobs
9426
+ WHERE id = ? AND status = 'running' AND lease_owner = ?
9427
+ `).get(id, workerId);
9428
+ if (!current) {
9429
+ this.commit();
9430
+ return void 0;
9431
+ }
9432
+ if (Number(current.rerun_requested) === 1) {
9433
+ this.db.prepare(`
9434
+ UPDATE maintenance_jobs
9435
+ SET status = 'pending', attempts = 0, run_after = ?,
9436
+ rerun_requested = 0, lease_owner = NULL, lease_expires_at = NULL,
9437
+ attempted = 0, succeeded = 0, failed = 0, remaining = 0,
9438
+ progress_recorded = 0, last_error = NULL, completed_at = NULL,
9439
+ updated_at = ?
9440
+ WHERE id = ?
9441
+ `).run(now3, now3, id);
9442
+ } else {
9443
+ this.db.prepare(`
9444
+ UPDATE maintenance_jobs
9445
+ SET status = 'completed', lease_owner = NULL, lease_expires_at = NULL,
9446
+ attempted = COALESCE(?, attempted), succeeded = COALESCE(?, succeeded),
9447
+ failed = COALESCE(?, failed), remaining = COALESCE(?, remaining),
9448
+ progress_recorded = CASE WHEN ? THEN 1 ELSE progress_recorded END,
9449
+ completed_at = ?, updated_at = ?
9450
+ WHERE id = ?
9451
+ `).run(
9452
+ progress?.attempted ?? null,
9453
+ progress?.succeeded ?? null,
9454
+ progress?.failed ?? null,
9455
+ progress?.remaining ?? null,
9456
+ progress ? 1 : 0,
9457
+ now3,
9458
+ now3,
9459
+ id
9460
+ );
9461
+ }
9462
+ const updated = this.get(id);
9463
+ this.commit();
9464
+ return updated;
9465
+ } catch (error) {
9466
+ this.rollback();
9467
+ throw error;
9468
+ }
8982
9469
  }
8983
9470
  reschedule(id, workerId, options) {
8984
9471
  const now3 = options.now ?? Date.now();
@@ -8987,22 +9474,37 @@ var init_maintenance_jobs = __esm({
8987
9474
  const status = options.status === "retry" ? "retry" : "pending";
8988
9475
  const hasLastError = options.lastError !== void 0;
8989
9476
  const lastError = hasLastError ? errorText(options.lastError) : null;
9477
+ const progress = options.progress;
9478
+ assertMaintenanceProgress(progress);
8990
9479
  this.db.prepare(`
8991
9480
  UPDATE maintenance_jobs
8992
- SET status = ?, run_after = ?, attempts = CASE WHEN ? THEN 0 ELSE attempts END,
8993
- payload_json = COALESCE(?, payload_json),
9481
+ SET status = ?,
9482
+ run_after = CASE WHEN rerun_requested = 1 AND ? = 0 THEN ? ELSE ? END,
9483
+ attempts = CASE WHEN rerun_requested = 1 AND ? = 0 THEN 0 WHEN ? THEN 0 ELSE attempts END,
9484
+ payload_json = CASE WHEN rerun_requested = 1 THEN payload_json ELSE COALESCE(?, payload_json) END,
9485
+ attempted = COALESCE(?, attempted), succeeded = COALESCE(?, succeeded),
9486
+ failed = COALESCE(?, failed), remaining = COALESCE(?, remaining),
9487
+ progress_recorded = CASE WHEN ? THEN 1 ELSE progress_recorded END,
8994
9488
  last_error = CASE
8995
9489
  WHEN ? THEN NULL
8996
9490
  WHEN ? THEN ?
8997
9491
  ELSE last_error
8998
9492
  END,
8999
- lease_owner = NULL, lease_expires_at = NULL, updated_at = ?
9493
+ rerun_requested = 0, lease_owner = NULL, lease_expires_at = NULL, updated_at = ?
9000
9494
  WHERE id = ? AND status = 'running' AND lease_owner = ?
9001
9495
  `).run(
9002
9496
  status,
9497
+ status === "retry" ? 1 : 0,
9498
+ now3,
9003
9499
  now3 + delayMs,
9500
+ status === "retry" ? 1 : 0,
9004
9501
  options.resetAttempts ? 1 : 0,
9005
9502
  payloadJson,
9503
+ progress?.attempted ?? null,
9504
+ progress?.succeeded ?? null,
9505
+ progress?.failed ?? null,
9506
+ progress?.remaining ?? null,
9507
+ progress ? 1 : 0,
9006
9508
  options.clearLastError ? 1 : 0,
9007
9509
  hasLastError ? 1 : 0,
9008
9510
  lastError,
@@ -9020,6 +9522,15 @@ var init_maintenance_jobs = __esm({
9020
9522
  `).run(now3, now3, projectId, dedupeKey);
9021
9523
  return Number(result.changes ?? 0);
9022
9524
  }
9525
+ /** A successful foreground projection can acknowledge its pending outbox row. */
9526
+ acknowledgePending(projectId, kind, dedupeKey, now3 = Date.now()) {
9527
+ const result = this.db.prepare(`
9528
+ UPDATE maintenance_jobs
9529
+ SET status = 'completed', completed_at = ?, updated_at = ?
9530
+ WHERE project_id = ? AND kind = ? AND dedupe_key = ? AND status = 'pending'
9531
+ `).run(now3, now3, projectId, kind, dedupeKey);
9532
+ return Number(result.changes ?? 0);
9533
+ }
9023
9534
  fail(id, workerId, error, now3 = Date.now()) {
9024
9535
  this.begin();
9025
9536
  try {
@@ -9032,15 +9543,18 @@ var init_maintenance_jobs = __esm({
9032
9543
  return void 0;
9033
9544
  }
9034
9545
  const attempts = Number(current.attempts);
9035
- const exhausted = attempts >= Number(current.max_attempts);
9546
+ const rerunRequested = Number(current.rerun_requested) === 1;
9547
+ const exhausted = attempts >= Number(current.max_attempts) && !rerunRequested;
9036
9548
  const status = exhausted ? "failed" : "retry";
9037
9549
  const runAfter = exhausted ? Number(current.run_after) : now3 + getMaintenanceRetryDelayMs(attempts);
9550
+ const nextAttempts = rerunRequested && attempts >= Number(current.max_attempts) ? 0 : attempts;
9038
9551
  this.db.prepare(`
9039
9552
  UPDATE maintenance_jobs
9040
- SET status = ?, run_after = ?, lease_owner = NULL, lease_expires_at = NULL,
9553
+ SET status = ?, run_after = ?, attempts = ?, rerun_requested = 0,
9554
+ lease_owner = NULL, lease_expires_at = NULL,
9041
9555
  last_error = ?, updated_at = ?
9042
9556
  WHERE id = ?
9043
- `).run(status, runAfter, errorText(error), now3, id);
9557
+ `).run(status, runAfter, nextAttempts, errorText(error), now3, id);
9044
9558
  const updated = this.getRow(id);
9045
9559
  this.commit();
9046
9560
  return rowToJob(updated);
@@ -9069,7 +9583,7 @@ var init_maintenance_jobs = __esm({
9069
9583
  constructor(store, handler, options = {}) {
9070
9584
  this.store = store;
9071
9585
  this.handler = handler;
9072
- this.workerId = options.workerId ?? `memorix-${process.pid}-${randomUUID2().slice(0, 8)}`;
9586
+ this.workerId = options.workerId ?? `memorix-${process.pid}-${randomUUID3().slice(0, 8)}`;
9073
9587
  this.leaseMs = clampPositiveInteger(options.leaseMs, DEFAULT_LEASE_MS);
9074
9588
  this.pollIntervalMs = clampPositiveInteger(options.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS);
9075
9589
  this.projectId = options.projectId;
@@ -9118,12 +9632,16 @@ var init_maintenance_jobs = __esm({
9118
9632
  status: result.status,
9119
9633
  lastError: result.lastError,
9120
9634
  clearLastError: result.clearLastError,
9635
+ progress: result.progress,
9121
9636
  now: now3
9122
9637
  });
9123
9638
  return { state: "rescheduled", job: updated2 };
9124
9639
  }
9125
- const updated = this.store.complete(job.id, this.workerId, now3);
9126
- return { state: "completed", job: updated };
9640
+ if (result?.progress && result.progress.remaining > 0) {
9641
+ throw new Error("maintenance job reported completion with remaining work");
9642
+ }
9643
+ const updated = this.store.complete(job.id, this.workerId, now3, result?.progress);
9644
+ return { state: updated?.status === "pending" ? "rescheduled" : "completed", job: updated };
9127
9645
  } catch (error) {
9128
9646
  const updated = this.store.fail(job.id, this.workerId, error, now3);
9129
9647
  return { state: "failed", job: updated };
@@ -9221,7 +9739,12 @@ var init_lifecycle = __esm({
9221
9739
  });
9222
9740
 
9223
9741
  // src/store/evidence-store.ts
9224
- import { createHash as createHash5, randomUUID as randomUUID3 } from "crypto";
9742
+ var evidence_store_exports = {};
9743
+ __export(evidence_store_exports, {
9744
+ EvidenceCardStore: () => EvidenceCardStore,
9745
+ buildEvidenceCardId: () => buildEvidenceCardId
9746
+ });
9747
+ import { createHash as createHash5, randomUUID as randomUUID4 } from "crypto";
9225
9748
  function safeJson(value, fallback) {
9226
9749
  if (typeof value !== "string" || value.length === 0) return fallback;
9227
9750
  try {
@@ -9270,6 +9793,9 @@ function sourceKind(observation) {
9270
9793
  if (observation.sourceDetail === "hook") return "hook";
9271
9794
  return observation.source ?? "agent";
9272
9795
  }
9796
+ function buildEvidenceCardId(projectId, candidateKind, candidateId) {
9797
+ return `evidence:${candidateKind}:${projectId}:${candidateId}`;
9798
+ }
9273
9799
  var EvidenceCardStore;
9274
9800
  var init_evidence_store = __esm({
9275
9801
  "src/store/evidence-store.ts"() {
@@ -9410,7 +9936,7 @@ var init_evidence_store = __esm({
9410
9936
  }
9411
9937
  recordEvent(projectId, cardId, kind, detail) {
9412
9938
  const event = {
9413
- id: randomUUID3(),
9939
+ id: randomUUID4(),
9414
9940
  projectId,
9415
9941
  cardId,
9416
9942
  kind,
@@ -9509,6 +10035,7 @@ var init_isolated_maintenance = __esm({
9509
10035
  "consolidation",
9510
10036
  "codegraph-refresh",
9511
10037
  "observation-qualify",
10038
+ "observation-project",
9512
10039
  "claim-derive",
9513
10040
  "claim-requalification",
9514
10041
  "knowledge-compile",
@@ -9521,7 +10048,7 @@ var init_isolated_maintenance = __esm({
9521
10048
  });
9522
10049
 
9523
10050
  // src/knowledge/workspace-store.ts
9524
- import { randomUUID as randomUUID4 } from "crypto";
10051
+ import { randomUUID as randomUUID5 } from "crypto";
9525
10052
  function arrayValue(raw) {
9526
10053
  if (typeof raw !== "string" || !raw) return [];
9527
10054
  try {
@@ -9662,7 +10189,7 @@ var init_workspace_store = __esm({
9662
10189
  }
9663
10190
  createProposal(input) {
9664
10191
  const proposal = {
9665
- id: input.id ?? randomUUID4(),
10192
+ id: input.id ?? randomUUID5(),
9666
10193
  ...input,
9667
10194
  status: input.status ?? "pending",
9668
10195
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
@@ -9948,11 +10475,11 @@ __export(consolidation_exports, {
9948
10475
  });
9949
10476
  function tokenize(text2) {
9950
10477
  return new Set(
9951
- text2.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff\s-]/g, " ").split(/\s+/).filter((t2) => t2.length > 1)
10478
+ text2.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, " ").split(/\s+/).filter((t2) => t2.length > 1)
9952
10479
  );
9953
10480
  }
9954
10481
  function jaccardSimilarity(a, b) {
9955
- if (a.size === 0 && b.size === 0) return 1;
10482
+ if (a.size === 0 && b.size === 0) return 0;
9956
10483
  let intersection = 0;
9957
10484
  for (const token of a) {
9958
10485
  if (b.has(token)) intersection++;
@@ -10318,7 +10845,7 @@ Respond in JSON only:
10318
10845
  });
10319
10846
 
10320
10847
  // src/media/media-store.ts
10321
- import { randomUUID as randomUUID5 } from "crypto";
10848
+ import { randomUUID as randomUUID6 } from "crypto";
10322
10849
  function asOptionalText(value) {
10323
10850
  return typeof value === "string" && value.length > 0 ? value : void 0;
10324
10851
  }
@@ -10488,7 +11015,7 @@ var init_media_store = __esm({
10488
11015
  return { asset: this.getAsset(input.projectId, existing.id), deduplicated: true };
10489
11016
  }
10490
11017
  const asset = {
10491
- id: randomUUID5(),
11018
+ id: randomUUID6(),
10492
11019
  ...input,
10493
11020
  createdAt: now3,
10494
11021
  updatedAt: now3
@@ -10568,7 +11095,7 @@ var init_media_store = __esm({
10568
11095
  `).get(input.assetId, input.observationId ?? null, input.role);
10569
11096
  if (existing) return rowToLink(existing);
10570
11097
  const link = {
10571
- id: randomUUID5(),
11098
+ id: randomUUID6(),
10572
11099
  assetId: input.assetId,
10573
11100
  projectId: input.projectId,
10574
11101
  ...input.observationId !== void 0 ? { observationId: input.observationId } : {},
@@ -10607,7 +11134,7 @@ var init_media_store = __esm({
10607
11134
  return rowToDerivation(this.db.prepare("SELECT * FROM media_derivations WHERE id = ?").get(existing.id));
10608
11135
  }
10609
11136
  const derivation = {
10610
- id: randomUUID5(),
11137
+ id: randomUUID6(),
10611
11138
  ...input,
10612
11139
  content,
10613
11140
  ...error ? { error } : {},
@@ -10694,7 +11221,7 @@ var init_media_store = __esm({
10694
11221
  createJob(input) {
10695
11222
  const now3 = Date.now();
10696
11223
  const job = {
10697
- id: randomUUID5(),
11224
+ id: randomUUID6(),
10698
11225
  projectId: input.projectId,
10699
11226
  kind: input.kind,
10700
11227
  status: "queued",
@@ -10856,7 +11383,7 @@ var init_types2 = __esm({
10856
11383
  });
10857
11384
 
10858
11385
  // src/media/asset-store.ts
10859
- import { createHash as createHash7, randomUUID as randomUUID6 } from "crypto";
11386
+ import { createHash as createHash7, randomUUID as randomUUID7 } from "crypto";
10860
11387
  import { copyFile, lstat, mkdir as mkdir3, open, readFile as readFile3, readdir, rename as rename2, rm, stat as stat2, writeFile as writeFile3 } from "fs/promises";
10861
11388
  import path12 from "path";
10862
11389
  function mediaRoot(dataDir) {
@@ -10927,7 +11454,7 @@ async function destinationExists(destination) {
10927
11454
  async function persistBuffer(bytes, destination) {
10928
11455
  await mkdir3(path12.dirname(destination), { recursive: true });
10929
11456
  if (await destinationExists(destination)) return false;
10930
- const temporary = `${destination}.${randomUUID6()}.tmp`;
11457
+ const temporary = `${destination}.${randomUUID7()}.tmp`;
10931
11458
  try {
10932
11459
  await writeFile3(temporary, bytes, { flag: "wx" });
10933
11460
  await rename2(temporary, destination);
@@ -19232,7 +19759,7 @@ var init_uuid = __esm({
19232
19759
  });
19233
19760
 
19234
19761
  // node_modules/openai/internal/errors.mjs
19235
- function isAbortError(err) {
19762
+ function isAbortError2(err) {
19236
19763
  return typeof err === "object" && err !== null && // Spec-compliant fetch implementations
19237
19764
  ("name" in err && err.name === "AbortError" || // Expo fetch
19238
19765
  "message" in err && String(err.message).includes("FetchRequestCanceledException"));
@@ -20412,7 +20939,7 @@ var init_streaming = __esm({
20412
20939
  }
20413
20940
  done = true;
20414
20941
  } catch (e2) {
20415
- if (isAbortError(e2))
20942
+ if (isAbortError2(e2))
20416
20943
  return;
20417
20944
  throw e2;
20418
20945
  } finally {
@@ -20455,7 +20982,7 @@ var init_streaming = __esm({
20455
20982
  }
20456
20983
  done = true;
20457
20984
  } catch (e2) {
20458
- if (isAbortError(e2))
20985
+ if (isAbortError2(e2))
20459
20986
  return;
20460
20987
  throw e2;
20461
20988
  } finally {
@@ -27004,7 +27531,7 @@ var init_client = __esm({
27004
27531
  if (options.signal?.aborted) {
27005
27532
  throw new APIUserAbortError();
27006
27533
  }
27007
- const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
27534
+ const isTimeout = isAbortError2(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
27008
27535
  if (retriesRemaining) {
27009
27536
  loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
27010
27537
  loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({
@@ -46093,7 +46620,7 @@ var init_uuid2 = __esm({
46093
46620
  });
46094
46621
 
46095
46622
  // node_modules/@anthropic-ai/sdk/internal/errors.mjs
46096
- function isAbortError2(err) {
46623
+ function isAbortError3(err) {
46097
46624
  return typeof err === "object" && err !== null && // Spec-compliant fetch implementations
46098
46625
  ("name" in err && err.name === "AbortError" || // Expo fetch
46099
46626
  "message" in err && String(err.message).includes("FetchRequestCanceledException"));
@@ -46864,7 +47391,7 @@ var init_streaming3 = __esm({
46864
47391
  }
46865
47392
  done = true;
46866
47393
  } catch (e2) {
46867
- if (isAbortError2(e2))
47394
+ if (isAbortError3(e2))
46868
47395
  return;
46869
47396
  throw e2;
46870
47397
  } finally {
@@ -46907,7 +47434,7 @@ var init_streaming3 = __esm({
46907
47434
  }
46908
47435
  done = true;
46909
47436
  } catch (e2) {
46910
- if (isAbortError2(e2))
47437
+ if (isAbortError3(e2))
46911
47438
  return;
46912
47439
  throw e2;
46913
47440
  } finally {
@@ -49029,7 +49556,7 @@ var init_BetaMessageStream = __esm({
49029
49556
  _BetaMessageStream_logger.set(this, void 0);
49030
49557
  _BetaMessageStream_handleError.set(this, (error) => {
49031
49558
  __classPrivateFieldSet2(this, _BetaMessageStream_errored, true, "f");
49032
- if (isAbortError2(error)) {
49559
+ if (isAbortError3(error)) {
49033
49560
  error = new APIUserAbortError2();
49034
49561
  }
49035
49562
  if (error instanceof APIUserAbortError2) {
@@ -51490,7 +52017,7 @@ var init_MessageStream = __esm({
51490
52017
  _MessageStream_logger.set(this, void 0);
51491
52018
  _MessageStream_handleError.set(this, (error) => {
51492
52019
  __classPrivateFieldSet2(this, _MessageStream_errored, true, "f");
51493
- if (isAbortError2(error)) {
52020
+ if (isAbortError3(error)) {
51494
52021
  error = new APIUserAbortError2();
51495
52022
  }
51496
52023
  if (error instanceof APIUserAbortError2) {
@@ -52620,7 +53147,7 @@ var init_client2 = __esm({
52620
53147
  if (options.signal?.aborted) {
52621
53148
  throw new APIUserAbortError2();
52622
53149
  }
52623
- const isTimeout = isAbortError2(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
53150
+ const isTimeout = isAbortError3(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
52624
53151
  if (retriesRemaining) {
52625
53152
  loggerFor2(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
52626
53153
  loggerFor2(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails2({
@@ -63829,7 +64356,7 @@ var require_gaxios = __commonJS({
63829
64356
  var retry_js_1 = require_retry3();
63830
64357
  var stream_1 = __require("stream");
63831
64358
  var interceptor_js_1 = require_interceptor();
63832
- var randomUUID16 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
64359
+ var randomUUID17 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
63833
64360
  var HTTP_STATUS_NO_CONTENT = 204;
63834
64361
  var Gaxios = class {
63835
64362
  agentCache = /* @__PURE__ */ new Map();
@@ -64102,7 +64629,7 @@ var require_gaxios = __commonJS({
64102
64629
  */
64103
64630
  ["Blob", "File", "FormData"].includes(opts.data?.constructor?.name || "");
64104
64631
  if (opts.multipart?.length) {
64105
- const boundary = await randomUUID16();
64632
+ const boundary = await randomUUID17();
64106
64633
  preparedHeaders.set("content-type", `multipart/related; boundary=${boundary}`);
64107
64634
  opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary));
64108
64635
  } else if (shouldDirectlyPassData) {
@@ -87128,7 +87655,7 @@ function listDocumentsResponseFromMldev(fromObject) {
87128
87655
  }
87129
87656
  return toObject;
87130
87657
  }
87131
- function isAbortError3(err) {
87658
+ function isAbortError4(err) {
87132
87659
  return typeof err === "object" && err !== null && // Spec-compliant fetch implementations
87133
87660
  ("name" in err && err.name === "AbortError" || // Expo fetch
87134
87661
  "message" in err && String(err.message).includes("FetchRequestCanceledException"));
@@ -94342,7 +94869,7 @@ ${underline}`);
94342
94869
  }
94343
94870
  done = true;
94344
94871
  } catch (e2) {
94345
- if (isAbortError3(e2))
94872
+ if (isAbortError4(e2))
94346
94873
  return yield __await(void 0);
94347
94874
  throw e2;
94348
94875
  } finally {
@@ -94417,7 +94944,7 @@ ${underline}`);
94417
94944
  }
94418
94945
  done = true;
94419
94946
  } catch (e2) {
94420
- if (isAbortError3(e2))
94947
+ if (isAbortError4(e2))
94421
94948
  return yield __await(void 0);
94422
94949
  throw e2;
94423
94950
  } finally {
@@ -94793,7 +95320,7 @@ ${underline}`);
94793
95320
  if ((_d = options.signal) === null || _d === void 0 ? void 0 : _d.aborted) {
94794
95321
  throw new APIUserAbortError3();
94795
95322
  }
94796
- const isTimeout = isAbortError3(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
95323
+ const isTimeout = isAbortError4(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
94797
95324
  if (retriesRemaining) {
94798
95325
  loggerFor3(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
94799
95326
  loggerFor3(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails3({
@@ -97017,7 +97544,7 @@ function isTimeoutError(err) {
97017
97544
  const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnaborted";
97018
97545
  return isNative || isLegacyNative || isGenericErr;
97019
97546
  }
97020
- function isAbortError4(err) {
97547
+ function isAbortError5(err) {
97021
97548
  if (typeof err !== "object" || err == null) {
97022
97549
  return false;
97023
97550
  }
@@ -98029,7 +98556,7 @@ var init_sdks = __esm({
98029
98556
  return response;
98030
98557
  }, { config: options.retryConfig, statusCodes: options.retryCodes }).then((r2) => OK(r2), (err) => {
98031
98558
  switch (true) {
98032
- case isAbortError4(err):
98559
+ case isAbortError5(err):
98033
98560
  return ERR(new RequestAbortedError("Request aborted by client", {
98034
98561
  cause: err
98035
98562
  }));
@@ -144857,14 +145384,23 @@ var init_audio_jobs = __esm({
144857
145384
  }
144858
145385
  });
144859
145386
 
144860
- // src/memory/feedback-model.ts
145387
+ // src/core/retrieval-policy.ts
144861
145388
  function feedbackWeightMultiplier(weight) {
144862
145389
  return Math.max(0.35, Math.min(1.4, 0.35 + Math.max(0, Math.min(2, weight)) * 0.525));
144863
145390
  }
145391
+ var init_retrieval_policy = __esm({
145392
+ "src/core/retrieval-policy.ts"() {
145393
+ "use strict";
145394
+ init_esm_shims();
145395
+ }
145396
+ });
145397
+
145398
+ // src/memory/feedback-model.ts
144864
145399
  var init_feedback_model = __esm({
144865
145400
  "src/memory/feedback-model.ts"() {
144866
145401
  "use strict";
144867
145402
  init_esm_shims();
145403
+ init_retrieval_policy();
144868
145404
  }
144869
145405
  });
144870
145406
 
@@ -144876,7 +145412,7 @@ __export(feedback_exports, {
144876
145412
  applyMemoryFeedback: () => applyMemoryFeedback,
144877
145413
  feedbackWeightMultiplier: () => feedbackWeightMultiplier
144878
145414
  });
144879
- import { randomUUID as randomUUID7 } from "crypto";
145415
+ import { randomUUID as randomUUID8 } from "crypto";
144880
145416
  function applyMemoryFeedback(current, event) {
144881
145417
  const delta = event.signal === "revoke" ? 0 : FEEDBACK_DELTAS[event.signal];
144882
145418
  const weight = Math.max(0, Math.min(2, current.weight + delta));
@@ -144994,7 +145530,7 @@ var init_feedback = __esm({
144994
145530
  if (!target) throw new Error("The feedback event to revoke was not found in the same candidate scope.");
144995
145531
  }
144996
145532
  const event = {
144997
- id: randomUUID7(),
145533
+ id: randomUUID8(),
144998
145534
  projectId: input.projectId,
144999
145535
  candidateKind: input.candidateKind,
145000
145536
  candidateId: input.candidateId,
@@ -145382,7 +145918,7 @@ var init_retention = __esm({
145382
145918
  });
145383
145919
 
145384
145920
  // src/memory/owner.ts
145385
- import { randomUUID as randomUUID8 } from "crypto";
145921
+ import { randomUUID as randomUUID9 } from "crypto";
145386
145922
  import { promises as fs9 } from "fs";
145387
145923
  import path18 from "path";
145388
145924
  function ownerPath(dataDir) {
@@ -145412,7 +145948,7 @@ async function resolveLocalMemoryOwner(dataDir, options = {}) {
145412
145948
  await fs9.mkdir(path18.dirname(filePath), { recursive: true });
145413
145949
  const created = {
145414
145950
  version: 1,
145415
- id: "local-" + randomUUID8(),
145951
+ id: "local-" + randomUUID9(),
145416
145952
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
145417
145953
  };
145418
145954
  try {
@@ -145435,7 +145971,7 @@ var init_owner = __esm({
145435
145971
  });
145436
145972
 
145437
145973
  // src/memory/long-term-store.ts
145438
- import { randomUUID as randomUUID9 } from "crypto";
145974
+ import { randomUUID as randomUUID10 } from "crypto";
145439
145975
  function optionalText2(value) {
145440
145976
  return typeof value === "string" && value.trim() ? value : void 0;
145441
145977
  }
@@ -145595,7 +146131,7 @@ var init_long_term_store = __esm({
145595
146131
  }
145596
146132
  insertEvidence(input) {
145597
146133
  const evidence = {
145598
- id: randomUUID9(),
146134
+ id: randomUUID10(),
145599
146135
  ...input,
145600
146136
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
145601
146137
  };
@@ -145622,7 +146158,7 @@ var init_long_term_store = __esm({
145622
146158
  }
145623
146159
  recordEvent(input) {
145624
146160
  const event = {
145625
- id: randomUUID9(),
146161
+ id: randomUUID10(),
145626
146162
  ...input,
145627
146163
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
145628
146164
  };
@@ -145712,7 +146248,7 @@ __export(long_term_exports, {
145712
146248
  selectLongTermMemoriesForTask: () => selectLongTermMemoriesForTask,
145713
146249
  supersedeLongTermMemory: () => supersedeLongTermMemory
145714
146250
  });
145715
- import { randomUUID as randomUUID10 } from "crypto";
146251
+ import { randomUUID as randomUUID11 } from "crypto";
145716
146252
  function isOneOf(value, values) {
145717
146253
  return typeof value === "string" && values.includes(value);
145718
146254
  }
@@ -145894,7 +146430,7 @@ async function createManualLongTermMemory(input) {
145894
146430
  const owner = await resolveLocalMemoryOwner(input.dataDir, { create: true });
145895
146431
  if (!owner) throw new Error("Memorix could not resolve a local memory owner.");
145896
146432
  assertScope(input.scope);
145897
- const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID10(), relation: "supports" }];
146433
+ const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID11(), relation: "supports" }];
145898
146434
  return createLongTermMemoryWithDataDir({
145899
146435
  dataDir: input.dataDir,
145900
146436
  originProjectId: input.projectId,
@@ -145949,7 +146485,7 @@ async function createLongTermMemoryWithDataDir(input) {
145949
146485
  assertPortableEvidence(input.scope, portability, evidenceInputs);
145950
146486
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
145951
146487
  const memory = {
145952
- id: randomUUID10(),
146488
+ id: randomUUID11(),
145953
146489
  originProjectId: compactText(input.originProjectId, "origin project id", 1e3),
145954
146490
  ownerId: compactText(input.ownerId, "owner id", 160),
145955
146491
  scope: input.scope,
@@ -146304,7 +146840,7 @@ var store_exports = {};
146304
146840
  __export(store_exports, {
146305
146841
  CodeGraphStore: () => CodeGraphStore
146306
146842
  });
146307
- import { randomUUID as randomUUID11 } from "crypto";
146843
+ import { randomUUID as randomUUID12 } from "crypto";
146308
146844
  import { posix as pathPosix } from "path";
146309
146845
  function rowToFile(row) {
146310
146846
  return {
@@ -147233,7 +147769,7 @@ var init_store = __esm({
147233
147769
  * so an interrupted scan cannot be advertised as complete.
147234
147770
  */
147235
147771
  recordCodeStateSnapshot(input) {
147236
- const id = randomUUID11();
147772
+ const id = randomUUID12();
147237
147773
  let snapshot;
147238
147774
  let compactNeeded = false;
147239
147775
  const tx = this.db.transaction(() => {
@@ -148466,7 +149002,7 @@ var claim_store_exports = {};
148466
149002
  __export(claim_store_exports, {
148467
149003
  ClaimStore: () => ClaimStore
148468
149004
  });
148469
- import { createHash as createHash12, randomUUID as randomUUID12 } from "crypto";
149005
+ import { createHash as createHash12, randomUUID as randomUUID13 } from "crypto";
148470
149006
  function optionalText3(value) {
148471
149007
  return typeof value === "string" && value ? value : void 0;
148472
149008
  }
@@ -148650,7 +149186,7 @@ var init_claim_store = __esm({
148650
149186
  locator, capturedHash, evidenceKey, createdAt
148651
149187
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
148652
149188
  `).run(
148653
- randomUUID12(),
149189
+ randomUUID13(),
148654
149190
  input.claimId,
148655
149191
  input.evidenceKind,
148656
149192
  input.evidenceId,
@@ -148672,7 +149208,7 @@ var init_claim_store = __esm({
148672
149208
  }
148673
149209
  recordEvent(input) {
148674
149210
  const event = {
148675
- id: randomUUID12(),
149211
+ id: randomUUID13(),
148676
149212
  ...input,
148677
149213
  ...input.detail ? { detail: sanitizeCredentials(input.detail) } : {},
148678
149214
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
@@ -148717,7 +149253,7 @@ __export(claims_exports, {
148717
149253
  supersedeClaim: () => supersedeClaim,
148718
149254
  writeClaim: () => writeClaim
148719
149255
  });
148720
- import { createHash as createHash13, randomUUID as randomUUID13 } from "crypto";
149256
+ import { createHash as createHash13, randomUUID as randomUUID14 } from "crypto";
148721
149257
  function compactText2(value, field) {
148722
149258
  if (typeof value !== "string") throw new Error("Claim " + field + " must be text");
148723
149259
  const sanitized = sanitizeCredentials(value).trim().replace(/\s+/g, " ");
@@ -148803,7 +149339,7 @@ function normalizeClaimInput(input) {
148803
149339
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
148804
149340
  return {
148805
149341
  claim: {
148806
- id: randomUUID13(),
149342
+ id: randomUUID14(),
148807
149343
  projectId,
148808
149344
  subject,
148809
149345
  predicate,
@@ -149888,7 +150424,7 @@ var init_workflow_sync = __esm({
149888
150424
  });
149889
150425
 
149890
150426
  // src/knowledge/workflow-store.ts
149891
- import { randomUUID as randomUUID14 } from "crypto";
150427
+ import { randomUUID as randomUUID15 } from "crypto";
149892
150428
  function parseJson(value, fallback) {
149893
150429
  if (typeof value !== "string" || !value) return fallback;
149894
150430
  try {
@@ -149988,7 +150524,7 @@ var init_workflow_store = __esm({
149988
150524
  }
149989
150525
  recordRun(input) {
149990
150526
  const run = {
149991
- id: randomUUID14(),
150527
+ id: randomUUID15(),
149992
150528
  workflowId: input.workflowId,
149993
150529
  projectId: input.projectId,
149994
150530
  task: input.task.trim(),
@@ -150056,7 +150592,7 @@ var init_outcome_types = __esm({
150056
150592
  });
150057
150593
 
150058
150594
  // src/knowledge/outcome-store.ts
150059
- import { randomUUID as randomUUID15 } from "crypto";
150595
+ import { randomUUID as randomUUID16 } from "crypto";
150060
150596
  function optionalText5(value) {
150061
150597
  return typeof value === "string" && value.trim() ? value : void 0;
150062
150598
  }
@@ -150100,7 +150636,7 @@ var init_outcome_store = __esm({
150100
150636
  }
150101
150637
  record(input) {
150102
150638
  const signal = {
150103
- id: randomUUID15(),
150639
+ id: randomUUID16(),
150104
150640
  projectId: text(input.projectId, "project id"),
150105
150641
  candidateKind: oneOf(input.candidateKind, MEMORY_OUTCOME_CANDIDATE_KINDS, "candidate kind"),
150106
150642
  candidateId: text(input.candidateId, "candidate id"),
@@ -150934,6 +151470,15 @@ function observationId(payload) {
150934
151470
  const value = payload.observationId;
150935
151471
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
150936
151472
  }
151473
+ async function automaticCleanupEnabled(projectRoot) {
151474
+ if (!projectRoot) return true;
151475
+ try {
151476
+ const { getResolvedConfig: getResolvedConfig2 } = await Promise.resolve().then(() => (init_resolved_config(), resolved_config_exports));
151477
+ return getResolvedConfig2({ projectRoot }).memory.autoCleanup !== false;
151478
+ } catch {
151479
+ return true;
151480
+ }
151481
+ }
150937
151482
  function workspaceMode(payload) {
150938
151483
  return payload.workspaceMode === "local" || payload.workspaceMode === "versioned" ? payload.workspaceMode : void 0;
150939
151484
  }
@@ -151022,6 +151567,9 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
151022
151567
  if (job.projectId !== projectId) {
151023
151568
  return { action: "reschedule", delayMs: VECTOR_RETRY_DELAY_MS };
151024
151569
  }
151570
+ if ((job.kind === "retention-archive" || job.kind === "consolidation" || job.kind === "long-term-maintenance") && !await automaticCleanupEnabled(projectRoot)) {
151571
+ return { action: "complete" };
151572
+ }
151025
151573
  if (job.kind === "media-video-generation") {
151026
151574
  const { runMiniMaxVideoGenerationJob: runMiniMaxVideoGenerationJob2 } = await Promise.resolve().then(() => (init_video_jobs(), video_jobs_exports));
151027
151575
  return runMiniMaxVideoGenerationJob2(job, { dataDir: projectDir2, projectId });
@@ -151114,6 +151662,33 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
151114
151662
  });
151115
151663
  return { action: "complete" };
151116
151664
  }
151665
+ if (job.kind === "observation-project") {
151666
+ if (!projectRoot) {
151667
+ throw new Error(`Observation projection requires a project root for ${projectId}`);
151668
+ }
151669
+ const id = observationId(job.payload);
151670
+ if (!id) return { action: "complete" };
151671
+ const [
151672
+ { CodeGraphStore: CodeGraphStore2 },
151673
+ { bindObservationToCode: bindObservationToCode2 },
151674
+ { EvidenceCardStore: EvidenceCardStore2 },
151675
+ { getObservationStore: getObservationStore2 }
151676
+ ] = await Promise.all([
151677
+ Promise.resolve().then(() => (init_store(), store_exports)),
151678
+ Promise.resolve().then(() => (init_binder(), binder_exports)),
151679
+ Promise.resolve().then(() => (init_evidence_store(), evidence_store_exports)),
151680
+ Promise.resolve().then(() => (init_obs_store(), obs_store_exports))
151681
+ ]);
151682
+ const observation = await getObservationStore2().getById(id);
151683
+ if (!observation || observation.projectId !== projectId) return { action: "complete" };
151684
+ const codeStore = new CodeGraphStore2();
151685
+ await codeStore.init(projectDir2);
151686
+ await bindObservationToCode2(codeStore, observation);
151687
+ const evidence = new EvidenceCardStore2();
151688
+ await evidence.init(projectDir2);
151689
+ evidence.upsertObservation(observation);
151690
+ return { action: "complete" };
151691
+ }
151117
151692
  if (job.kind === "observation-qualify") {
151118
151693
  const [
151119
151694
  { CodeGraphStore: CodeGraphStore2 },
@@ -151321,7 +151896,15 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
151321
151896
  const after = getVectorStatus2(projectId);
151322
151897
  if (after.missing === 0) {
151323
151898
  resolveSupersededVectorFailures(projectDir2, projectId);
151324
- return { action: "complete" };
151899
+ return {
151900
+ action: "complete",
151901
+ progress: {
151902
+ attempted: result.attempted,
151903
+ succeeded: result.succeeded,
151904
+ failed: result.failed,
151905
+ remaining: 0
151906
+ }
151907
+ };
151325
151908
  }
151326
151909
  if (result.failed > 0 && result.succeeded === 0) {
151327
151910
  const streak = vectorBackfillFailureStreak(job.payload) + 1;
@@ -151336,6 +151919,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
151336
151919
  ...job.payload,
151337
151920
  vectorBackfillFailureStreak: streak
151338
151921
  },
151922
+ progress: {
151923
+ attempted: result.attempted,
151924
+ succeeded: result.succeeded,
151925
+ failed: result.failed,
151926
+ remaining: after.missing
151927
+ },
151339
151928
  lastError: result.lastError ?? `vector backfill made no progress (${result.failed}/${result.attempted} failed)`
151340
151929
  };
151341
151930
  }
@@ -151345,6 +151934,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
151345
151934
  action: "reschedule",
151346
151935
  delayMs: result.attempted === 0 ? VECTOR_RETRY_DELAY_MS : 0,
151347
151936
  resetAttempts: result.succeeded > 0,
151937
+ progress: {
151938
+ attempted: result.attempted,
151939
+ succeeded: result.succeeded,
151940
+ failed: result.failed,
151941
+ remaining: after.missing
151942
+ },
151348
151943
  ...result.succeeded > 0 ? {
151349
151944
  ...priorFailureStreak > 0 ? { payload } : {},
151350
151945
  ...result.failed > 0 && result.lastError ? { lastError: result.lastError } : priorFailureStreak > 0 ? { clearLastError: true } : {}
@@ -151753,24 +152348,40 @@ function queueVectorBackfill(projectId, options = {}) {
151753
152348
  });
151754
152349
  }
151755
152350
  async function bindObservationCodeRefsBestEffort(observation) {
151756
- if (!projectDir) return;
152351
+ if (!projectDir) return true;
151757
152352
  try {
151758
152353
  const { CodeGraphStore: CodeGraphStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
151759
152354
  const { bindObservationToCode: bindObservationToCode2 } = await Promise.resolve().then(() => (init_binder(), binder_exports));
151760
152355
  const codeStore = new CodeGraphStore2();
151761
152356
  await codeStore.init(projectDir);
151762
152357
  await bindObservationToCode2(codeStore, observation);
152358
+ return true;
151763
152359
  } catch {
152360
+ return false;
151764
152361
  }
151765
152362
  }
151766
152363
  async function persistEvidenceCard(observation) {
151767
- if (!projectDir) return;
152364
+ if (!projectDir) return true;
151768
152365
  try {
151769
152366
  const evidence = new EvidenceCardStore();
151770
152367
  await evidence.init(projectDir);
151771
152368
  evidence.upsertObservation(observation);
152369
+ return true;
151772
152370
  } catch (error) {
151773
152371
  console.error(`[memorix] Evidence card projection failed for obs-${observation.id}: ${error instanceof Error ? error.message : String(error)}`);
152372
+ return false;
152373
+ }
152374
+ }
152375
+ async function acknowledgeObservationProjection(observation) {
152376
+ if (!projectDir) return;
152377
+ try {
152378
+ const { MaintenanceJobStore: MaintenanceJobStore2 } = await Promise.resolve().then(() => (init_maintenance_jobs(), maintenance_jobs_exports));
152379
+ new MaintenanceJobStore2(projectDir).acknowledgePending(
152380
+ observation.projectId,
152381
+ "observation-project",
152382
+ "observation-project:" + observation.id
152383
+ );
152384
+ } catch {
151774
152385
  }
151775
152386
  }
151776
152387
  function queueClaimDerivation(observation) {
@@ -151799,6 +152410,45 @@ function queueObservationQualification(observation) {
151799
152410
  } catch {
151800
152411
  }
151801
152412
  }
152413
+ async function enqueueObservationDerivedWork(tx, observation) {
152414
+ if (!tx.enqueueMaintenanceJob) return false;
152415
+ if (!isEmbeddingExplicitlyDisabled()) {
152416
+ await tx.enqueueMaintenanceJob({
152417
+ projectId: observation.projectId,
152418
+ kind: "vector-backfill",
152419
+ dedupeKey: "vector-backfill",
152420
+ payload: { limit: 12 }
152421
+ });
152422
+ }
152423
+ if (observation.admissionState === "candidate") {
152424
+ await tx.enqueueMaintenanceJob({
152425
+ projectId: observation.projectId,
152426
+ kind: "observation-qualify",
152427
+ dedupeKey: "observation-qualify",
152428
+ payload: { source: "automatic-capture:" + observation.id, limit: 100 }
152429
+ });
152430
+ }
152431
+ const claimSource = observation.sourceDetail === "explicit" || observation.source === "git" || observation.sourceDetail === "git-ingest";
152432
+ if (claimSource && resolveObservationVisibility(observation) === "project") {
152433
+ await tx.enqueueMaintenanceJob({
152434
+ projectId: observation.projectId,
152435
+ kind: "claim-derive",
152436
+ dedupeKey: "claim-derive:" + observation.id,
152437
+ payload: { observationId: observation.id }
152438
+ });
152439
+ }
152440
+ await enqueueObservationProjectionWork(tx, observation);
152441
+ return true;
152442
+ }
152443
+ async function enqueueObservationProjectionWork(tx, observation) {
152444
+ if (!tx.enqueueMaintenanceJob) return;
152445
+ await tx.enqueueMaintenanceJob({
152446
+ projectId: observation.projectId,
152447
+ kind: "observation-project",
152448
+ dedupeKey: "observation-project:" + observation.id,
152449
+ payload: { observationId: observation.id }
152450
+ });
152451
+ }
151802
152452
  function isVectorCompatibleWithCurrentIndex(embedding) {
151803
152453
  if (!embedding) return false;
151804
152454
  const vectorDimensions = getVectorDimensions();
@@ -151977,7 +152627,6 @@ async function storeObservation(input) {
151977
152627
  throw new Error("Cannot update a memory outside this session's write scope.");
151978
152628
  }
151979
152629
  const observation2 = await upsertObservation(existing, input, now3);
151980
- await input.onPersisted?.(observation2);
151981
152630
  return { observation: observation2, upserted: true };
151982
152631
  }
151983
152632
  }
@@ -152004,6 +152653,7 @@ async function storeObservation(input) {
152004
152653
  let upsertedInsideLock = false;
152005
152654
  let reloadCacheAfterCommit = false;
152006
152655
  let persistedCallbackInvoked = false;
152656
+ let derivedJobsCommitted = false;
152007
152657
  const assignAndPersist = async () => {
152008
152658
  if (projectDir) {
152009
152659
  const store = getObservationStore();
@@ -152059,6 +152709,7 @@ async function storeObservation(input) {
152059
152709
  writeGeneration: transactionGeneration + 1
152060
152710
  };
152061
152711
  await tx.insert(observation);
152712
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, observation);
152062
152713
  await input.onPersisted?.(observation);
152063
152714
  persistedCallbackInvoked = true;
152064
152715
  await tx.saveIdCounter(id + 1);
@@ -152157,15 +152808,17 @@ async function storeObservation(input) {
152157
152808
  await assignAndPersist();
152158
152809
  if (upsertedInsideLock) {
152159
152810
  const updated = await upsertObservation(observation, input, now3);
152160
- await input.onPersisted?.(updated);
152161
152811
  return { observation: updated, upserted: true };
152162
152812
  }
152163
152813
  if (!persistedCallbackInvoked) await input.onPersisted?.(observation);
152164
- await bindObservationCodeRefsBestEffort(observation);
152165
- await persistEvidenceCard(observation);
152166
- queueObservationQualification(observation);
152167
- if (resolveObservationVisibility(observation) === "project") {
152168
- queueClaimDerivation(observation);
152814
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(observation);
152815
+ const evidenceProjected = await persistEvidenceCard(observation);
152816
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(observation);
152817
+ if (!derivedJobsCommitted) {
152818
+ queueObservationQualification(observation);
152819
+ if (resolveObservationVisibility(observation) === "project") {
152820
+ queueClaimDerivation(observation);
152821
+ }
152169
152822
  }
152170
152823
  scheduleObservationEmbedding({
152171
152824
  observationId: observation.id,
@@ -152187,86 +152840,115 @@ async function upsertObservation(existing, input, now3) {
152187
152840
  }
152188
152841
  const fullText = [input.title, input.narrative, ...input.facts ?? [], ...enrichedFiles, ...enrichedConcepts].join(" ");
152189
152842
  const tokens = countTextTokens(fullText);
152190
- existing.entityName = input.entityName;
152191
- existing.type = input.type;
152192
- existing.title = input.title;
152193
- existing.narrative = input.narrative;
152194
- existing.facts = input.facts ?? [];
152195
- existing.attachments = input.attachments;
152196
- existing.filesModified = enrichedFiles;
152197
- existing.concepts = enrichedConcepts;
152198
- existing.tokens = tokens;
152199
- existing.updatedAt = now3;
152200
- existing.hasCausalLanguage = extracted.hasCausalLanguage;
152201
- existing.revisionCount = (existing.revisionCount ?? 1) + 1;
152202
- existing.status = "active";
152203
- if (input.sessionId) existing.sessionId = input.sessionId;
152204
- if (input.progress) existing.progress = input.progress;
152205
- if (input.sourceDetail !== void 0) existing.sourceDetail = input.sourceDetail;
152206
- if (input.valueCategory !== void 0) existing.valueCategory = input.valueCategory;
152207
- if (input.admissionState !== void 0) existing.admissionState = input.admissionState;
152208
- if (input.admissionReason !== void 0) existing.admissionReason = sanitizeCredentials(input.admissionReason);
152209
- if (input.visibility !== void 0) existing.visibility = input.visibility;
152210
- if (input.sharedWithAgentIds !== void 0) existing.sharedWithAgentIds = input.sharedWithAgentIds;
152843
+ const applyUpdate = (current) => ({
152844
+ ...current,
152845
+ entityName: input.entityName,
152846
+ type: input.type,
152847
+ title: input.title,
152848
+ narrative: input.narrative,
152849
+ facts: input.facts ?? [],
152850
+ attachments: input.attachments,
152851
+ filesModified: enrichedFiles,
152852
+ concepts: enrichedConcepts,
152853
+ tokens,
152854
+ updatedAt: now3,
152855
+ hasCausalLanguage: extracted.hasCausalLanguage,
152856
+ revisionCount: (current.revisionCount ?? 1) + 1,
152857
+ status: "active",
152858
+ ...input.sessionId ? { sessionId: input.sessionId } : {},
152859
+ ...input.progress ? { progress: input.progress } : {},
152860
+ ...input.sourceDetail !== void 0 ? { sourceDetail: input.sourceDetail } : {},
152861
+ ...input.valueCategory !== void 0 ? { valueCategory: input.valueCategory } : {},
152862
+ ...input.admissionState !== void 0 ? { admissionState: input.admissionState } : {},
152863
+ ...input.admissionReason !== void 0 ? { admissionReason: sanitizeCredentials(input.admissionReason) } : {},
152864
+ ...input.visibility !== void 0 ? { visibility: input.visibility } : {},
152865
+ ...input.sharedWithAgentIds !== void 0 ? { sharedWithAgentIds: input.sharedWithAgentIds } : {}
152866
+ });
152867
+ let updated = applyUpdate(existing);
152868
+ let derivedJobsCommitted = false;
152869
+ if (projectDir) {
152870
+ const store = getObservationStore();
152871
+ await store.atomic(async (tx) => {
152872
+ const current = await tx.getById(existing.id);
152873
+ if (!current || current.projectId !== existing.projectId) {
152874
+ throw new Error("Topic observation changed before update");
152875
+ }
152876
+ updated = applyUpdate(current);
152877
+ updated.writeGeneration = await tx.getGeneration() + 1;
152878
+ await tx.update(updated);
152879
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, updated);
152880
+ await input.onPersisted?.(updated);
152881
+ });
152882
+ updated.writeGeneration = store.getGeneration();
152883
+ } else {
152884
+ await input.onPersisted?.(updated);
152885
+ }
152886
+ if (corpusLoaded) {
152887
+ const cacheIndex = observations.findIndex((observation) => observation.id === updated.id);
152888
+ if (cacheIndex >= 0) observations[cacheIndex] = updated;
152889
+ }
152211
152890
  const doc = {
152212
- id: makeOramaObservationId(existing.projectId, existing.id),
152213
- observationId: existing.id,
152214
- entityName: existing.entityName,
152215
- type: existing.type,
152216
- title: existing.title,
152217
- narrative: existing.narrative,
152218
- facts: existing.facts.join("\n"),
152891
+ id: makeOramaObservationId(updated.projectId, updated.id),
152892
+ observationId: updated.id,
152893
+ entityName: updated.entityName,
152894
+ type: updated.type,
152895
+ title: updated.title,
152896
+ narrative: updated.narrative,
152897
+ facts: updated.facts.join("\n"),
152219
152898
  filesModified: enrichedFiles.join("\n"),
152220
152899
  concepts: enrichedConcepts.map((c) => c.replace(/-/g, " ")).join(", "),
152221
- attachments: formatAttachmentProvenance(existing.attachments),
152900
+ attachments: formatAttachmentProvenance(updated.attachments),
152222
152901
  tokens,
152223
- createdAt: existing.createdAt,
152224
- projectId: existing.projectId,
152902
+ createdAt: updated.createdAt,
152903
+ projectId: updated.projectId,
152225
152904
  accessCount: 0,
152226
152905
  lastAccessedAt: "",
152227
152906
  status: "active",
152228
- source: existing.source ?? "agent",
152229
- sourceDetail: existing.sourceDetail ?? "",
152230
- valueCategory: existing.valueCategory ?? "",
152231
- admissionState: existing.admissionState ?? "",
152232
- admissionReason: existing.admissionReason ?? "",
152233
- visibility: existing.visibility ?? "project",
152234
- createdByAgentId: existing.createdByAgentId ?? "",
152235
- sharedWithAgentIds: JSON.stringify(existing.sharedWithAgentIds ?? [])
152236
- };
152237
- const oramaId = makeOramaObservationId(existing.projectId, existing.id);
152238
- try {
152239
- const { removeObservation: removeObservation2 } = await Promise.resolve().then(() => (init_orama_store(), orama_store_exports));
152240
- await removeObservation2(oramaId);
152241
- } catch {
152242
- }
152243
- try {
152244
- await insertObservation(doc);
152245
- } catch {
152907
+ source: updated.source ?? "agent",
152908
+ sourceDetail: updated.sourceDetail ?? "",
152909
+ valueCategory: updated.valueCategory ?? "",
152910
+ admissionState: updated.admissionState ?? "",
152911
+ admissionReason: updated.admissionReason ?? "",
152912
+ visibility: updated.visibility ?? "project",
152913
+ createdByAgentId: updated.createdByAgentId ?? "",
152914
+ sharedWithAgentIds: JSON.stringify(updated.sharedWithAgentIds ?? [])
152915
+ };
152916
+ if (corpusLoaded) {
152917
+ const oramaId = makeOramaObservationId(updated.projectId, updated.id);
152246
152918
  try {
152247
- const { removeObservation: removeObs } = await Promise.resolve().then(() => (init_orama_store(), orama_store_exports));
152248
- await removeObs(oramaId);
152919
+ try {
152920
+ await removeObservation(oramaId);
152921
+ } catch {
152922
+ }
152249
152923
  await insertObservation(doc);
152250
152924
  } catch {
152925
+ try {
152926
+ try {
152927
+ await removeObservation(oramaId);
152928
+ } catch {
152929
+ }
152930
+ await insertObservation(doc);
152931
+ } catch (error) {
152932
+ console.error(`[memorix] Observation index projection failed for obs-${updated.id}: ${sanitizeCredentials(error instanceof Error ? error.message : String(error))}`);
152933
+ }
152251
152934
  }
152252
152935
  }
152253
- if (projectDir) {
152254
- const store = getObservationStore();
152255
- await store.update(existing);
152256
- }
152257
- await bindObservationCodeRefsBestEffort(existing);
152258
- await persistEvidenceCard(existing);
152259
- queueObservationQualification(existing);
152260
- if (resolveObservationVisibility(existing) === "project") {
152261
- queueClaimDerivation(existing);
152936
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(updated);
152937
+ const evidenceProjected = await persistEvidenceCard(updated);
152938
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(updated);
152939
+ if (!derivedJobsCommitted) {
152940
+ queueObservationQualification(updated);
152941
+ if (resolveObservationVisibility(updated) === "project") {
152942
+ queueClaimDerivation(updated);
152943
+ }
152262
152944
  }
152263
152945
  scheduleObservationEmbedding({
152264
- observationId: existing.id,
152265
- projectId: existing.projectId,
152946
+ observationId: updated.id,
152947
+ projectId: updated.projectId,
152266
152948
  searchableText: [input.title, input.narrative, ...input.facts ?? []].join(" "),
152267
152949
  doc
152268
152950
  });
152269
- return existing;
152951
+ return updated;
152270
152952
  }
152271
152953
  function getObservation(id, projectId) {
152272
152954
  return observations.find((o) => o.id === id && (projectId ? o.projectId === projectId : true));
@@ -152299,6 +152981,7 @@ async function updateObservationAdmission(input) {
152299
152981
  const next = apply(current);
152300
152982
  if (!next) return;
152301
152983
  await tx.update(next);
152984
+ await enqueueObservationProjectionWork(tx, next);
152302
152985
  updated = next;
152303
152986
  });
152304
152987
  } else {
@@ -152316,6 +152999,9 @@ async function updateObservationAdmission(input) {
152316
152999
  });
152317
153000
  } catch {
152318
153001
  }
153002
+ if (await persistEvidenceCard(updated)) {
153003
+ await acknowledgeObservationProjection(updated);
153004
+ }
152319
153005
  if (updated.admissionState === "qualified" && resolveObservationVisibility(updated) === "project") {
152320
153006
  queueClaimDerivation(updated);
152321
153007
  }
@@ -152386,10 +153072,17 @@ async function resolveObservations(ids, status = "resolved") {
152386
153072
  if (projectDir && resolved.length > 0) {
152387
153073
  const store = getObservationStore();
152388
153074
  await store.atomic(async (tx) => {
152389
- await Promise.all(changed.map((observation) => tx.update(observation)));
153075
+ await Promise.all(changed.map(async (observation) => {
153076
+ await tx.update(observation);
153077
+ await enqueueObservationProjectionWork(tx, observation);
153078
+ }));
152390
153079
  });
152391
153080
  }
152392
- for (const observation of changed) await persistEvidenceCard(observation);
153081
+ for (const observation of changed) {
153082
+ if (await persistEvidenceCard(observation)) {
153083
+ await acknowledgeObservationProjection(observation);
153084
+ }
153085
+ }
152393
153086
  return { resolved, notFound };
152394
153087
  }
152395
153088
  function getProjectObservations(projectId) {
@@ -152542,9 +153235,9 @@ async function prepareSearchIndex(options = {}) {
152542
153235
  for (const projectId of projects) {
152543
153236
  const projectObservations = await store.loadByProject(projectId);
152544
153237
  for (const observation of projectObservations) {
152545
- if (!persistedIds?.has(observation.id)) markVectorMissing(observation.id, observation.projectId);
153238
+ if (!persistedIds?.has(semanticVectorKey(observation.projectId, observation.id))) markVectorMissing(observation.id, observation.projectId);
152546
153239
  }
152547
- if (projectObservations.some((observation) => !persistedIds?.has(observation.id))) {
153240
+ if (projectObservations.some((observation) => !persistedIds?.has(semanticVectorKey(observation.projectId, observation.id)))) {
152548
153241
  queueVectorBackfill(projectId);
152549
153242
  }
152550
153243
  }
@@ -152566,7 +153259,7 @@ async function prepareSearchIndex(options = {}) {
152566
153259
  const persistedSemanticIds = await getPersistentSemanticVectorIds(hydratedProjectDir).catch(() => null);
152567
153260
  const projectsWithMissingVectors = /* @__PURE__ */ new Set();
152568
153261
  for (const obs of observations) {
152569
- if (!hasObservationVector(obs.projectId, obs.id) && !persistedSemanticIds?.has(obs.id)) {
153262
+ if (!hasObservationVector(obs.projectId, obs.id) && !persistedSemanticIds?.has(semanticVectorKey(obs.projectId, obs.id))) {
152570
153263
  markVectorMissing(obs.id, obs.projectId);
152571
153264
  projectsWithMissingVectors.add(obs.projectId);
152572
153265
  }
@@ -152610,7 +153303,7 @@ function getSearchIndexStatus(projectId) {
152610
153303
  };
152611
153304
  }
152612
153305
  async function probeSearchIndex(projectId) {
152613
- await searchObservations({
153306
+ const result = await searchObservationsDetailed({
152614
153307
  query: "semantic memory retrieval status",
152615
153308
  projectId,
152616
153309
  reader: { projectId },
@@ -152618,7 +153311,7 @@ async function probeSearchIndex(projectId) {
152618
153311
  status: "all",
152619
153312
  trackAccess: false
152620
153313
  });
152621
- return getLastSearchMode(projectId);
153314
+ return result.diagnostics.mode;
152622
153315
  }
152623
153316
  async function backfillVectorEmbeddings(options = {}) {
152624
153317
  if (vectorBackfillRunning) {
@@ -152770,6 +153463,7 @@ var init_observations = __esm({
152770
153463
  init_token_budget();
152771
153464
  init_entity_extractor();
152772
153465
  init_provider2();
153466
+ init_semantic_index();
152773
153467
  init_secret_filter();
152774
153468
  init_lifecycle();
152775
153469
  init_visibility();