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
@@ -193,6 +193,7 @@ function loadYamlConfig(projectRoot, options = {}) {
193
193
  llm: { ...userConfig.llm, ...projectConfig.llm },
194
194
  agent: { ...userConfig.agent, ...projectConfig.agent },
195
195
  embedding: { ...userConfig.embedding, ...projectConfig.embedding },
196
+ retrieval: { ...userConfig.retrieval, ...projectConfig.retrieval },
196
197
  rerank: { ...userConfig.rerank, ...projectConfig.rerank },
197
198
  git: { ...userConfig.git, ...projectConfig.git },
198
199
  codegraph: { ...userConfig.codegraph, ...projectConfig.codegraph },
@@ -1374,6 +1375,12 @@ CREATE TABLE IF NOT EXISTS maintenance_jobs (
1374
1375
  lease_owner TEXT,
1375
1376
  lease_expires_at INTEGER,
1376
1377
  last_error TEXT,
1378
+ attempted INTEGER NOT NULL DEFAULT 0,
1379
+ succeeded INTEGER NOT NULL DEFAULT 0,
1380
+ failed INTEGER NOT NULL DEFAULT 0,
1381
+ remaining INTEGER NOT NULL DEFAULT 0,
1382
+ progress_recorded INTEGER NOT NULL DEFAULT 0,
1383
+ rerun_requested INTEGER NOT NULL DEFAULT 0,
1377
1384
  created_at INTEGER NOT NULL,
1378
1385
  updated_at INTEGER NOT NULL,
1379
1386
  completed_at INTEGER
@@ -1794,6 +1801,22 @@ CREATE UNIQUE INDEX IF NOT EXISTS idx_maintenance_jobs_active_dedupe
1794
1801
  ON task_continuity_events(project_id, task_id, event_key)
1795
1802
  WHERE event_key IS NOT NULL`);
1796
1803
  }
1804
+ },
1805
+ {
1806
+ id: "1.11-maintenance-progress",
1807
+ apply: (db2) => {
1808
+ addColumnIfMissing(db2, "maintenance_jobs", "attempted", "attempted INTEGER NOT NULL DEFAULT 0");
1809
+ addColumnIfMissing(db2, "maintenance_jobs", "succeeded", "succeeded INTEGER NOT NULL DEFAULT 0");
1810
+ addColumnIfMissing(db2, "maintenance_jobs", "failed", "failed INTEGER NOT NULL DEFAULT 0");
1811
+ addColumnIfMissing(db2, "maintenance_jobs", "remaining", "remaining INTEGER NOT NULL DEFAULT 0");
1812
+ addColumnIfMissing(db2, "maintenance_jobs", "progress_recorded", "progress_recorded INTEGER NOT NULL DEFAULT 0");
1813
+ }
1814
+ },
1815
+ {
1816
+ id: "1.11-maintenance-rerun",
1817
+ apply: (db2) => {
1818
+ addColumnIfMissing(db2, "maintenance_jobs", "rerun_requested", "rerun_requested INTEGER NOT NULL DEFAULT 0");
1819
+ }
1797
1820
  }
1798
1821
  ];
1799
1822
  _dbCache = /* @__PURE__ */ new Map();
@@ -2273,6 +2296,7 @@ function mergeTomlConfig(base, override) {
2273
2296
  llm: { ...base.memory?.llm, ...override.memory?.llm }
2274
2297
  },
2275
2298
  embedding: { ...base.embedding, ...override.embedding },
2299
+ retrieval: { ...base.retrieval, ...override.retrieval },
2276
2300
  rerank: { ...base.rerank, ...override.rerank },
2277
2301
  hooks: { ...base.hooks, ...override.hooks },
2278
2302
  git: { ...base.git, ...override.git },
@@ -2362,6 +2386,32 @@ var init_toml_loader = __esm({
2362
2386
  }
2363
2387
  });
2364
2388
 
2389
+ // src/config/retrieval-strategy.ts
2390
+ function isCjkHeavyQuery(query) {
2391
+ if (!query) return false;
2392
+ const matches = query.match(CJK);
2393
+ return (matches?.length ?? 0) / query.length > 0.3;
2394
+ }
2395
+ function normalizeRetrievalStrategy(value) {
2396
+ if (value === "vector" || value === "hybrid") return value;
2397
+ return void 0;
2398
+ }
2399
+ function firstRetrievalStrategy(fallback, ...values) {
2400
+ for (const value of values) {
2401
+ const normalized = normalizeRetrievalStrategy(value);
2402
+ if (normalized) return normalized;
2403
+ }
2404
+ return fallback;
2405
+ }
2406
+ var CJK;
2407
+ var init_retrieval_strategy = __esm({
2408
+ "src/config/retrieval-strategy.ts"() {
2409
+ "use strict";
2410
+ init_esm_shims();
2411
+ CJK = /[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g;
2412
+ }
2413
+ });
2414
+
2365
2415
  // src/config/resolved-config.ts
2366
2416
  var resolved_config_exports = {};
2367
2417
  __export(resolved_config_exports, {
@@ -2471,6 +2521,10 @@ function getResolvedConfig(options = {}) {
2471
2521
  apiKey: first(process.env.MEMORIX_EMBEDDING_API_KEY, toml.embedding?.api_key, yaml.embedding?.apiKey, legacy.embeddingApi?.apiKey, openRouterEmbeddingApiKey, requestyEmbeddingApiKey),
2472
2522
  dimensions: firstNumber(parseNumber(process.env.MEMORIX_EMBEDDING_DIMENSIONS), toml.embedding?.dimensions, yaml.embedding?.dimensions, legacy.embeddingApi?.dimensions)
2473
2523
  },
2524
+ retrieval: {
2525
+ cjk: firstRetrievalStrategy("vector", process.env.MEMORIX_RETRIEVAL_CJK, toml.retrieval?.cjk, yaml.retrieval?.cjk),
2526
+ ascii: firstRetrievalStrategy("hybrid", process.env.MEMORIX_RETRIEVAL_ASCII, toml.retrieval?.ascii, yaml.retrieval?.ascii)
2527
+ },
2474
2528
  rerank: resolveRerankLane({
2475
2529
  toml,
2476
2530
  yaml,
@@ -2592,6 +2646,8 @@ function getEnvSourceNames() {
2592
2646
  "MEMORIX_EMBEDDING_BASE_URL",
2593
2647
  "MEMORIX_EMBEDDING_MODEL",
2594
2648
  "MEMORIX_EMBEDDING_DIMENSIONS",
2649
+ "MEMORIX_RETRIEVAL_CJK",
2650
+ "MEMORIX_RETRIEVAL_ASCII",
2595
2651
  "MEMORIX_RERANK_PROVIDER",
2596
2652
  "MEMORIX_RERANK_MODEL",
2597
2653
  "MEMORIX_RERANK_BASE_URL",
@@ -2700,6 +2756,7 @@ var init_resolved_config = __esm({
2700
2756
  init_toml_loader();
2701
2757
  init_yaml_loader();
2702
2758
  init_dotenv_loader();
2759
+ init_retrieval_strategy();
2703
2760
  }
2704
2761
  });
2705
2762
 
@@ -3094,6 +3151,96 @@ var init_transformers_provider = __esm({
3094
3151
  }
3095
3152
  });
3096
3153
 
3154
+ // src/embedding/ollama-embed.ts
3155
+ async function routeOllamaEmbedding(url, body, fetchImpl = fetch, probeOptions) {
3156
+ const parsed = parseUrl(url);
3157
+ if (!parsed) return { url, body, rewritten: false };
3158
+ const openAIRoute = parsed.pathname.endsWith("/v1/embeddings");
3159
+ const nativeRoute = parsed.pathname.endsWith("/api/embed");
3160
+ if (!openAIRoute && !nativeRoute) return { url, body, rewritten: false };
3161
+ if (!await originServesOllama(parsed.origin, fetchImpl, probeOptions)) return { url, body, rewritten: false };
3162
+ if (nativeRoute) return { url, body, rewritten: true };
3163
+ parsed.pathname = parsed.pathname.replace(/\/v1\/embeddings$/, "/api/embed");
3164
+ return { url: parsed.toString(), body: withEmbeddingKeepAlive(body), rewritten: true };
3165
+ }
3166
+ async function originServesOllama(origin, fetchImpl = fetch, probeOptions) {
3167
+ const cached = ollamaOrigins.get(origin);
3168
+ if (cached != null) return cached;
3169
+ if (probeOptions?.signal?.aborted) return false;
3170
+ try {
3171
+ const response = await fetchImpl(`${origin}/api/version`, {
3172
+ method: "GET",
3173
+ signal: buildProbeSignal(probeOptions)
3174
+ });
3175
+ if (!response.ok) {
3176
+ ollamaOrigins.set(origin, false);
3177
+ return false;
3178
+ }
3179
+ const detected = isOllamaVersionPayload(await response.json());
3180
+ ollamaOrigins.set(origin, detected);
3181
+ return detected;
3182
+ } catch (err) {
3183
+ if (isAbortError(err) || probeOptions?.signal?.aborted) return false;
3184
+ ollamaOrigins.set(origin, false);
3185
+ return false;
3186
+ }
3187
+ }
3188
+ function mapOllamaEmbeddingResponse(payload) {
3189
+ if (!payload || typeof payload !== "object") return payload;
3190
+ const record80 = payload;
3191
+ if (Array.isArray(record80.data) || !Array.isArray(record80.embeddings)) return payload;
3192
+ const embeddings = record80.embeddings.filter((item) => Array.isArray(item));
3193
+ return {
3194
+ ...record80,
3195
+ object: "list",
3196
+ data: embeddings.map((embedding, index) => ({
3197
+ object: "embedding",
3198
+ index,
3199
+ embedding
3200
+ }))
3201
+ };
3202
+ }
3203
+ function withEmbeddingKeepAlive(body) {
3204
+ if (body.keep_alive != null && body.keep_alive !== "") return body;
3205
+ return { ...body, keep_alive: OLLAMA_EMBED_KEEP_ALIVE };
3206
+ }
3207
+ function isOllamaVersionPayload(payload) {
3208
+ if (!payload || typeof payload !== "object") return false;
3209
+ const version = payload.version;
3210
+ return typeof version === "string" && /^\d+\.\d+\.\d+/.test(version);
3211
+ }
3212
+ function parseUrl(url) {
3213
+ try {
3214
+ return new URL(url);
3215
+ } catch {
3216
+ return null;
3217
+ }
3218
+ }
3219
+ function buildProbeSignal(probeOptions) {
3220
+ const timeoutMs = Math.max(
3221
+ 1,
3222
+ Math.min(
3223
+ typeof probeOptions?.probeTimeoutMs === "number" && Number.isFinite(probeOptions.probeTimeoutMs) ? Math.floor(probeOptions.probeTimeoutMs) : 1e3,
3224
+ 6e4
3225
+ )
3226
+ );
3227
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
3228
+ if (probeOptions?.signal) return AbortSignal.any([probeOptions.signal, timeoutSignal]);
3229
+ return timeoutSignal;
3230
+ }
3231
+ function isAbortError(err) {
3232
+ return err instanceof Error && err.name === "AbortError";
3233
+ }
3234
+ var OLLAMA_EMBED_KEEP_ALIVE, ollamaOrigins;
3235
+ var init_ollama_embed = __esm({
3236
+ "src/embedding/ollama-embed.ts"() {
3237
+ "use strict";
3238
+ init_esm_shims();
3239
+ OLLAMA_EMBED_KEEP_ALIVE = "5m";
3240
+ ollamaOrigins = /* @__PURE__ */ new Map();
3241
+ }
3242
+ });
3243
+
3097
3244
  // src/embedding/api-provider.ts
3098
3245
  var api_provider_exports = {};
3099
3246
  __export(api_provider_exports, {
@@ -3482,8 +3629,8 @@ async function loadCacheJsonl(filePath) {
3482
3629
  loaded = cache3.size;
3483
3630
  } catch {
3484
3631
  }
3485
- if (onDiskCount % 250 === 0) {
3486
- await new Promise((resolve2) => setImmediate(resolve2));
3632
+ if (onDiskCount % CACHE_LOAD_YIELD_EVERY === 0) {
3633
+ await new Promise((resolve2) => setTimeout(resolve2, 0));
3487
3634
  }
3488
3635
  }
3489
3636
  diskCacheEntryCount = onDiskCount;
@@ -3795,8 +3942,18 @@ function parseBatchLimit(error) {
3795
3942
  return null;
3796
3943
  }
3797
3944
  async function fetchWithRetry(url, apiKey, body, options = {}, attempt = 0, nativeGemini = false) {
3798
- const controller = new AbortController();
3799
3945
  const timeoutMs = typeof options.timeoutMs === "number" && Number.isFinite(options.timeoutMs) ? Math.max(100, Math.min(Math.floor(options.timeoutMs), 6e4)) : 1e4;
3946
+ let rewritten = false;
3947
+ if (!nativeGemini) {
3948
+ const routed = await routeOllamaEmbedding(url, body, fetch, {
3949
+ signal: options.signal,
3950
+ probeTimeoutMs: Math.min(1e3, timeoutMs)
3951
+ });
3952
+ url = routed.url;
3953
+ body = routed.body;
3954
+ rewritten = routed.rewritten;
3955
+ }
3956
+ const controller = new AbortController();
3800
3957
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
3801
3958
  const signal = options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal;
3802
3959
  let response;
@@ -3812,14 +3969,21 @@ async function fetchWithRetry(url, apiKey, body, options = {}, attempt = 0, nati
3812
3969
  if (err instanceof Error && (err.name === "AbortError" || controller.signal.aborted || options.signal?.aborted)) {
3813
3970
  throw new Error(`Embedding API timeout after ${timeoutMs}ms: ${url}`);
3814
3971
  }
3972
+ if (options.retry !== false && attempt < MAX_RETRIES2) {
3973
+ const delay3 = BASE_DELAY_MS * Math.pow(2, attempt);
3974
+ console.error(`[memorix] Embedding transport failure, retry ${attempt + 1}/${MAX_RETRIES2} in ${delay3}ms`);
3975
+ await waitForRetry(delay3, options.signal);
3976
+ return fetchWithRetry(url, apiKey, body, options, attempt + 1, nativeGemini);
3977
+ }
3815
3978
  throw err;
3816
3979
  }
3817
3980
  try {
3818
3981
  if (response.ok) {
3819
- return await raceWithAbort(
3982
+ const payload = await raceWithAbort(
3820
3983
  response.json(),
3821
3984
  signal
3822
3985
  );
3986
+ return rewritten ? mapOllamaEmbeddingResponse(payload) : payload;
3823
3987
  }
3824
3988
  if (options.retry !== false && (response.status === 429 || response.status >= 500) && attempt < MAX_RETRIES2) {
3825
3989
  const delay3 = BASE_DELAY_MS * Math.pow(2, attempt);
@@ -3890,12 +4054,13 @@ async function waitForRetry(waitMs, signal) {
3890
4054
  abortSignal.addEventListener("abort", onAbort, { once: true });
3891
4055
  });
3892
4056
  }
3893
- 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;
4057
+ 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;
3894
4058
  var init_api_provider = __esm({
3895
4059
  "src/embedding/api-provider.ts"() {
3896
4060
  "use strict";
3897
4061
  init_esm_shims();
3898
4062
  init_provider();
4063
+ init_ollama_embed();
3899
4064
  cache3 = /* @__PURE__ */ new Map();
3900
4065
  MAX_CACHE_ENTRIES = 2e5;
3901
4066
  MAX_CACHE_PAYLOAD_BYTES = 256 * 1024 * 1024;
@@ -3918,6 +4083,7 @@ var init_api_provider = __esm({
3918
4083
  DASHSCOPE_MAX_BATCH_SIZE = 10;
3919
4084
  MAX_RETRIES2 = 3;
3920
4085
  BASE_DELAY_MS = 500;
4086
+ CACHE_LOAD_YIELD_EVERY = 32;
3921
4087
  EmbeddingAPIError = class extends Error {
3922
4088
  status;
3923
4089
  constructor(status, detail) {
@@ -3969,7 +4135,7 @@ var init_api_provider = __esm({
3969
4135
  console.error(`[memorix] Dimension shortening: ${config.requestedDimensions}d requested`);
3970
4136
  }
3971
4137
  if (allowNetworkProbe) {
3972
- startDiskCacheLoad();
4138
+ setImmediate(startDiskCacheLoad);
3973
4139
  }
3974
4140
  return new _APIEmbeddingProvider(config, probeDimensions);
3975
4141
  }
@@ -4041,10 +4207,8 @@ var init_api_provider = __esm({
4041
4207
  return this.embedInput({ modality: "text", text: normalized }, { intent: "document", ...options });
4042
4208
  }
4043
4209
  const hash4 = textHash2(normalized, this.cacheKeyNamespace);
4044
- if (diskCacheLoaded) {
4045
- const cached = cache3.get(hash4);
4046
- if (cached) return cached;
4047
- }
4210
+ const cached = cache3.get(hash4);
4211
+ if (cached) return cached;
4048
4212
  const apiCall = async () => {
4049
4213
  const body = {
4050
4214
  model: this.config.model,
@@ -4069,8 +4233,8 @@ var init_api_provider = __esm({
4069
4233
  let embedding;
4070
4234
  if (!diskCacheLoaded && diskCacheLoadPromise) {
4071
4235
  const cacheRace = diskCacheLoadPromise.then(() => {
4072
- const cached = cache3.get(hash4);
4073
- if (cached) return cached;
4236
+ const cached2 = cache3.get(hash4);
4237
+ if (cached2) return cached2;
4074
4238
  return null;
4075
4239
  });
4076
4240
  const result = await Promise.race([
@@ -5776,6 +5940,7 @@ var sqlite_store_exports = {};
5776
5940
  __export(sqlite_store_exports, {
5777
5941
  SqliteBackend: () => SqliteBackend
5778
5942
  });
5943
+ import { randomUUID as randomUUID2 } from "crypto";
5779
5944
  import path7 from "path";
5780
5945
  import fs4 from "fs";
5781
5946
  function obsToRow(obs) {
@@ -6164,6 +6329,32 @@ var init_sqlite_store = __esm({
6164
6329
  }, "Observation atomic write");
6165
6330
  try {
6166
6331
  const tx = {
6332
+ enqueueMaintenanceJob: async (input) => {
6333
+ const payloadJson = JSON.stringify(input.payload ?? {});
6334
+ const existing = this.db.prepare(`
6335
+ SELECT id, status FROM maintenance_jobs
6336
+ WHERE project_id = ? AND kind = ? AND dedupe_key = ?
6337
+ AND status IN ('pending', 'running', 'retry')
6338
+ LIMIT 1
6339
+ `).get(input.projectId, input.kind, input.dedupeKey);
6340
+ if (existing) {
6341
+ if (existing.status === "running") {
6342
+ this.db.prepare(`
6343
+ UPDATE maintenance_jobs
6344
+ SET rerun_requested = 1, payload_json = ?, updated_at = ?
6345
+ WHERE id = ?
6346
+ `).run(payloadJson, Date.now(), existing.id);
6347
+ }
6348
+ return;
6349
+ }
6350
+ const now3 = Date.now();
6351
+ this.db.prepare(`
6352
+ INSERT INTO maintenance_jobs (
6353
+ id, project_id, kind, dedupe_key, payload_json, status, attempts,
6354
+ max_attempts, run_after, created_at, updated_at
6355
+ ) VALUES (?, ?, ?, ?, ?, 'pending', 0, 8, ?, ?, ?)
6356
+ `).run(randomUUID2(), input.projectId, input.kind, input.dedupeKey, payloadJson, now3, now3, now3);
6357
+ },
6167
6358
  loadAll: async () => this.rawLoadAll(),
6168
6359
  getById: async (id) => this.rawGetById(id),
6169
6360
  findByTopicKey: async (projectId, topicKey) => this.rawFindByTopicKey(projectId, topicKey),
@@ -6234,6 +6425,7 @@ __export(obs_store_exports, {
6234
6425
  DegradedBackend: () => DegradedBackend,
6235
6426
  createObservationStore: () => createObservationStore,
6236
6427
  getObservationStore: () => getObservationStore,
6428
+ getObservationStoreDataDir: () => getObservationStoreDataDir,
6237
6429
  initObservationStore: () => initObservationStore,
6238
6430
  resetObservationStore: () => resetObservationStore,
6239
6431
  setObservationStore: () => setObservationStore
@@ -6244,6 +6436,12 @@ function getObservationStore() {
6244
6436
  }
6245
6437
  return _store2;
6246
6438
  }
6439
+ function getObservationStoreDataDir() {
6440
+ if (!_store2 || !_storeDataDir) {
6441
+ throw new Error("[memorix] ObservationStore data directory is not bound");
6442
+ }
6443
+ return _storeDataDir;
6444
+ }
6247
6445
  function setObservationStore(store) {
6248
6446
  _store2 = store;
6249
6447
  }
@@ -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,
@@ -9491,7 +10017,7 @@ var init_maintenance_targets = __esm({
9491
10017
  });
9492
10018
 
9493
10019
  // src/knowledge/workspace-store.ts
9494
- import { randomUUID as randomUUID4 } from "crypto";
10020
+ import { randomUUID as randomUUID5 } from "crypto";
9495
10021
  function arrayValue(raw) {
9496
10022
  if (typeof raw !== "string" || !raw) return [];
9497
10023
  try {
@@ -9632,7 +10158,7 @@ var init_workspace_store = __esm({
9632
10158
  }
9633
10159
  createProposal(input) {
9634
10160
  const proposal = {
9635
- id: input.id ?? randomUUID4(),
10161
+ id: input.id ?? randomUUID5(),
9636
10162
  ...input,
9637
10163
  status: input.status ?? "pending",
9638
10164
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
@@ -9918,11 +10444,11 @@ __export(consolidation_exports, {
9918
10444
  });
9919
10445
  function tokenize(text2) {
9920
10446
  return new Set(
9921
- text2.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff\s-]/g, " ").split(/\s+/).filter((t2) => t2.length > 1)
10447
+ text2.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, " ").split(/\s+/).filter((t2) => t2.length > 1)
9922
10448
  );
9923
10449
  }
9924
10450
  function jaccardSimilarity(a, b) {
9925
- if (a.size === 0 && b.size === 0) return 1;
10451
+ if (a.size === 0 && b.size === 0) return 0;
9926
10452
  let intersection = 0;
9927
10453
  for (const token of a) {
9928
10454
  if (b.has(token)) intersection++;
@@ -10288,7 +10814,7 @@ Respond in JSON only:
10288
10814
  });
10289
10815
 
10290
10816
  // src/media/media-store.ts
10291
- import { randomUUID as randomUUID5 } from "crypto";
10817
+ import { randomUUID as randomUUID6 } from "crypto";
10292
10818
  function asOptionalText(value) {
10293
10819
  return typeof value === "string" && value.length > 0 ? value : void 0;
10294
10820
  }
@@ -10458,7 +10984,7 @@ var init_media_store = __esm({
10458
10984
  return { asset: this.getAsset(input.projectId, existing.id), deduplicated: true };
10459
10985
  }
10460
10986
  const asset = {
10461
- id: randomUUID5(),
10987
+ id: randomUUID6(),
10462
10988
  ...input,
10463
10989
  createdAt: now3,
10464
10990
  updatedAt: now3
@@ -10538,7 +11064,7 @@ var init_media_store = __esm({
10538
11064
  `).get(input.assetId, input.observationId ?? null, input.role);
10539
11065
  if (existing) return rowToLink(existing);
10540
11066
  const link = {
10541
- id: randomUUID5(),
11067
+ id: randomUUID6(),
10542
11068
  assetId: input.assetId,
10543
11069
  projectId: input.projectId,
10544
11070
  ...input.observationId !== void 0 ? { observationId: input.observationId } : {},
@@ -10577,7 +11103,7 @@ var init_media_store = __esm({
10577
11103
  return rowToDerivation(this.db.prepare("SELECT * FROM media_derivations WHERE id = ?").get(existing.id));
10578
11104
  }
10579
11105
  const derivation = {
10580
- id: randomUUID5(),
11106
+ id: randomUUID6(),
10581
11107
  ...input,
10582
11108
  content,
10583
11109
  ...error ? { error } : {},
@@ -10664,7 +11190,7 @@ var init_media_store = __esm({
10664
11190
  createJob(input) {
10665
11191
  const now3 = Date.now();
10666
11192
  const job = {
10667
- id: randomUUID5(),
11193
+ id: randomUUID6(),
10668
11194
  projectId: input.projectId,
10669
11195
  kind: input.kind,
10670
11196
  status: "queued",
@@ -10826,7 +11352,7 @@ var init_types2 = __esm({
10826
11352
  });
10827
11353
 
10828
11354
  // src/media/asset-store.ts
10829
- import { createHash as createHash7, randomUUID as randomUUID6 } from "crypto";
11355
+ import { createHash as createHash7, randomUUID as randomUUID7 } from "crypto";
10830
11356
  import { copyFile, lstat, mkdir as mkdir3, open, readFile as readFile3, readdir, rename as rename2, rm, stat as stat2, writeFile as writeFile3 } from "fs/promises";
10831
11357
  import path11 from "path";
10832
11358
  function mediaRoot(dataDir) {
@@ -10897,7 +11423,7 @@ async function destinationExists(destination) {
10897
11423
  async function persistBuffer(bytes, destination) {
10898
11424
  await mkdir3(path11.dirname(destination), { recursive: true });
10899
11425
  if (await destinationExists(destination)) return false;
10900
- const temporary = `${destination}.${randomUUID6()}.tmp`;
11426
+ const temporary = `${destination}.${randomUUID7()}.tmp`;
10901
11427
  try {
10902
11428
  await writeFile3(temporary, bytes, { flag: "wx" });
10903
11429
  await rename2(temporary, destination);
@@ -19202,7 +19728,7 @@ var init_uuid = __esm({
19202
19728
  });
19203
19729
 
19204
19730
  // node_modules/openai/internal/errors.mjs
19205
- function isAbortError(err) {
19731
+ function isAbortError2(err) {
19206
19732
  return typeof err === "object" && err !== null && // Spec-compliant fetch implementations
19207
19733
  ("name" in err && err.name === "AbortError" || // Expo fetch
19208
19734
  "message" in err && String(err.message).includes("FetchRequestCanceledException"));
@@ -20382,7 +20908,7 @@ var init_streaming = __esm({
20382
20908
  }
20383
20909
  done = true;
20384
20910
  } catch (e2) {
20385
- if (isAbortError(e2))
20911
+ if (isAbortError2(e2))
20386
20912
  return;
20387
20913
  throw e2;
20388
20914
  } finally {
@@ -20425,7 +20951,7 @@ var init_streaming = __esm({
20425
20951
  }
20426
20952
  done = true;
20427
20953
  } catch (e2) {
20428
- if (isAbortError(e2))
20954
+ if (isAbortError2(e2))
20429
20955
  return;
20430
20956
  throw e2;
20431
20957
  } finally {
@@ -26974,7 +27500,7 @@ var init_client = __esm({
26974
27500
  if (options.signal?.aborted) {
26975
27501
  throw new APIUserAbortError();
26976
27502
  }
26977
- const isTimeout = isAbortError(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
27503
+ const isTimeout = isAbortError2(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
26978
27504
  if (retriesRemaining) {
26979
27505
  loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
26980
27506
  loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails({
@@ -46063,7 +46589,7 @@ var init_uuid2 = __esm({
46063
46589
  });
46064
46590
 
46065
46591
  // node_modules/@anthropic-ai/sdk/internal/errors.mjs
46066
- function isAbortError2(err) {
46592
+ function isAbortError3(err) {
46067
46593
  return typeof err === "object" && err !== null && // Spec-compliant fetch implementations
46068
46594
  ("name" in err && err.name === "AbortError" || // Expo fetch
46069
46595
  "message" in err && String(err.message).includes("FetchRequestCanceledException"));
@@ -46834,7 +47360,7 @@ var init_streaming3 = __esm({
46834
47360
  }
46835
47361
  done = true;
46836
47362
  } catch (e2) {
46837
- if (isAbortError2(e2))
47363
+ if (isAbortError3(e2))
46838
47364
  return;
46839
47365
  throw e2;
46840
47366
  } finally {
@@ -46877,7 +47403,7 @@ var init_streaming3 = __esm({
46877
47403
  }
46878
47404
  done = true;
46879
47405
  } catch (e2) {
46880
- if (isAbortError2(e2))
47406
+ if (isAbortError3(e2))
46881
47407
  return;
46882
47408
  throw e2;
46883
47409
  } finally {
@@ -48999,7 +49525,7 @@ var init_BetaMessageStream = __esm({
48999
49525
  _BetaMessageStream_logger.set(this, void 0);
49000
49526
  _BetaMessageStream_handleError.set(this, (error) => {
49001
49527
  __classPrivateFieldSet2(this, _BetaMessageStream_errored, true, "f");
49002
- if (isAbortError2(error)) {
49528
+ if (isAbortError3(error)) {
49003
49529
  error = new APIUserAbortError2();
49004
49530
  }
49005
49531
  if (error instanceof APIUserAbortError2) {
@@ -51460,7 +51986,7 @@ var init_MessageStream = __esm({
51460
51986
  _MessageStream_logger.set(this, void 0);
51461
51987
  _MessageStream_handleError.set(this, (error) => {
51462
51988
  __classPrivateFieldSet2(this, _MessageStream_errored, true, "f");
51463
- if (isAbortError2(error)) {
51989
+ if (isAbortError3(error)) {
51464
51990
  error = new APIUserAbortError2();
51465
51991
  }
51466
51992
  if (error instanceof APIUserAbortError2) {
@@ -52590,7 +53116,7 @@ var init_client2 = __esm({
52590
53116
  if (options.signal?.aborted) {
52591
53117
  throw new APIUserAbortError2();
52592
53118
  }
52593
- const isTimeout = isAbortError2(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
53119
+ const isTimeout = isAbortError3(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
52594
53120
  if (retriesRemaining) {
52595
53121
  loggerFor2(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
52596
53122
  loggerFor2(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails2({
@@ -63799,7 +64325,7 @@ var require_gaxios = __commonJS({
63799
64325
  var retry_js_1 = require_retry3();
63800
64326
  var stream_1 = __require("stream");
63801
64327
  var interceptor_js_1 = require_interceptor();
63802
- var randomUUID16 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
64328
+ var randomUUID17 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
63803
64329
  var HTTP_STATUS_NO_CONTENT = 204;
63804
64330
  var Gaxios = class {
63805
64331
  agentCache = /* @__PURE__ */ new Map();
@@ -64072,7 +64598,7 @@ var require_gaxios = __commonJS({
64072
64598
  */
64073
64599
  ["Blob", "File", "FormData"].includes(opts.data?.constructor?.name || "");
64074
64600
  if (opts.multipart?.length) {
64075
- const boundary = await randomUUID16();
64601
+ const boundary = await randomUUID17();
64076
64602
  preparedHeaders.set("content-type", `multipart/related; boundary=${boundary}`);
64077
64603
  opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary));
64078
64604
  } else if (shouldDirectlyPassData) {
@@ -87098,7 +87624,7 @@ function listDocumentsResponseFromMldev(fromObject) {
87098
87624
  }
87099
87625
  return toObject;
87100
87626
  }
87101
- function isAbortError3(err) {
87627
+ function isAbortError4(err) {
87102
87628
  return typeof err === "object" && err !== null && // Spec-compliant fetch implementations
87103
87629
  ("name" in err && err.name === "AbortError" || // Expo fetch
87104
87630
  "message" in err && String(err.message).includes("FetchRequestCanceledException"));
@@ -94312,7 +94838,7 @@ ${underline}`);
94312
94838
  }
94313
94839
  done = true;
94314
94840
  } catch (e2) {
94315
- if (isAbortError3(e2))
94841
+ if (isAbortError4(e2))
94316
94842
  return yield __await(void 0);
94317
94843
  throw e2;
94318
94844
  } finally {
@@ -94387,7 +94913,7 @@ ${underline}`);
94387
94913
  }
94388
94914
  done = true;
94389
94915
  } catch (e2) {
94390
- if (isAbortError3(e2))
94916
+ if (isAbortError4(e2))
94391
94917
  return yield __await(void 0);
94392
94918
  throw e2;
94393
94919
  } finally {
@@ -94763,7 +95289,7 @@ ${underline}`);
94763
95289
  if ((_d = options.signal) === null || _d === void 0 ? void 0 : _d.aborted) {
94764
95290
  throw new APIUserAbortError3();
94765
95291
  }
94766
- const isTimeout = isAbortError3(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
95292
+ const isTimeout = isAbortError4(response) || /timed? ?out/i.test(String(response) + ("cause" in response ? String(response.cause) : ""));
94767
95293
  if (retriesRemaining) {
94768
95294
  loggerFor3(this).info(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} - ${retryMessage}`);
94769
95295
  loggerFor3(this).debug(`[${requestLogID}] connection ${isTimeout ? "timed out" : "failed"} (${retryMessage})`, formatRequestDetails3({
@@ -96987,7 +97513,7 @@ function isTimeoutError(err) {
96987
97513
  const isGenericErr = "code" in err && typeof err.code === "string" && err.code.toLowerCase() === "econnaborted";
96988
97514
  return isNative || isLegacyNative || isGenericErr;
96989
97515
  }
96990
- function isAbortError4(err) {
97516
+ function isAbortError5(err) {
96991
97517
  if (typeof err !== "object" || err == null) {
96992
97518
  return false;
96993
97519
  }
@@ -97999,7 +98525,7 @@ var init_sdks = __esm({
97999
98525
  return response;
98000
98526
  }, { config: options.retryConfig, statusCodes: options.retryCodes }).then((r2) => OK(r2), (err) => {
98001
98527
  switch (true) {
98002
- case isAbortError4(err):
98528
+ case isAbortError5(err):
98003
98529
  return ERR(new RequestAbortedError("Request aborted by client", {
98004
98530
  cause: err
98005
98531
  }));
@@ -144827,14 +145353,23 @@ var init_audio_jobs = __esm({
144827
145353
  }
144828
145354
  });
144829
145355
 
144830
- // src/memory/feedback-model.ts
145356
+ // src/core/retrieval-policy.ts
144831
145357
  function feedbackWeightMultiplier(weight) {
144832
145358
  return Math.max(0.35, Math.min(1.4, 0.35 + Math.max(0, Math.min(2, weight)) * 0.525));
144833
145359
  }
145360
+ var init_retrieval_policy = __esm({
145361
+ "src/core/retrieval-policy.ts"() {
145362
+ "use strict";
145363
+ init_esm_shims();
145364
+ }
145365
+ });
145366
+
145367
+ // src/memory/feedback-model.ts
144834
145368
  var init_feedback_model = __esm({
144835
145369
  "src/memory/feedback-model.ts"() {
144836
145370
  "use strict";
144837
145371
  init_esm_shims();
145372
+ init_retrieval_policy();
144838
145373
  }
144839
145374
  });
144840
145375
 
@@ -144846,7 +145381,7 @@ __export(feedback_exports, {
144846
145381
  applyMemoryFeedback: () => applyMemoryFeedback,
144847
145382
  feedbackWeightMultiplier: () => feedbackWeightMultiplier
144848
145383
  });
144849
- import { randomUUID as randomUUID7 } from "crypto";
145384
+ import { randomUUID as randomUUID8 } from "crypto";
144850
145385
  function applyMemoryFeedback(current, event) {
144851
145386
  const delta = event.signal === "revoke" ? 0 : FEEDBACK_DELTAS[event.signal];
144852
145387
  const weight = Math.max(0, Math.min(2, current.weight + delta));
@@ -144964,7 +145499,7 @@ var init_feedback = __esm({
144964
145499
  if (!target) throw new Error("The feedback event to revoke was not found in the same candidate scope.");
144965
145500
  }
144966
145501
  const event = {
144967
- id: randomUUID7(),
145502
+ id: randomUUID8(),
144968
145503
  projectId: input.projectId,
144969
145504
  candidateKind: input.candidateKind,
144970
145505
  candidateId: input.candidateId,
@@ -145352,7 +145887,7 @@ var init_retention = __esm({
145352
145887
  });
145353
145888
 
145354
145889
  // src/memory/owner.ts
145355
- import { randomUUID as randomUUID8 } from "crypto";
145890
+ import { randomUUID as randomUUID9 } from "crypto";
145356
145891
  import { promises as fs9 } from "fs";
145357
145892
  import path17 from "path";
145358
145893
  function ownerPath(dataDir) {
@@ -145382,7 +145917,7 @@ async function resolveLocalMemoryOwner(dataDir, options = {}) {
145382
145917
  await fs9.mkdir(path17.dirname(filePath), { recursive: true });
145383
145918
  const created = {
145384
145919
  version: 1,
145385
- id: "local-" + randomUUID8(),
145920
+ id: "local-" + randomUUID9(),
145386
145921
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
145387
145922
  };
145388
145923
  try {
@@ -145405,7 +145940,7 @@ var init_owner = __esm({
145405
145940
  });
145406
145941
 
145407
145942
  // src/memory/long-term-store.ts
145408
- import { randomUUID as randomUUID9 } from "crypto";
145943
+ import { randomUUID as randomUUID10 } from "crypto";
145409
145944
  function optionalText2(value) {
145410
145945
  return typeof value === "string" && value.trim() ? value : void 0;
145411
145946
  }
@@ -145565,7 +146100,7 @@ var init_long_term_store = __esm({
145565
146100
  }
145566
146101
  insertEvidence(input) {
145567
146102
  const evidence = {
145568
- id: randomUUID9(),
146103
+ id: randomUUID10(),
145569
146104
  ...input,
145570
146105
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
145571
146106
  };
@@ -145592,7 +146127,7 @@ var init_long_term_store = __esm({
145592
146127
  }
145593
146128
  recordEvent(input) {
145594
146129
  const event = {
145595
- id: randomUUID9(),
146130
+ id: randomUUID10(),
145596
146131
  ...input,
145597
146132
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
145598
146133
  };
@@ -145682,7 +146217,7 @@ __export(long_term_exports, {
145682
146217
  selectLongTermMemoriesForTask: () => selectLongTermMemoriesForTask,
145683
146218
  supersedeLongTermMemory: () => supersedeLongTermMemory
145684
146219
  });
145685
- import { randomUUID as randomUUID10 } from "crypto";
146220
+ import { randomUUID as randomUUID11 } from "crypto";
145686
146221
  function isOneOf(value, values) {
145687
146222
  return typeof value === "string" && values.includes(value);
145688
146223
  }
@@ -145864,7 +146399,7 @@ async function createManualLongTermMemory(input) {
145864
146399
  const owner = await resolveLocalMemoryOwner(input.dataDir, { create: true });
145865
146400
  if (!owner) throw new Error("Memorix could not resolve a local memory owner.");
145866
146401
  assertScope(input.scope);
145867
- const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID10(), relation: "supports" }];
146402
+ const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID11(), relation: "supports" }];
145868
146403
  return createLongTermMemoryWithDataDir({
145869
146404
  dataDir: input.dataDir,
145870
146405
  originProjectId: input.projectId,
@@ -145919,7 +146454,7 @@ async function createLongTermMemoryWithDataDir(input) {
145919
146454
  assertPortableEvidence(input.scope, portability, evidenceInputs);
145920
146455
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
145921
146456
  const memory = {
145922
- id: randomUUID10(),
146457
+ id: randomUUID11(),
145923
146458
  originProjectId: compactText(input.originProjectId, "origin project id", 1e3),
145924
146459
  ownerId: compactText(input.ownerId, "owner id", 160),
145925
146460
  scope: input.scope,
@@ -146274,7 +146809,7 @@ var store_exports = {};
146274
146809
  __export(store_exports, {
146275
146810
  CodeGraphStore: () => CodeGraphStore
146276
146811
  });
146277
- import { randomUUID as randomUUID11 } from "crypto";
146812
+ import { randomUUID as randomUUID12 } from "crypto";
146278
146813
  import { posix as pathPosix } from "path";
146279
146814
  function rowToFile(row) {
146280
146815
  return {
@@ -147203,7 +147738,7 @@ var init_store = __esm({
147203
147738
  * so an interrupted scan cannot be advertised as complete.
147204
147739
  */
147205
147740
  recordCodeStateSnapshot(input) {
147206
- const id = randomUUID11();
147741
+ const id = randomUUID12();
147207
147742
  let snapshot;
147208
147743
  let compactNeeded = false;
147209
147744
  const tx = this.db.transaction(() => {
@@ -148436,7 +148971,7 @@ var claim_store_exports = {};
148436
148971
  __export(claim_store_exports, {
148437
148972
  ClaimStore: () => ClaimStore
148438
148973
  });
148439
- import { createHash as createHash12, randomUUID as randomUUID12 } from "crypto";
148974
+ import { createHash as createHash12, randomUUID as randomUUID13 } from "crypto";
148440
148975
  function optionalText3(value) {
148441
148976
  return typeof value === "string" && value ? value : void 0;
148442
148977
  }
@@ -148620,7 +149155,7 @@ var init_claim_store = __esm({
148620
149155
  locator, capturedHash, evidenceKey, createdAt
148621
149156
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
148622
149157
  `).run(
148623
- randomUUID12(),
149158
+ randomUUID13(),
148624
149159
  input.claimId,
148625
149160
  input.evidenceKind,
148626
149161
  input.evidenceId,
@@ -148642,7 +149177,7 @@ var init_claim_store = __esm({
148642
149177
  }
148643
149178
  recordEvent(input) {
148644
149179
  const event = {
148645
- id: randomUUID12(),
149180
+ id: randomUUID13(),
148646
149181
  ...input,
148647
149182
  ...input.detail ? { detail: sanitizeCredentials(input.detail) } : {},
148648
149183
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
@@ -148687,7 +149222,7 @@ __export(claims_exports, {
148687
149222
  supersedeClaim: () => supersedeClaim,
148688
149223
  writeClaim: () => writeClaim
148689
149224
  });
148690
- import { createHash as createHash13, randomUUID as randomUUID13 } from "crypto";
149225
+ import { createHash as createHash13, randomUUID as randomUUID14 } from "crypto";
148691
149226
  function compactText2(value, field) {
148692
149227
  if (typeof value !== "string") throw new Error("Claim " + field + " must be text");
148693
149228
  const sanitized = sanitizeCredentials(value).trim().replace(/\s+/g, " ");
@@ -148773,7 +149308,7 @@ function normalizeClaimInput(input) {
148773
149308
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
148774
149309
  return {
148775
149310
  claim: {
148776
- id: randomUUID13(),
149311
+ id: randomUUID14(),
148777
149312
  projectId,
148778
149313
  subject,
148779
149314
  predicate,
@@ -149858,7 +150393,7 @@ var init_workflow_sync = __esm({
149858
150393
  });
149859
150394
 
149860
150395
  // src/knowledge/workflow-store.ts
149861
- import { randomUUID as randomUUID14 } from "crypto";
150396
+ import { randomUUID as randomUUID15 } from "crypto";
149862
150397
  function parseJson(value, fallback) {
149863
150398
  if (typeof value !== "string" || !value) return fallback;
149864
150399
  try {
@@ -149958,7 +150493,7 @@ var init_workflow_store = __esm({
149958
150493
  }
149959
150494
  recordRun(input) {
149960
150495
  const run = {
149961
- id: randomUUID14(),
150496
+ id: randomUUID15(),
149962
150497
  workflowId: input.workflowId,
149963
150498
  projectId: input.projectId,
149964
150499
  task: input.task.trim(),
@@ -150026,7 +150561,7 @@ var init_outcome_types = __esm({
150026
150561
  });
150027
150562
 
150028
150563
  // src/knowledge/outcome-store.ts
150029
- import { randomUUID as randomUUID15 } from "crypto";
150564
+ import { randomUUID as randomUUID16 } from "crypto";
150030
150565
  function optionalText5(value) {
150031
150566
  return typeof value === "string" && value.trim() ? value : void 0;
150032
150567
  }
@@ -150070,7 +150605,7 @@ var init_outcome_store = __esm({
150070
150605
  }
150071
150606
  record(input) {
150072
150607
  const signal = {
150073
- id: randomUUID15(),
150608
+ id: randomUUID16(),
150074
150609
  projectId: text(input.projectId, "project id"),
150075
150610
  candidateKind: oneOf(input.candidateKind, MEMORY_OUTCOME_CANDIDATE_KINDS, "candidate kind"),
150076
150611
  candidateId: text(input.candidateId, "candidate id"),
@@ -150904,6 +151439,15 @@ function observationId(payload) {
150904
151439
  const value = payload.observationId;
150905
151440
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
150906
151441
  }
151442
+ async function automaticCleanupEnabled(projectRoot) {
151443
+ if (!projectRoot) return true;
151444
+ try {
151445
+ const { getResolvedConfig: getResolvedConfig2 } = await Promise.resolve().then(() => (init_resolved_config(), resolved_config_exports));
151446
+ return getResolvedConfig2({ projectRoot }).memory.autoCleanup !== false;
151447
+ } catch {
151448
+ return true;
151449
+ }
151450
+ }
150907
151451
  function workspaceMode(payload) {
150908
151452
  return payload.workspaceMode === "local" || payload.workspaceMode === "versioned" ? payload.workspaceMode : void 0;
150909
151453
  }
@@ -150992,6 +151536,9 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
150992
151536
  if (job.projectId !== projectId) {
150993
151537
  return { action: "reschedule", delayMs: VECTOR_RETRY_DELAY_MS };
150994
151538
  }
151539
+ if ((job.kind === "retention-archive" || job.kind === "consolidation" || job.kind === "long-term-maintenance") && !await automaticCleanupEnabled(projectRoot)) {
151540
+ return { action: "complete" };
151541
+ }
150995
151542
  if (job.kind === "media-video-generation") {
150996
151543
  const { runMiniMaxVideoGenerationJob: runMiniMaxVideoGenerationJob2 } = await Promise.resolve().then(() => (init_video_jobs(), video_jobs_exports));
150997
151544
  return runMiniMaxVideoGenerationJob2(job, { dataDir: projectDir2, projectId });
@@ -151084,6 +151631,33 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
151084
151631
  });
151085
151632
  return { action: "complete" };
151086
151633
  }
151634
+ if (job.kind === "observation-project") {
151635
+ if (!projectRoot) {
151636
+ throw new Error(`Observation projection requires a project root for ${projectId}`);
151637
+ }
151638
+ const id = observationId(job.payload);
151639
+ if (!id) return { action: "complete" };
151640
+ const [
151641
+ { CodeGraphStore: CodeGraphStore2 },
151642
+ { bindObservationToCode: bindObservationToCode2 },
151643
+ { EvidenceCardStore: EvidenceCardStore2 },
151644
+ { getObservationStore: getObservationStore2 }
151645
+ ] = await Promise.all([
151646
+ Promise.resolve().then(() => (init_store(), store_exports)),
151647
+ Promise.resolve().then(() => (init_binder(), binder_exports)),
151648
+ Promise.resolve().then(() => (init_evidence_store(), evidence_store_exports)),
151649
+ Promise.resolve().then(() => (init_obs_store(), obs_store_exports))
151650
+ ]);
151651
+ const observation = await getObservationStore2().getById(id);
151652
+ if (!observation || observation.projectId !== projectId) return { action: "complete" };
151653
+ const codeStore = new CodeGraphStore2();
151654
+ await codeStore.init(projectDir2);
151655
+ await bindObservationToCode2(codeStore, observation);
151656
+ const evidence = new EvidenceCardStore2();
151657
+ await evidence.init(projectDir2);
151658
+ evidence.upsertObservation(observation);
151659
+ return { action: "complete" };
151660
+ }
151087
151661
  if (job.kind === "observation-qualify") {
151088
151662
  const [
151089
151663
  { CodeGraphStore: CodeGraphStore2 },
@@ -151291,7 +151865,15 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
151291
151865
  const after = getVectorStatus2(projectId);
151292
151866
  if (after.missing === 0) {
151293
151867
  resolveSupersededVectorFailures(projectDir2, projectId);
151294
- return { action: "complete" };
151868
+ return {
151869
+ action: "complete",
151870
+ progress: {
151871
+ attempted: result.attempted,
151872
+ succeeded: result.succeeded,
151873
+ failed: result.failed,
151874
+ remaining: 0
151875
+ }
151876
+ };
151295
151877
  }
151296
151878
  if (result.failed > 0 && result.succeeded === 0) {
151297
151879
  const streak = vectorBackfillFailureStreak(job.payload) + 1;
@@ -151306,6 +151888,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
151306
151888
  ...job.payload,
151307
151889
  vectorBackfillFailureStreak: streak
151308
151890
  },
151891
+ progress: {
151892
+ attempted: result.attempted,
151893
+ succeeded: result.succeeded,
151894
+ failed: result.failed,
151895
+ remaining: after.missing
151896
+ },
151309
151897
  lastError: result.lastError ?? `vector backfill made no progress (${result.failed}/${result.attempted} failed)`
151310
151898
  };
151311
151899
  }
@@ -151315,6 +151903,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
151315
151903
  action: "reschedule",
151316
151904
  delayMs: result.attempted === 0 ? VECTOR_RETRY_DELAY_MS : 0,
151317
151905
  resetAttempts: result.succeeded > 0,
151906
+ progress: {
151907
+ attempted: result.attempted,
151908
+ succeeded: result.succeeded,
151909
+ failed: result.failed,
151910
+ remaining: after.missing
151911
+ },
151318
151912
  ...result.succeeded > 0 ? {
151319
151913
  ...priorFailureStreak > 0 ? { payload } : {},
151320
151914
  ...result.failed > 0 && result.lastError ? { lastError: result.lastError } : priorFailureStreak > 0 ? { clearLastError: true } : {}
@@ -151723,24 +152317,40 @@ function queueVectorBackfill(projectId, options = {}) {
151723
152317
  });
151724
152318
  }
151725
152319
  async function bindObservationCodeRefsBestEffort(observation) {
151726
- if (!projectDir) return;
152320
+ if (!projectDir) return true;
151727
152321
  try {
151728
152322
  const { CodeGraphStore: CodeGraphStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
151729
152323
  const { bindObservationToCode: bindObservationToCode2 } = await Promise.resolve().then(() => (init_binder(), binder_exports));
151730
152324
  const codeStore = new CodeGraphStore2();
151731
152325
  await codeStore.init(projectDir);
151732
152326
  await bindObservationToCode2(codeStore, observation);
152327
+ return true;
151733
152328
  } catch {
152329
+ return false;
151734
152330
  }
151735
152331
  }
151736
152332
  async function persistEvidenceCard(observation) {
151737
- if (!projectDir) return;
152333
+ if (!projectDir) return true;
151738
152334
  try {
151739
152335
  const evidence = new EvidenceCardStore();
151740
152336
  await evidence.init(projectDir);
151741
152337
  evidence.upsertObservation(observation);
152338
+ return true;
151742
152339
  } catch (error) {
151743
152340
  console.error(`[memorix] Evidence card projection failed for obs-${observation.id}: ${error instanceof Error ? error.message : String(error)}`);
152341
+ return false;
152342
+ }
152343
+ }
152344
+ async function acknowledgeObservationProjection(observation) {
152345
+ if (!projectDir) return;
152346
+ try {
152347
+ const { MaintenanceJobStore: MaintenanceJobStore2 } = await Promise.resolve().then(() => (init_maintenance_jobs(), maintenance_jobs_exports));
152348
+ new MaintenanceJobStore2(projectDir).acknowledgePending(
152349
+ observation.projectId,
152350
+ "observation-project",
152351
+ "observation-project:" + observation.id
152352
+ );
152353
+ } catch {
151744
152354
  }
151745
152355
  }
151746
152356
  function queueClaimDerivation(observation) {
@@ -151769,6 +152379,45 @@ function queueObservationQualification(observation) {
151769
152379
  } catch {
151770
152380
  }
151771
152381
  }
152382
+ async function enqueueObservationDerivedWork(tx, observation) {
152383
+ if (!tx.enqueueMaintenanceJob) return false;
152384
+ if (!isEmbeddingExplicitlyDisabled()) {
152385
+ await tx.enqueueMaintenanceJob({
152386
+ projectId: observation.projectId,
152387
+ kind: "vector-backfill",
152388
+ dedupeKey: "vector-backfill",
152389
+ payload: { limit: 12 }
152390
+ });
152391
+ }
152392
+ if (observation.admissionState === "candidate") {
152393
+ await tx.enqueueMaintenanceJob({
152394
+ projectId: observation.projectId,
152395
+ kind: "observation-qualify",
152396
+ dedupeKey: "observation-qualify",
152397
+ payload: { source: "automatic-capture:" + observation.id, limit: 100 }
152398
+ });
152399
+ }
152400
+ const claimSource = observation.sourceDetail === "explicit" || observation.source === "git" || observation.sourceDetail === "git-ingest";
152401
+ if (claimSource && resolveObservationVisibility(observation) === "project") {
152402
+ await tx.enqueueMaintenanceJob({
152403
+ projectId: observation.projectId,
152404
+ kind: "claim-derive",
152405
+ dedupeKey: "claim-derive:" + observation.id,
152406
+ payload: { observationId: observation.id }
152407
+ });
152408
+ }
152409
+ await enqueueObservationProjectionWork(tx, observation);
152410
+ return true;
152411
+ }
152412
+ async function enqueueObservationProjectionWork(tx, observation) {
152413
+ if (!tx.enqueueMaintenanceJob) return;
152414
+ await tx.enqueueMaintenanceJob({
152415
+ projectId: observation.projectId,
152416
+ kind: "observation-project",
152417
+ dedupeKey: "observation-project:" + observation.id,
152418
+ payload: { observationId: observation.id }
152419
+ });
152420
+ }
151772
152421
  function isVectorCompatibleWithCurrentIndex(embedding) {
151773
152422
  if (!embedding) return false;
151774
152423
  const vectorDimensions = getVectorDimensions();
@@ -151947,7 +152596,6 @@ async function storeObservation(input) {
151947
152596
  throw new Error("Cannot update a memory outside this session's write scope.");
151948
152597
  }
151949
152598
  const observation2 = await upsertObservation(existing, input, now3);
151950
- await input.onPersisted?.(observation2);
151951
152599
  return { observation: observation2, upserted: true };
151952
152600
  }
151953
152601
  }
@@ -151974,6 +152622,7 @@ async function storeObservation(input) {
151974
152622
  let upsertedInsideLock = false;
151975
152623
  let reloadCacheAfterCommit = false;
151976
152624
  let persistedCallbackInvoked = false;
152625
+ let derivedJobsCommitted = false;
151977
152626
  const assignAndPersist = async () => {
151978
152627
  if (projectDir) {
151979
152628
  const store = getObservationStore();
@@ -152029,6 +152678,7 @@ async function storeObservation(input) {
152029
152678
  writeGeneration: transactionGeneration + 1
152030
152679
  };
152031
152680
  await tx.insert(observation);
152681
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, observation);
152032
152682
  await input.onPersisted?.(observation);
152033
152683
  persistedCallbackInvoked = true;
152034
152684
  await tx.saveIdCounter(id + 1);
@@ -152127,15 +152777,17 @@ async function storeObservation(input) {
152127
152777
  await assignAndPersist();
152128
152778
  if (upsertedInsideLock) {
152129
152779
  const updated = await upsertObservation(observation, input, now3);
152130
- await input.onPersisted?.(updated);
152131
152780
  return { observation: updated, upserted: true };
152132
152781
  }
152133
152782
  if (!persistedCallbackInvoked) await input.onPersisted?.(observation);
152134
- await bindObservationCodeRefsBestEffort(observation);
152135
- await persistEvidenceCard(observation);
152136
- queueObservationQualification(observation);
152137
- if (resolveObservationVisibility(observation) === "project") {
152138
- queueClaimDerivation(observation);
152783
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(observation);
152784
+ const evidenceProjected = await persistEvidenceCard(observation);
152785
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(observation);
152786
+ if (!derivedJobsCommitted) {
152787
+ queueObservationQualification(observation);
152788
+ if (resolveObservationVisibility(observation) === "project") {
152789
+ queueClaimDerivation(observation);
152790
+ }
152139
152791
  }
152140
152792
  scheduleObservationEmbedding({
152141
152793
  observationId: observation.id,
@@ -152157,86 +152809,115 @@ async function upsertObservation(existing, input, now3) {
152157
152809
  }
152158
152810
  const fullText = [input.title, input.narrative, ...input.facts ?? [], ...enrichedFiles, ...enrichedConcepts].join(" ");
152159
152811
  const tokens = countTextTokens(fullText);
152160
- existing.entityName = input.entityName;
152161
- existing.type = input.type;
152162
- existing.title = input.title;
152163
- existing.narrative = input.narrative;
152164
- existing.facts = input.facts ?? [];
152165
- existing.attachments = input.attachments;
152166
- existing.filesModified = enrichedFiles;
152167
- existing.concepts = enrichedConcepts;
152168
- existing.tokens = tokens;
152169
- existing.updatedAt = now3;
152170
- existing.hasCausalLanguage = extracted.hasCausalLanguage;
152171
- existing.revisionCount = (existing.revisionCount ?? 1) + 1;
152172
- existing.status = "active";
152173
- if (input.sessionId) existing.sessionId = input.sessionId;
152174
- if (input.progress) existing.progress = input.progress;
152175
- if (input.sourceDetail !== void 0) existing.sourceDetail = input.sourceDetail;
152176
- if (input.valueCategory !== void 0) existing.valueCategory = input.valueCategory;
152177
- if (input.admissionState !== void 0) existing.admissionState = input.admissionState;
152178
- if (input.admissionReason !== void 0) existing.admissionReason = sanitizeCredentials(input.admissionReason);
152179
- if (input.visibility !== void 0) existing.visibility = input.visibility;
152180
- if (input.sharedWithAgentIds !== void 0) existing.sharedWithAgentIds = input.sharedWithAgentIds;
152812
+ const applyUpdate = (current) => ({
152813
+ ...current,
152814
+ entityName: input.entityName,
152815
+ type: input.type,
152816
+ title: input.title,
152817
+ narrative: input.narrative,
152818
+ facts: input.facts ?? [],
152819
+ attachments: input.attachments,
152820
+ filesModified: enrichedFiles,
152821
+ concepts: enrichedConcepts,
152822
+ tokens,
152823
+ updatedAt: now3,
152824
+ hasCausalLanguage: extracted.hasCausalLanguage,
152825
+ revisionCount: (current.revisionCount ?? 1) + 1,
152826
+ status: "active",
152827
+ ...input.sessionId ? { sessionId: input.sessionId } : {},
152828
+ ...input.progress ? { progress: input.progress } : {},
152829
+ ...input.sourceDetail !== void 0 ? { sourceDetail: input.sourceDetail } : {},
152830
+ ...input.valueCategory !== void 0 ? { valueCategory: input.valueCategory } : {},
152831
+ ...input.admissionState !== void 0 ? { admissionState: input.admissionState } : {},
152832
+ ...input.admissionReason !== void 0 ? { admissionReason: sanitizeCredentials(input.admissionReason) } : {},
152833
+ ...input.visibility !== void 0 ? { visibility: input.visibility } : {},
152834
+ ...input.sharedWithAgentIds !== void 0 ? { sharedWithAgentIds: input.sharedWithAgentIds } : {}
152835
+ });
152836
+ let updated = applyUpdate(existing);
152837
+ let derivedJobsCommitted = false;
152838
+ if (projectDir) {
152839
+ const store = getObservationStore();
152840
+ await store.atomic(async (tx) => {
152841
+ const current = await tx.getById(existing.id);
152842
+ if (!current || current.projectId !== existing.projectId) {
152843
+ throw new Error("Topic observation changed before update");
152844
+ }
152845
+ updated = applyUpdate(current);
152846
+ updated.writeGeneration = await tx.getGeneration() + 1;
152847
+ await tx.update(updated);
152848
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, updated);
152849
+ await input.onPersisted?.(updated);
152850
+ });
152851
+ updated.writeGeneration = store.getGeneration();
152852
+ } else {
152853
+ await input.onPersisted?.(updated);
152854
+ }
152855
+ if (corpusLoaded) {
152856
+ const cacheIndex = observations.findIndex((observation) => observation.id === updated.id);
152857
+ if (cacheIndex >= 0) observations[cacheIndex] = updated;
152858
+ }
152181
152859
  const doc = {
152182
- id: makeOramaObservationId(existing.projectId, existing.id),
152183
- observationId: existing.id,
152184
- entityName: existing.entityName,
152185
- type: existing.type,
152186
- title: existing.title,
152187
- narrative: existing.narrative,
152188
- facts: existing.facts.join("\n"),
152860
+ id: makeOramaObservationId(updated.projectId, updated.id),
152861
+ observationId: updated.id,
152862
+ entityName: updated.entityName,
152863
+ type: updated.type,
152864
+ title: updated.title,
152865
+ narrative: updated.narrative,
152866
+ facts: updated.facts.join("\n"),
152189
152867
  filesModified: enrichedFiles.join("\n"),
152190
152868
  concepts: enrichedConcepts.map((c) => c.replace(/-/g, " ")).join(", "),
152191
- attachments: formatAttachmentProvenance(existing.attachments),
152869
+ attachments: formatAttachmentProvenance(updated.attachments),
152192
152870
  tokens,
152193
- createdAt: existing.createdAt,
152194
- projectId: existing.projectId,
152871
+ createdAt: updated.createdAt,
152872
+ projectId: updated.projectId,
152195
152873
  accessCount: 0,
152196
152874
  lastAccessedAt: "",
152197
152875
  status: "active",
152198
- source: existing.source ?? "agent",
152199
- sourceDetail: existing.sourceDetail ?? "",
152200
- valueCategory: existing.valueCategory ?? "",
152201
- admissionState: existing.admissionState ?? "",
152202
- admissionReason: existing.admissionReason ?? "",
152203
- visibility: existing.visibility ?? "project",
152204
- createdByAgentId: existing.createdByAgentId ?? "",
152205
- sharedWithAgentIds: JSON.stringify(existing.sharedWithAgentIds ?? [])
152206
- };
152207
- const oramaId = makeOramaObservationId(existing.projectId, existing.id);
152208
- try {
152209
- const { removeObservation: removeObservation2 } = await Promise.resolve().then(() => (init_orama_store(), orama_store_exports));
152210
- await removeObservation2(oramaId);
152211
- } catch {
152212
- }
152213
- try {
152214
- await insertObservation(doc);
152215
- } catch {
152876
+ source: updated.source ?? "agent",
152877
+ sourceDetail: updated.sourceDetail ?? "",
152878
+ valueCategory: updated.valueCategory ?? "",
152879
+ admissionState: updated.admissionState ?? "",
152880
+ admissionReason: updated.admissionReason ?? "",
152881
+ visibility: updated.visibility ?? "project",
152882
+ createdByAgentId: updated.createdByAgentId ?? "",
152883
+ sharedWithAgentIds: JSON.stringify(updated.sharedWithAgentIds ?? [])
152884
+ };
152885
+ if (corpusLoaded) {
152886
+ const oramaId = makeOramaObservationId(updated.projectId, updated.id);
152216
152887
  try {
152217
- const { removeObservation: removeObs } = await Promise.resolve().then(() => (init_orama_store(), orama_store_exports));
152218
- await removeObs(oramaId);
152888
+ try {
152889
+ await removeObservation(oramaId);
152890
+ } catch {
152891
+ }
152219
152892
  await insertObservation(doc);
152220
152893
  } catch {
152894
+ try {
152895
+ try {
152896
+ await removeObservation(oramaId);
152897
+ } catch {
152898
+ }
152899
+ await insertObservation(doc);
152900
+ } catch (error) {
152901
+ console.error(`[memorix] Observation index projection failed for obs-${updated.id}: ${sanitizeCredentials(error instanceof Error ? error.message : String(error))}`);
152902
+ }
152221
152903
  }
152222
152904
  }
152223
- if (projectDir) {
152224
- const store = getObservationStore();
152225
- await store.update(existing);
152226
- }
152227
- await bindObservationCodeRefsBestEffort(existing);
152228
- await persistEvidenceCard(existing);
152229
- queueObservationQualification(existing);
152230
- if (resolveObservationVisibility(existing) === "project") {
152231
- queueClaimDerivation(existing);
152905
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(updated);
152906
+ const evidenceProjected = await persistEvidenceCard(updated);
152907
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(updated);
152908
+ if (!derivedJobsCommitted) {
152909
+ queueObservationQualification(updated);
152910
+ if (resolveObservationVisibility(updated) === "project") {
152911
+ queueClaimDerivation(updated);
152912
+ }
152232
152913
  }
152233
152914
  scheduleObservationEmbedding({
152234
- observationId: existing.id,
152235
- projectId: existing.projectId,
152915
+ observationId: updated.id,
152916
+ projectId: updated.projectId,
152236
152917
  searchableText: [input.title, input.narrative, ...input.facts ?? []].join(" "),
152237
152918
  doc
152238
152919
  });
152239
- return existing;
152920
+ return updated;
152240
152921
  }
152241
152922
  function getObservation(id, projectId) {
152242
152923
  return observations.find((o) => o.id === id && (projectId ? o.projectId === projectId : true));
@@ -152269,6 +152950,7 @@ async function updateObservationAdmission(input) {
152269
152950
  const next = apply(current);
152270
152951
  if (!next) return;
152271
152952
  await tx.update(next);
152953
+ await enqueueObservationProjectionWork(tx, next);
152272
152954
  updated = next;
152273
152955
  });
152274
152956
  } else {
@@ -152286,6 +152968,9 @@ async function updateObservationAdmission(input) {
152286
152968
  });
152287
152969
  } catch {
152288
152970
  }
152971
+ if (await persistEvidenceCard(updated)) {
152972
+ await acknowledgeObservationProjection(updated);
152973
+ }
152289
152974
  if (updated.admissionState === "qualified" && resolveObservationVisibility(updated) === "project") {
152290
152975
  queueClaimDerivation(updated);
152291
152976
  }
@@ -152356,10 +153041,17 @@ async function resolveObservations(ids, status = "resolved") {
152356
153041
  if (projectDir && resolved.length > 0) {
152357
153042
  const store = getObservationStore();
152358
153043
  await store.atomic(async (tx) => {
152359
- await Promise.all(changed.map((observation) => tx.update(observation)));
153044
+ await Promise.all(changed.map(async (observation) => {
153045
+ await tx.update(observation);
153046
+ await enqueueObservationProjectionWork(tx, observation);
153047
+ }));
152360
153048
  });
152361
153049
  }
152362
- for (const observation of changed) await persistEvidenceCard(observation);
153050
+ for (const observation of changed) {
153051
+ if (await persistEvidenceCard(observation)) {
153052
+ await acknowledgeObservationProjection(observation);
153053
+ }
153054
+ }
152363
153055
  return { resolved, notFound };
152364
153056
  }
152365
153057
  function getProjectObservations(projectId) {
@@ -152512,9 +153204,9 @@ async function prepareSearchIndex(options = {}) {
152512
153204
  for (const projectId of projects) {
152513
153205
  const projectObservations = await store.loadByProject(projectId);
152514
153206
  for (const observation of projectObservations) {
152515
- if (!persistedIds?.has(observation.id)) markVectorMissing(observation.id, observation.projectId);
153207
+ if (!persistedIds?.has(semanticVectorKey(observation.projectId, observation.id))) markVectorMissing(observation.id, observation.projectId);
152516
153208
  }
152517
- if (projectObservations.some((observation) => !persistedIds?.has(observation.id))) {
153209
+ if (projectObservations.some((observation) => !persistedIds?.has(semanticVectorKey(observation.projectId, observation.id)))) {
152518
153210
  queueVectorBackfill(projectId);
152519
153211
  }
152520
153212
  }
@@ -152536,7 +153228,7 @@ async function prepareSearchIndex(options = {}) {
152536
153228
  const persistedSemanticIds = await getPersistentSemanticVectorIds(hydratedProjectDir).catch(() => null);
152537
153229
  const projectsWithMissingVectors = /* @__PURE__ */ new Set();
152538
153230
  for (const obs of observations) {
152539
- if (!hasObservationVector(obs.projectId, obs.id) && !persistedSemanticIds?.has(obs.id)) {
153231
+ if (!hasObservationVector(obs.projectId, obs.id) && !persistedSemanticIds?.has(semanticVectorKey(obs.projectId, obs.id))) {
152540
153232
  markVectorMissing(obs.id, obs.projectId);
152541
153233
  projectsWithMissingVectors.add(obs.projectId);
152542
153234
  }
@@ -152580,7 +153272,7 @@ function getSearchIndexStatus(projectId) {
152580
153272
  };
152581
153273
  }
152582
153274
  async function probeSearchIndex(projectId) {
152583
- await searchObservations({
153275
+ const result = await searchObservationsDetailed({
152584
153276
  query: "semantic memory retrieval status",
152585
153277
  projectId,
152586
153278
  reader: { projectId },
@@ -152588,7 +153280,7 @@ async function probeSearchIndex(projectId) {
152588
153280
  status: "all",
152589
153281
  trackAccess: false
152590
153282
  });
152591
- return getLastSearchMode(projectId);
153283
+ return result.diagnostics.mode;
152592
153284
  }
152593
153285
  async function backfillVectorEmbeddings(options = {}) {
152594
153286
  if (vectorBackfillRunning) {
@@ -152740,6 +153432,7 @@ var init_observations = __esm({
152740
153432
  init_token_budget();
152741
153433
  init_entity_extractor();
152742
153434
  init_provider();
153435
+ init_semantic_index();
152743
153436
  init_secret_filter();
152744
153437
  init_lifecycle();
152745
153438
  init_visibility();