memorix 1.10.3 → 1.10.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +62 -1
  2. package/dist/cli/index.js +1886 -1273
  3. package/dist/index.js +1724 -1088
  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 +694 -172
  7. package/dist/media-audio-runner.js +685 -164
  8. package/dist/media-video-runner.js +693 -172
  9. package/dist/memcode-runtime/CHANGELOG.md +44 -1
  10. package/dist/sdk.js +13952 -13345
  11. package/dist/vector-backfill-runner.d.ts +1 -1
  12. package/dist/vector-backfill-runner.js +693 -172
  13. package/docs/ARCHITECTURE.md +219 -0
  14. package/docs/CONFIGURATION.md +15 -0
  15. package/docs/DESIGN_DECISIONS.md +37 -0
  16. package/docs/DEVELOPMENT.md +1 -1
  17. package/docs/MODULES.md +7 -1
  18. package/docs/PERFORMANCE.md +14 -0
  19. package/docs/README.md +1 -1
  20. package/docs/ROADMAP-1.9.12-2.0.md +18 -2
  21. package/package.json +1 -1
  22. package/plugins/antigravity/memorix/plugin.json +1 -1
  23. package/plugins/claude/memorix/.claude-plugin/plugin.json +1 -1
  24. package/plugins/codebuddy/memorix/.codebuddy-plugin/plugin.json +1 -1
  25. package/plugins/codex/memorix/.codex-plugin/plugin.json +1 -1
  26. package/plugins/copilot/memorix/plugin.json +1 -1
  27. package/plugins/gemini/memorix/gemini-extension.json +1 -1
  28. package/plugins/hermes/memorix/plugin.yaml +1 -1
  29. package/plugins/omp/memorix/package.json +1 -1
  30. package/plugins/openclaw/memorix/.codex-plugin/plugin.json +1 -1
  31. package/plugins/pi/memorix/package.json +1 -1
  32. package/server.json +2 -2
  33. package/src/cli/tui/chat-service.ts +6 -9
  34. package/src/cli/tui/data.ts +2 -2
  35. package/src/codegraph/auto-context.ts +9 -2
  36. package/src/codegraph/derived-view.ts +63 -0
  37. package/src/compact/engine.ts +10 -33
  38. package/src/config/resolved-config.ts +11 -0
  39. package/src/config/retrieval-strategy.ts +22 -0
  40. package/src/config/toml-loader.ts +5 -0
  41. package/src/config/yaml-loader.ts +7 -0
  42. package/src/core/derived-view.ts +15 -0
  43. package/src/core/maintenance-result.ts +33 -0
  44. package/src/core/retrieval-contracts.ts +57 -0
  45. package/src/core/retrieval-facade.ts +18 -0
  46. package/src/core/retrieval-policy.ts +44 -0
  47. package/src/core/runtime-context.ts +42 -0
  48. package/src/embedding/api-provider.ts +18 -8
  49. package/src/knowledge/workset.ts +0 -2
  50. package/src/memory/consolidation.ts +3 -2
  51. package/src/memory/feedback-model.ts +1 -4
  52. package/src/memory/observations.ts +165 -87
  53. package/src/runtime/control-plane-maintenance.ts +1 -0
  54. package/src/runtime/isolated-maintenance.ts +1 -0
  55. package/src/runtime/maintenance-jobs.ts +123 -32
  56. package/src/runtime/project-maintenance.ts +69 -1
  57. package/src/sdk.ts +3 -2
  58. package/src/search/fts-view.ts +53 -0
  59. package/src/search/orama-view.ts +40 -0
  60. package/src/search/retrieval-facade.ts +38 -0
  61. package/src/search/semantic-index.ts +13 -0
  62. package/src/search/semantic-view.ts +34 -0
  63. package/src/server.ts +19 -7
  64. package/src/store/obs-store.ts +15 -0
  65. package/src/store/orama-store.ts +116 -42
  66. package/src/store/sqlite-db.ts +22 -0
  67. 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
 
@@ -3482,8 +3539,8 @@ async function loadCacheJsonl(filePath) {
3482
3539
  loaded = cache3.size;
3483
3540
  } catch {
3484
3541
  }
3485
- if (onDiskCount % 250 === 0) {
3486
- await new Promise((resolve2) => setImmediate(resolve2));
3542
+ if (onDiskCount % CACHE_LOAD_YIELD_EVERY === 0) {
3543
+ await new Promise((resolve2) => setTimeout(resolve2, 0));
3487
3544
  }
3488
3545
  }
3489
3546
  diskCacheEntryCount = onDiskCount;
@@ -3812,6 +3869,12 @@ async function fetchWithRetry(url, apiKey, body, options = {}, attempt = 0, nati
3812
3869
  if (err instanceof Error && (err.name === "AbortError" || controller.signal.aborted || options.signal?.aborted)) {
3813
3870
  throw new Error(`Embedding API timeout after ${timeoutMs}ms: ${url}`);
3814
3871
  }
3872
+ if (options.retry !== false && attempt < MAX_RETRIES2) {
3873
+ const delay3 = BASE_DELAY_MS * Math.pow(2, attempt);
3874
+ console.error(`[memorix] Embedding transport failure, retry ${attempt + 1}/${MAX_RETRIES2} in ${delay3}ms`);
3875
+ await waitForRetry(delay3, options.signal);
3876
+ return fetchWithRetry(url, apiKey, body, options, attempt + 1, nativeGemini);
3877
+ }
3815
3878
  throw err;
3816
3879
  }
3817
3880
  try {
@@ -3890,7 +3953,7 @@ async function waitForRetry(waitMs, signal) {
3890
3953
  abortSignal.addEventListener("abort", onAbort, { once: true });
3891
3954
  });
3892
3955
  }
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;
3956
+ var cache3, MAX_CACHE_ENTRIES, MAX_CACHE_PAYLOAD_BYTES, BYTES_PER_DIM, DEFAULT_ASSUMED_DIMENSIONS, MAX_MIGRATION_VALUE_BYTES, cachePayloadBytes3, cacheDimensions, diskCacheEntryCount, diskCacheDirty2, diskSaveTimer, diskCacheLoaded, diskCacheLoadPromise, diskCacheLoadCount, jsonlLineCountCalls, MAX_INPUT_CHARS, MAX_CONCURRENCY, DISK_SAVE_DEBOUNCE_MS, DEFAULT_MAX_BATCH_SIZE, DASHSCOPE_MAX_BATCH_SIZE, MAX_RETRIES2, BASE_DELAY_MS, CACHE_LOAD_YIELD_EVERY, EmbeddingAPIError, APIEmbeddingProvider;
3894
3957
  var init_api_provider = __esm({
3895
3958
  "src/embedding/api-provider.ts"() {
3896
3959
  "use strict";
@@ -3918,6 +3981,7 @@ var init_api_provider = __esm({
3918
3981
  DASHSCOPE_MAX_BATCH_SIZE = 10;
3919
3982
  MAX_RETRIES2 = 3;
3920
3983
  BASE_DELAY_MS = 500;
3984
+ CACHE_LOAD_YIELD_EVERY = 32;
3921
3985
  EmbeddingAPIError = class extends Error {
3922
3986
  status;
3923
3987
  constructor(status, detail) {
@@ -3969,7 +4033,7 @@ var init_api_provider = __esm({
3969
4033
  console.error(`[memorix] Dimension shortening: ${config.requestedDimensions}d requested`);
3970
4034
  }
3971
4035
  if (allowNetworkProbe) {
3972
- startDiskCacheLoad();
4036
+ setImmediate(startDiskCacheLoad);
3973
4037
  }
3974
4038
  return new _APIEmbeddingProvider(config, probeDimensions);
3975
4039
  }
@@ -4041,10 +4105,8 @@ var init_api_provider = __esm({
4041
4105
  return this.embedInput({ modality: "text", text: normalized }, { intent: "document", ...options });
4042
4106
  }
4043
4107
  const hash4 = textHash2(normalized, this.cacheKeyNamespace);
4044
- if (diskCacheLoaded) {
4045
- const cached = cache3.get(hash4);
4046
- if (cached) return cached;
4047
- }
4108
+ const cached = cache3.get(hash4);
4109
+ if (cached) return cached;
4048
4110
  const apiCall = async () => {
4049
4111
  const body = {
4050
4112
  model: this.config.model,
@@ -4069,8 +4131,8 @@ var init_api_provider = __esm({
4069
4131
  let embedding;
4070
4132
  if (!diskCacheLoaded && diskCacheLoadPromise) {
4071
4133
  const cacheRace = diskCacheLoadPromise.then(() => {
4072
- const cached = cache3.get(hash4);
4073
- if (cached) return cached;
4134
+ const cached2 = cache3.get(hash4);
4135
+ if (cached2) return cached2;
4074
4136
  return null;
4075
4137
  });
4076
4138
  const result = await Promise.race([
@@ -5776,6 +5838,7 @@ var sqlite_store_exports = {};
5776
5838
  __export(sqlite_store_exports, {
5777
5839
  SqliteBackend: () => SqliteBackend
5778
5840
  });
5841
+ import { randomUUID as randomUUID2 } from "crypto";
5779
5842
  import path7 from "path";
5780
5843
  import fs4 from "fs";
5781
5844
  function obsToRow(obs) {
@@ -6164,6 +6227,32 @@ var init_sqlite_store = __esm({
6164
6227
  }, "Observation atomic write");
6165
6228
  try {
6166
6229
  const tx = {
6230
+ enqueueMaintenanceJob: async (input) => {
6231
+ const payloadJson = JSON.stringify(input.payload ?? {});
6232
+ const existing = this.db.prepare(`
6233
+ SELECT id, status FROM maintenance_jobs
6234
+ WHERE project_id = ? AND kind = ? AND dedupe_key = ?
6235
+ AND status IN ('pending', 'running', 'retry')
6236
+ LIMIT 1
6237
+ `).get(input.projectId, input.kind, input.dedupeKey);
6238
+ if (existing) {
6239
+ if (existing.status === "running") {
6240
+ this.db.prepare(`
6241
+ UPDATE maintenance_jobs
6242
+ SET rerun_requested = 1, payload_json = ?, updated_at = ?
6243
+ WHERE id = ?
6244
+ `).run(payloadJson, Date.now(), existing.id);
6245
+ }
6246
+ return;
6247
+ }
6248
+ const now3 = Date.now();
6249
+ this.db.prepare(`
6250
+ INSERT INTO maintenance_jobs (
6251
+ id, project_id, kind, dedupe_key, payload_json, status, attempts,
6252
+ max_attempts, run_after, created_at, updated_at
6253
+ ) VALUES (?, ?, ?, ?, ?, 'pending', 0, 8, ?, ?, ?)
6254
+ `).run(randomUUID2(), input.projectId, input.kind, input.dedupeKey, payloadJson, now3, now3, now3);
6255
+ },
6167
6256
  loadAll: async () => this.rawLoadAll(),
6168
6257
  getById: async (id) => this.rawGetById(id),
6169
6258
  findByTopicKey: async (projectId, topicKey) => this.rawFindByTopicKey(projectId, topicKey),
@@ -6234,6 +6323,7 @@ __export(obs_store_exports, {
6234
6323
  DegradedBackend: () => DegradedBackend,
6235
6324
  createObservationStore: () => createObservationStore,
6236
6325
  getObservationStore: () => getObservationStore,
6326
+ getObservationStoreDataDir: () => getObservationStoreDataDir,
6237
6327
  initObservationStore: () => initObservationStore,
6238
6328
  resetObservationStore: () => resetObservationStore,
6239
6329
  setObservationStore: () => setObservationStore
@@ -6244,6 +6334,12 @@ function getObservationStore() {
6244
6334
  }
6245
6335
  return _store2;
6246
6336
  }
6337
+ function getObservationStoreDataDir() {
6338
+ if (!_store2 || !_storeDataDir) {
6339
+ throw new Error("[memorix] ObservationStore data directory is not bound");
6340
+ }
6341
+ return _storeDataDir;
6342
+ }
6247
6343
  function setObservationStore(store) {
6248
6344
  _store2 = store;
6249
6345
  }
@@ -6422,6 +6518,9 @@ async function loadLanceDb() {
6422
6518
  return null;
6423
6519
  }
6424
6520
  }
6521
+ async function isSemanticIndexAvailable() {
6522
+ return await loadLanceDb() !== null;
6523
+ }
6425
6524
  function semanticIndexEnabled() {
6426
6525
  return process.env.MEMORIX_SEMANTIC_INDEX !== "off" && process.env.MEMORIX_SEMANTIC_INDEX !== "orama";
6427
6526
  }
@@ -6551,6 +6650,22 @@ async function listSemanticVectorIds(dataDir, profile) {
6551
6650
  const rows = await state.table.query().select(["observation_id"]).toArray();
6552
6651
  return new Set(rows.map((row) => Number(row.observation_id)).filter(Number.isSafeInteger));
6553
6652
  }
6653
+ async function getSemanticIndexStats(dataDir, profile) {
6654
+ const state = await getState(dataDir, profile);
6655
+ if (!state?.table) return null;
6656
+ return {
6657
+ rowCount: await state.table.countRows(),
6658
+ version: typeof state.table.version === "function" ? await state.table.version() : 0
6659
+ };
6660
+ }
6661
+ function optimizeSemanticIndex(dataDir, profile) {
6662
+ const key = stateKey(dataDir, profile);
6663
+ return queueOperation(key, async () => {
6664
+ const state = await getState(dataDir, profile);
6665
+ if (state) await optimizeState(state);
6666
+ mutationCounts.set(key, 0);
6667
+ });
6668
+ }
6554
6669
  function resolveIndexThreshold() {
6555
6670
  const raw = Number.parseInt(process.env.MEMORIX_SEMANTIC_INDEX_THRESHOLD ?? "", 10);
6556
6671
  return Number.isSafeInteger(raw) && raw > 0 ? raw : DEFAULT_INDEX_THRESHOLD;
@@ -6602,6 +6717,20 @@ async function searchSemanticVectors(options) {
6602
6717
  distance: Number(row._distance ?? Number.POSITIVE_INFINITY)
6603
6718
  })).filter((row) => Number.isFinite(row.distance));
6604
6719
  }
6720
+ async function closeSemanticIndexProfile(dataDir, profile) {
6721
+ const key = stateKey(dataDir, profile);
6722
+ await flushPendingVectorBatch(key);
6723
+ await writeQueues.get(key);
6724
+ const state = await statePromises.get(key)?.catch(() => null);
6725
+ try {
6726
+ state?.connection?.close?.();
6727
+ } catch {
6728
+ }
6729
+ statePromises.delete(key);
6730
+ writeQueues.delete(key);
6731
+ indexBuilds.delete(key);
6732
+ mutationCounts.delete(key);
6733
+ }
6605
6734
  var SEMANTIC_INDEX_DIR, TABLE_PREFIX, DEFAULT_INDEX_THRESHOLD, MAX_INDEX_PARTITIONS, DEFAULT_WRITE_BATCH_SIZE, DEFAULT_WRITE_FLUSH_MS, DEFAULT_OPTIMIZE_EVERY, DEFAULT_VERSION_RETENTION_MS, statePromises, writeQueues, indexBuilds, mutationCounts, pendingVectorBatches, availability, requireFromHere2;
6606
6735
  var init_semantic_index = __esm({
6607
6736
  "src/search/semantic-index.ts"() {
@@ -6624,6 +6753,59 @@ var init_semantic_index = __esm({
6624
6753
  }
6625
6754
  });
6626
6755
 
6756
+ // src/search/semantic-view.ts
6757
+ function createSemanticDerivedView(dataDir, profile) {
6758
+ return {
6759
+ async status() {
6760
+ if (!await isSemanticIndexAvailable()) return { state: "unavailable" };
6761
+ const stats = await getSemanticIndexStats(dataDir, profile);
6762
+ return stats ? { state: "ready", generation: stats.version, rowCount: stats.rowCount } : { state: "missing" };
6763
+ },
6764
+ async refresh(records) {
6765
+ if (records.length === 1) await upsertSemanticVector(dataDir, profile, records[0]);
6766
+ else await upsertSemanticVectors(dataDir, profile, records);
6767
+ },
6768
+ rebuild: () => ensureSemanticIndex(dataDir, profile),
6769
+ compact: () => optimizeSemanticIndex(dataDir, profile),
6770
+ close: () => closeSemanticIndexProfile(dataDir, profile)
6771
+ };
6772
+ }
6773
+ var init_semantic_view = __esm({
6774
+ "src/search/semantic-view.ts"() {
6775
+ "use strict";
6776
+ init_esm_shims();
6777
+ init_semantic_index();
6778
+ }
6779
+ });
6780
+
6781
+ // src/core/retrieval-contracts.ts
6782
+ function createRetrievalPlan(options) {
6783
+ const requestedLimit = Number.isFinite(options.limit) ? Math.floor(options.limit ?? 20) : 20;
6784
+ const requestedTokens = Number.isFinite(options.maxTokens) ? Math.floor(options.maxTokens ?? 0) : 0;
6785
+ return {
6786
+ query: options.query.trim(),
6787
+ quality: options.quality ?? "balanced",
6788
+ limit: Math.max(1, Math.min(1e4, requestedLimit)),
6789
+ ...options.projectId ? { projectId: options.projectId } : {},
6790
+ status: options.status ?? "active",
6791
+ ...options.source ? { source: options.source } : {},
6792
+ ...options.type ? { type: options.type } : {},
6793
+ ...options.since ? { since: options.since } : {},
6794
+ ...options.until ? { until: options.until } : {},
6795
+ maxTokens: Math.max(0, requestedTokens),
6796
+ trackAccess: options.trackAccess !== false,
6797
+ reader: options.reader,
6798
+ surfacedIds: [...options.surfacedIds ?? []],
6799
+ signal: options.signal
6800
+ };
6801
+ }
6802
+ var init_retrieval_contracts = __esm({
6803
+ "src/core/retrieval-contracts.ts"() {
6804
+ "use strict";
6805
+ init_esm_shims();
6806
+ }
6807
+ });
6808
+
6627
6809
  // src/memory/secret-filter.ts
6628
6810
  function applyRedaction(text2) {
6629
6811
  if (!text2) return text2;
@@ -7284,6 +7466,7 @@ var orama_store_exports = {};
7284
7466
  __export(orama_store_exports, {
7285
7467
  _classifyQueryTier: () => classifyQueryTier,
7286
7468
  batchGenerateEmbeddings: () => batchGenerateEmbeddings,
7469
+ countIndexedDocuments: () => countIndexedDocuments,
7287
7470
  createSearchTokenizer: () => createSearchTokenizer,
7288
7471
  generateEmbedding: () => generateEmbedding,
7289
7472
  generateEmbeddingInput: () => generateEmbeddingInput,
@@ -7309,6 +7492,7 @@ __export(orama_store_exports, {
7309
7492
  resetDb: () => resetDb,
7310
7493
  resolveSearchFuzzyTolerance: () => resolveSearchFuzzyTolerance,
7311
7494
  searchObservations: () => searchObservations,
7495
+ searchObservationsDetailed: () => searchObservationsDetailed,
7312
7496
  updateObservationMetadata: () => updateObservationMetadata
7313
7497
  });
7314
7498
  import { components, create, insert as insert2, insertMultiple, search, remove as remove2, update, count, getByID } from "@orama/orama";
@@ -7497,6 +7681,46 @@ async function searchPersistentLexically(options, projectIds, limit2) {
7497
7681
  return null;
7498
7682
  }
7499
7683
  }
7684
+ async function searchLanceInVectorOrder(options, projectIds, limit2, queryVector, provider2) {
7685
+ try {
7686
+ const { getObservationDataDir: getObservationDataDir2 } = await Promise.resolve().then(() => (init_observations(), observations_exports));
7687
+ const dataDir = getObservationDataDir2();
7688
+ if (!dataDir) return null;
7689
+ const vectorHits = await searchSemanticVectors({
7690
+ dataDir,
7691
+ profile: createSemanticIndexProfile(provider2),
7692
+ vector: queryVector,
7693
+ projectId: projectIds ?? options.projectId,
7694
+ status: "all",
7695
+ limit: Math.min(1e4, Math.max(limit2, 1) * 4)
7696
+ });
7697
+ if (!vectorHits || vectorHits.length === 0) return null;
7698
+ const store = getObservationStore();
7699
+ const hits = [];
7700
+ const seen = /* @__PURE__ */ new Set();
7701
+ for (const hit of vectorHits) {
7702
+ if (seen.has(hit.observationId)) continue;
7703
+ seen.add(hit.observationId);
7704
+ const observation = await store.getById(hit.observationId);
7705
+ if (!observation) continue;
7706
+ if (projectIds && !projectIds.includes(observation.projectId)) continue;
7707
+ if (options.status !== "all" && (observation.status ?? "active") !== (options.status ?? "active")) continue;
7708
+ if (options.type && observation.type !== options.type) continue;
7709
+ if (options.source && observation.source !== options.source) continue;
7710
+ const document2 = observationToSearchDocument(observation);
7711
+ hits.push({
7712
+ id: document2.id,
7713
+ score: 1 / (1 + hits.length),
7714
+ document: document2
7715
+ });
7716
+ if (hits.length >= limit2) break;
7717
+ }
7718
+ if (hits.length === 0) return null;
7719
+ return { count: hits.length, hits };
7720
+ } catch {
7721
+ return null;
7722
+ }
7723
+ }
7500
7724
  async function searchPersistentSemantically(options, projectIds, limit2, queryVector, provider2) {
7501
7725
  try {
7502
7726
  const { getObservationDataDir: getObservationDataDir2 } = await Promise.resolve().then(() => (init_observations(), observations_exports));
@@ -7661,6 +7885,9 @@ async function getDb(options = {}) {
7661
7885
  }
7662
7886
  }
7663
7887
  }
7888
+ async function countIndexedDocuments(database) {
7889
+ return count(database ?? await getDb({ allowNetworkProbe: false }));
7890
+ }
7664
7891
  async function resetDb() {
7665
7892
  dbGeneration++;
7666
7893
  db = null;
@@ -7690,7 +7917,7 @@ async function queueSemanticVector(dataDir, record80) {
7690
7917
  const profile = provider2 ? createSemanticIndexProfile(provider2) : null;
7691
7918
  if (!profile) return;
7692
7919
  try {
7693
- await upsertSemanticVector(dataDir, profile, record80);
7920
+ await createSemanticDerivedView(dataDir, profile).refresh([record80]);
7694
7921
  } catch {
7695
7922
  }
7696
7923
  }
@@ -7781,7 +8008,7 @@ async function attachCachedVectors(database, observations2) {
7781
8008
  }
7782
8009
  }
7783
8010
  if (semanticDataDir && semanticProfile && semanticRecords.length > 0) {
7784
- void upsertSemanticVectors(semanticDataDir, semanticProfile, semanticRecords).catch(() => {
8011
+ void createSemanticDerivedView(semanticDataDir, semanticProfile).refresh(semanticRecords).catch(() => {
7785
8012
  });
7786
8013
  }
7787
8014
  await new Promise((resolve2) => setImmediate(resolve2));
@@ -7892,7 +8119,9 @@ async function removeObservation(oramaId) {
7892
8119
  const database = await getDb();
7893
8120
  await remove2(database, oramaId);
7894
8121
  }
7895
- async function searchObservations(options) {
8122
+ async function searchObservationsDetailed(options) {
8123
+ const retrievalPlan = createRetrievalPlan(options);
8124
+ options = { ...options, ...retrievalPlan };
7896
8125
  const searchStartedAt = Date.now();
7897
8126
  const perf = !!process.env.MEMORIX_PERF;
7898
8127
  const t0 = perf ? performance.now() : 0;
@@ -7906,10 +8135,12 @@ async function searchObservations(options) {
7906
8135
  const modeKey = options.projectId ?? SEARCH_MODE_DEFAULT_KEY;
7907
8136
  const quality = options.quality ?? "balanced";
7908
8137
  const database = await getDb();
7909
- rememberSearchMode(
7910
- modeKey,
7911
- quality === "fast" ? "fulltext (fast profile)" : embeddingEnabled ? "hybrid" : "fulltext"
7912
- );
8138
+ let requestMode = quality === "fast" ? "fulltext (fast profile)" : embeddingEnabled ? "hybrid" : "fulltext";
8139
+ const setMode = (mode) => {
8140
+ requestMode = mode;
8141
+ rememberSearchMode(modeKey, mode);
8142
+ };
8143
+ setMode(requestMode);
7913
8144
  let projectIds = null;
7914
8145
  if (options.projectId) {
7915
8146
  try {
@@ -7930,7 +8161,7 @@ async function searchObservations(options) {
7930
8161
  filters["source"] = options.source;
7931
8162
  }
7932
8163
  const hasQuery = options.query && options.query.trim().length > 0;
7933
- const originalQuery = options.query;
8164
+ const originalQuery = retrievalPlan.query;
7934
8165
  const tier = quality === "fast" ? "fast" : hasQuery ? classifyQueryTier(originalQuery) : "fast";
7935
8166
  mark(`tier=${tier}`);
7936
8167
  if (quality === "thorough" && hasQuery) {
@@ -7984,10 +8215,7 @@ async function searchObservations(options) {
7984
8215
  embeddingUnavailable = true;
7985
8216
  fallbackUsed = true;
7986
8217
  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
- );
8218
+ setMode(`fulltext (embedding dimension mismatch: provider ${provider2.dimensions}d vs index ${activeVectorDimensions}d)`);
7991
8219
  console.error(
7992
8220
  `[memorix] Embedding provider dimension mismatch (${provider2.dimensions}d provider vs ${activeVectorDimensions}d index); using fulltext search`
7993
8221
  );
@@ -8009,7 +8237,7 @@ async function searchObservations(options) {
8009
8237
  mark("embedding");
8010
8238
  const cjkRatio = (originalQuery.match(/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g) || []).length / originalQuery.length;
8011
8239
  const isCJKHeavy = cjkRatio > 0.3;
8012
- rememberSearchMode(modeKey, "hybrid");
8240
+ setMode("hybrid");
8013
8241
  searchParams = {
8014
8242
  ...searchParams,
8015
8243
  mode: "hybrid",
@@ -8032,32 +8260,41 @@ async function searchObservations(options) {
8032
8260
  embeddingUnavailable = true;
8033
8261
  fallbackUsed = true;
8034
8262
  fallbackReason = "embedding failed or timed out; lexical search used";
8035
- rememberSearchMode(modeKey, "fulltext (embedding unavailable)");
8263
+ setMode("fulltext (embedding unavailable)");
8036
8264
  console.error("[memorix] Embedding failed or timed out, falling back to fulltext search");
8037
8265
  }
8038
8266
  }
8039
8267
  mark("preSearch");
8040
8268
  let results;
8269
+ const retrieval = getResolvedConfig().retrieval;
8270
+ const wantLanceOrder = (isCjkHeavyQuery(originalQuery ?? "") ? retrieval.cjk : retrieval.ascii) === "vector";
8271
+ let lanceOrderUsed = false;
8272
+ let persistent = null;
8273
+ if (wantLanceOrder && queryVector && embeddingProviderForSearch) {
8274
+ persistent = await searchLanceInVectorOrder(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch);
8275
+ if (persistent) lanceOrderUsed = true;
8276
+ else {
8277
+ fallbackUsed = true;
8278
+ fallbackReason = fallbackReason ?? "lance vector index empty; hybrid search used";
8279
+ }
8280
+ }
8041
8281
  const persistentCorpusEligible = await shouldUsePersistentSearch(projectIds, options.projectId);
8042
8282
  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;
8283
+ if (!persistent) persistent = persistentCorpusEligible && queryVector && embeddingProviderForSearch ? await searchPersistentSemantically(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch) : canUsePersistentLexical ? await searchPersistentLexically(options, projectIds, requestLimit) : null;
8044
8284
  const durableStore = getOptionalObservationStore();
8045
8285
  if (!persistent && queryVector && durableStore?.hasLexicalIndex?.() && count(database) === 0) {
8046
8286
  persistent = await searchPersistentLexically(options, projectIds, requestLimit);
8047
8287
  }
8048
8288
  if (persistent) {
8049
8289
  results = persistent;
8050
- rememberSearchMode(
8051
- modeKey,
8052
- queryVector ? "hybrid" : quality === "fast" ? "fulltext (fast profile)" : "fulltext"
8053
- );
8290
+ setMode(lanceOrderUsed ? "vector" : queryVector ? "hybrid" : quality === "fast" ? "fulltext (fast profile)" : "fulltext");
8054
8291
  mark(queryVector ? "persistentHybridSearch" : "sqliteFtsSearch");
8055
8292
  } else {
8056
8293
  try {
8057
8294
  results = await search(database, searchParams);
8058
8295
  } catch (error) {
8059
8296
  if (queryVector && isVectorDimensionMismatchError(error)) {
8060
- rememberSearchMode(modeKey, "fulltext (embedding dimension mismatch)");
8297
+ setMode("fulltext (embedding dimension mismatch)");
8061
8298
  console.error("[memorix] Vector search dimension mismatch detected, retrying without embeddings");
8062
8299
  results = await search(database, stripVectorSearchParams(searchParams));
8063
8300
  } else {
@@ -8080,7 +8317,7 @@ async function searchObservations(options) {
8080
8317
  },
8081
8318
  similarity: 0.25
8082
8319
  };
8083
- rememberSearchMode(modeKey, "vector-only (hybrid empty fallback)");
8320
+ setMode("vector-only (hybrid empty fallback)");
8084
8321
  fallbackUsed = true;
8085
8322
  fallbackReason = "hybrid search returned no results; vector-only fallback used";
8086
8323
  results = await search(database, vectorOnlyParams);
@@ -8325,7 +8562,7 @@ async function searchObservations(options) {
8325
8562
  const rerankedTop = neural.map((row) => candidateMap.get(row.id)).filter((entry) => entry != null);
8326
8563
  if (rerankedTop.length > 0) {
8327
8564
  intermediate = [...rerankedTop, ...intermediate.slice(RERANK_TOP_K)];
8328
- rememberSearchMode(modeKey, (lastSearchModeByProject.get(modeKey) ?? "fulltext") + " + neural rerank");
8565
+ setMode(requestMode + " + neural rerank");
8329
8566
  mark("rerank(usedNeural=true)");
8330
8567
  }
8331
8568
  }
@@ -8342,7 +8579,7 @@ async function searchObservations(options) {
8342
8579
  );
8343
8580
  mark(`rerank(usedLLM=${usedLLM})`);
8344
8581
  if (usedLLM) {
8345
- rememberSearchMode(modeKey, (lastSearchModeByProject.get(modeKey) ?? "fulltext") + " + LLM rerank");
8582
+ setMode(requestMode + " + LLM rerank");
8346
8583
  const rerankedTop = reranked.map((row) => candidateMap.get(row.id)).filter((entry) => entry != null);
8347
8584
  if (rerankedTop.length > 0) {
8348
8585
  intermediate = [...rerankedTop, ...intermediate.slice(RERANK_TOP_K)];
@@ -8405,9 +8642,9 @@ async function searchObservations(options) {
8405
8642
  if (options.maxTokens && options.maxTokens > 0) {
8406
8643
  entries = applyTokenBudget(entries, options.maxTokens);
8407
8644
  }
8408
- rememberSearchDiagnostics(modeKey, {
8645
+ const diagnostics = {
8409
8646
  version: "1",
8410
- mode: getLastSearchMode(options.projectId),
8647
+ mode: requestMode,
8411
8648
  rawCandidateCount: results.hits.length,
8412
8649
  candidateCount,
8413
8650
  selectedCount: entries.length,
@@ -8416,14 +8653,25 @@ async function searchObservations(options) {
8416
8653
  fallbackUsed,
8417
8654
  ...fallbackReason ? { fallbackReason } : {},
8418
8655
  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)));
8656
+ };
8657
+ rememberSearchDiagnostics(modeKey, diagnostics);
8658
+ const recordAccess = (selected) => {
8659
+ if (options.trackAccess === false || selected.length === 0) return;
8660
+ const returnedKeys = new Set(selected.map((entry) => makeEntryKey(entry.projectId, entry.id)));
8422
8661
  const hitDocs = results.hits.map((hit) => ({ id: hit.id, doc: hit.document })).filter(({ doc }) => returnedKeys.has(makeEntryKey(doc.projectId, doc.observationId)));
8423
8662
  recordAccessBatch(hitDocs).catch(() => {
8424
8663
  });
8664
+ };
8665
+ const derivedViews = getSearchDerivedViews();
8666
+ if (fallbackUsed && fallbackReason) {
8667
+ derivedViews.embedding = { freshness: "stale", rebuildStatus: "failed", failureReason: fallbackReason };
8425
8668
  }
8426
- return entries;
8669
+ return { entries, diagnostics, derivedViews, recordAccess };
8670
+ }
8671
+ async function searchObservations(options) {
8672
+ const result = await searchObservationsDetailed(options);
8673
+ result.recordAccess?.(result.entries);
8674
+ return result.entries;
8427
8675
  }
8428
8676
  async function getObservationsByIds(ids, projectId) {
8429
8677
  const database = await getDb();
@@ -8548,6 +8796,10 @@ var init_orama_store = __esm({
8548
8796
  init_policy();
8549
8797
  init_timeout();
8550
8798
  init_obs_store();
8799
+ init_resolved_config();
8800
+ init_retrieval_strategy();
8801
+ init_semantic_view();
8802
+ init_retrieval_contracts();
8551
8803
  init_semantic_index();
8552
8804
  init_derived_view_receipt();
8553
8805
  db = null;
@@ -8674,6 +8926,24 @@ var init_entity_extractor = __esm({
8674
8926
  }
8675
8927
  });
8676
8928
 
8929
+ // src/core/maintenance-result.ts
8930
+ function assertMaintenanceProgress(progress) {
8931
+ if (!progress) return;
8932
+ const counts = [progress.attempted, progress.succeeded, progress.failed, progress.remaining];
8933
+ if (counts.some((count2) => !Number.isSafeInteger(count2) || count2 < 0)) {
8934
+ throw new Error("maintenance progress must contain non-negative safe integers");
8935
+ }
8936
+ if (progress.succeeded + progress.failed > progress.attempted) {
8937
+ throw new Error("maintenance progress outcomes exceed attempted work");
8938
+ }
8939
+ }
8940
+ var init_maintenance_result = __esm({
8941
+ "src/core/maintenance-result.ts"() {
8942
+ "use strict";
8943
+ init_esm_shims();
8944
+ }
8945
+ });
8946
+
8677
8947
  // src/runtime/maintenance-jobs.ts
8678
8948
  var maintenance_jobs_exports = {};
8679
8949
  __export(maintenance_jobs_exports, {
@@ -8683,7 +8953,7 @@ __export(maintenance_jobs_exports, {
8683
8953
  MaintenanceJobWorker: () => MaintenanceJobWorker,
8684
8954
  getMaintenanceRetryDelayMs: () => getMaintenanceRetryDelayMs
8685
8955
  });
8686
- import { randomUUID as randomUUID2 } from "crypto";
8956
+ import { randomUUID as randomUUID3 } from "crypto";
8687
8957
  function parsePayload(raw) {
8688
8958
  if (typeof raw !== "string" || !raw) return {};
8689
8959
  try {
@@ -8707,6 +8977,12 @@ function rowToJob(row) {
8707
8977
  ...row.lease_owner ? { leaseOwner: row.lease_owner } : {},
8708
8978
  ...row.lease_expires_at != null ? { leaseExpiresAt: Number(row.lease_expires_at) } : {},
8709
8979
  ...row.last_error ? { lastError: row.last_error } : {},
8980
+ ...Number(row.progress_recorded ?? 0) === 1 ? { progress: {
8981
+ attempted: Number(row.attempted ?? 0),
8982
+ succeeded: Number(row.succeeded ?? 0),
8983
+ failed: Number(row.failed ?? 0),
8984
+ remaining: Number(row.remaining ?? 0)
8985
+ } } : {},
8710
8986
  createdAt: Number(row.created_at),
8711
8987
  updatedAt: Number(row.updated_at),
8712
8988
  ...row.completed_at != null ? { completedAt: Number(row.completed_at) } : {}
@@ -8732,6 +9008,7 @@ var init_maintenance_jobs = __esm({
8732
9008
  "src/runtime/maintenance-jobs.ts"() {
8733
9009
  "use strict";
8734
9010
  init_esm_shims();
9011
+ init_maintenance_result();
8735
9012
  init_sqlite_db();
8736
9013
  init_secret_filter();
8737
9014
  MAINTENANCE_JOB_KINDS = [
@@ -8742,6 +9019,7 @@ var init_maintenance_jobs = __esm({
8742
9019
  "consolidation",
8743
9020
  "codegraph-refresh",
8744
9021
  "observation-qualify",
9022
+ "observation-project",
8745
9023
  "claim-derive",
8746
9024
  "claim-requalification",
8747
9025
  "knowledge-compile",
@@ -8780,6 +9058,16 @@ var init_maintenance_jobs = __esm({
8780
9058
  this.commit();
8781
9059
  return rowToJob(existing);
8782
9060
  }
9061
+ if (existing.status === "running") {
9062
+ this.db.prepare(`
9063
+ UPDATE maintenance_jobs
9064
+ SET rerun_requested = 1, payload_json = ?, updated_at = ?
9065
+ WHERE id = ?
9066
+ `).run(payloadJson, now3, existing.id);
9067
+ const updated2 = this.getRow(existing.id);
9068
+ this.commit();
9069
+ return rowToJob(updated2);
9070
+ }
8783
9071
  const nextRunAfter = Math.min(Number(existing.run_after), runAfter);
8784
9072
  this.db.prepare(`
8785
9073
  UPDATE maintenance_jobs
@@ -8810,7 +9098,7 @@ var init_maintenance_jobs = __esm({
8810
9098
  return rowToJob(revived);
8811
9099
  }
8812
9100
  }
8813
- const id = randomUUID2();
9101
+ const id = randomUUID3();
8814
9102
  this.db.prepare(`
8815
9103
  INSERT INTO maintenance_jobs (
8816
9104
  id, project_id, kind, dedupe_key, payload_json, status, attempts,
@@ -8907,8 +9195,10 @@ var init_maintenance_jobs = __esm({
8907
9195
  this.db.prepare(`
8908
9196
  UPDATE maintenance_jobs
8909
9197
  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,
9198
+ status = CASE WHEN attempts >= max_attempts AND rerun_requested = 0 THEN 'failed' ELSE 'retry' END,
9199
+ run_after = CASE WHEN attempts >= max_attempts AND rerun_requested = 0 THEN run_after ELSE ? END,
9200
+ attempts = CASE WHEN rerun_requested = 1 AND attempts >= max_attempts THEN 0 ELSE attempts END,
9201
+ rerun_requested = 0,
8912
9202
  lease_owner = NULL,
8913
9203
  lease_expires_at = NULL,
8914
9204
  last_error = COALESCE(last_error, 'worker lease expired'),
@@ -8971,14 +9261,55 @@ var init_maintenance_jobs = __esm({
8971
9261
  `).run(expiresAt, now3, id, workerId);
8972
9262
  return Number(result.changes) > 0;
8973
9263
  }
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);
9264
+ complete(id, workerId, now3 = Date.now(), progress) {
9265
+ assertMaintenanceProgress(progress);
9266
+ this.begin();
9267
+ try {
9268
+ const current = this.db.prepare(`
9269
+ SELECT rerun_requested FROM maintenance_jobs
9270
+ WHERE id = ? AND status = 'running' AND lease_owner = ?
9271
+ `).get(id, workerId);
9272
+ if (!current) {
9273
+ this.commit();
9274
+ return void 0;
9275
+ }
9276
+ if (Number(current.rerun_requested) === 1) {
9277
+ this.db.prepare(`
9278
+ UPDATE maintenance_jobs
9279
+ SET status = 'pending', attempts = 0, run_after = ?,
9280
+ rerun_requested = 0, lease_owner = NULL, lease_expires_at = NULL,
9281
+ attempted = 0, succeeded = 0, failed = 0, remaining = 0,
9282
+ progress_recorded = 0, last_error = NULL, completed_at = NULL,
9283
+ updated_at = ?
9284
+ WHERE id = ?
9285
+ `).run(now3, now3, id);
9286
+ } else {
9287
+ this.db.prepare(`
9288
+ UPDATE maintenance_jobs
9289
+ SET status = 'completed', lease_owner = NULL, lease_expires_at = NULL,
9290
+ attempted = COALESCE(?, attempted), succeeded = COALESCE(?, succeeded),
9291
+ failed = COALESCE(?, failed), remaining = COALESCE(?, remaining),
9292
+ progress_recorded = CASE WHEN ? THEN 1 ELSE progress_recorded END,
9293
+ completed_at = ?, updated_at = ?
9294
+ WHERE id = ?
9295
+ `).run(
9296
+ progress?.attempted ?? null,
9297
+ progress?.succeeded ?? null,
9298
+ progress?.failed ?? null,
9299
+ progress?.remaining ?? null,
9300
+ progress ? 1 : 0,
9301
+ now3,
9302
+ now3,
9303
+ id
9304
+ );
9305
+ }
9306
+ const updated = this.get(id);
9307
+ this.commit();
9308
+ return updated;
9309
+ } catch (error) {
9310
+ this.rollback();
9311
+ throw error;
9312
+ }
8982
9313
  }
8983
9314
  reschedule(id, workerId, options) {
8984
9315
  const now3 = options.now ?? Date.now();
@@ -8987,22 +9318,37 @@ var init_maintenance_jobs = __esm({
8987
9318
  const status = options.status === "retry" ? "retry" : "pending";
8988
9319
  const hasLastError = options.lastError !== void 0;
8989
9320
  const lastError = hasLastError ? errorText(options.lastError) : null;
9321
+ const progress = options.progress;
9322
+ assertMaintenanceProgress(progress);
8990
9323
  this.db.prepare(`
8991
9324
  UPDATE maintenance_jobs
8992
- SET status = ?, run_after = ?, attempts = CASE WHEN ? THEN 0 ELSE attempts END,
8993
- payload_json = COALESCE(?, payload_json),
9325
+ SET status = ?,
9326
+ run_after = CASE WHEN rerun_requested = 1 AND ? = 0 THEN ? ELSE ? END,
9327
+ attempts = CASE WHEN rerun_requested = 1 AND ? = 0 THEN 0 WHEN ? THEN 0 ELSE attempts END,
9328
+ payload_json = CASE WHEN rerun_requested = 1 THEN payload_json ELSE COALESCE(?, payload_json) END,
9329
+ attempted = COALESCE(?, attempted), succeeded = COALESCE(?, succeeded),
9330
+ failed = COALESCE(?, failed), remaining = COALESCE(?, remaining),
9331
+ progress_recorded = CASE WHEN ? THEN 1 ELSE progress_recorded END,
8994
9332
  last_error = CASE
8995
9333
  WHEN ? THEN NULL
8996
9334
  WHEN ? THEN ?
8997
9335
  ELSE last_error
8998
9336
  END,
8999
- lease_owner = NULL, lease_expires_at = NULL, updated_at = ?
9337
+ rerun_requested = 0, lease_owner = NULL, lease_expires_at = NULL, updated_at = ?
9000
9338
  WHERE id = ? AND status = 'running' AND lease_owner = ?
9001
9339
  `).run(
9002
9340
  status,
9341
+ status === "retry" ? 1 : 0,
9342
+ now3,
9003
9343
  now3 + delayMs,
9344
+ status === "retry" ? 1 : 0,
9004
9345
  options.resetAttempts ? 1 : 0,
9005
9346
  payloadJson,
9347
+ progress?.attempted ?? null,
9348
+ progress?.succeeded ?? null,
9349
+ progress?.failed ?? null,
9350
+ progress?.remaining ?? null,
9351
+ progress ? 1 : 0,
9006
9352
  options.clearLastError ? 1 : 0,
9007
9353
  hasLastError ? 1 : 0,
9008
9354
  lastError,
@@ -9020,6 +9366,15 @@ var init_maintenance_jobs = __esm({
9020
9366
  `).run(now3, now3, projectId, dedupeKey);
9021
9367
  return Number(result.changes ?? 0);
9022
9368
  }
9369
+ /** A successful foreground projection can acknowledge its pending outbox row. */
9370
+ acknowledgePending(projectId, kind, dedupeKey, now3 = Date.now()) {
9371
+ const result = this.db.prepare(`
9372
+ UPDATE maintenance_jobs
9373
+ SET status = 'completed', completed_at = ?, updated_at = ?
9374
+ WHERE project_id = ? AND kind = ? AND dedupe_key = ? AND status = 'pending'
9375
+ `).run(now3, now3, projectId, kind, dedupeKey);
9376
+ return Number(result.changes ?? 0);
9377
+ }
9023
9378
  fail(id, workerId, error, now3 = Date.now()) {
9024
9379
  this.begin();
9025
9380
  try {
@@ -9032,15 +9387,18 @@ var init_maintenance_jobs = __esm({
9032
9387
  return void 0;
9033
9388
  }
9034
9389
  const attempts = Number(current.attempts);
9035
- const exhausted = attempts >= Number(current.max_attempts);
9390
+ const rerunRequested = Number(current.rerun_requested) === 1;
9391
+ const exhausted = attempts >= Number(current.max_attempts) && !rerunRequested;
9036
9392
  const status = exhausted ? "failed" : "retry";
9037
9393
  const runAfter = exhausted ? Number(current.run_after) : now3 + getMaintenanceRetryDelayMs(attempts);
9394
+ const nextAttempts = rerunRequested && attempts >= Number(current.max_attempts) ? 0 : attempts;
9038
9395
  this.db.prepare(`
9039
9396
  UPDATE maintenance_jobs
9040
- SET status = ?, run_after = ?, lease_owner = NULL, lease_expires_at = NULL,
9397
+ SET status = ?, run_after = ?, attempts = ?, rerun_requested = 0,
9398
+ lease_owner = NULL, lease_expires_at = NULL,
9041
9399
  last_error = ?, updated_at = ?
9042
9400
  WHERE id = ?
9043
- `).run(status, runAfter, errorText(error), now3, id);
9401
+ `).run(status, runAfter, nextAttempts, errorText(error), now3, id);
9044
9402
  const updated = this.getRow(id);
9045
9403
  this.commit();
9046
9404
  return rowToJob(updated);
@@ -9069,7 +9427,7 @@ var init_maintenance_jobs = __esm({
9069
9427
  constructor(store, handler, options = {}) {
9070
9428
  this.store = store;
9071
9429
  this.handler = handler;
9072
- this.workerId = options.workerId ?? `memorix-${process.pid}-${randomUUID2().slice(0, 8)}`;
9430
+ this.workerId = options.workerId ?? `memorix-${process.pid}-${randomUUID3().slice(0, 8)}`;
9073
9431
  this.leaseMs = clampPositiveInteger(options.leaseMs, DEFAULT_LEASE_MS);
9074
9432
  this.pollIntervalMs = clampPositiveInteger(options.pollIntervalMs, DEFAULT_POLL_INTERVAL_MS);
9075
9433
  this.projectId = options.projectId;
@@ -9118,12 +9476,16 @@ var init_maintenance_jobs = __esm({
9118
9476
  status: result.status,
9119
9477
  lastError: result.lastError,
9120
9478
  clearLastError: result.clearLastError,
9479
+ progress: result.progress,
9121
9480
  now: now3
9122
9481
  });
9123
9482
  return { state: "rescheduled", job: updated2 };
9124
9483
  }
9125
- const updated = this.store.complete(job.id, this.workerId, now3);
9126
- return { state: "completed", job: updated };
9484
+ if (result?.progress && result.progress.remaining > 0) {
9485
+ throw new Error("maintenance job reported completion with remaining work");
9486
+ }
9487
+ const updated = this.store.complete(job.id, this.workerId, now3, result?.progress);
9488
+ return { state: updated?.status === "pending" ? "rescheduled" : "completed", job: updated };
9127
9489
  } catch (error) {
9128
9490
  const updated = this.store.fail(job.id, this.workerId, error, now3);
9129
9491
  return { state: "failed", job: updated };
@@ -9221,7 +9583,12 @@ var init_lifecycle = __esm({
9221
9583
  });
9222
9584
 
9223
9585
  // src/store/evidence-store.ts
9224
- import { createHash as createHash5, randomUUID as randomUUID3 } from "crypto";
9586
+ var evidence_store_exports = {};
9587
+ __export(evidence_store_exports, {
9588
+ EvidenceCardStore: () => EvidenceCardStore,
9589
+ buildEvidenceCardId: () => buildEvidenceCardId
9590
+ });
9591
+ import { createHash as createHash5, randomUUID as randomUUID4 } from "crypto";
9225
9592
  function safeJson(value, fallback) {
9226
9593
  if (typeof value !== "string" || value.length === 0) return fallback;
9227
9594
  try {
@@ -9270,6 +9637,9 @@ function sourceKind(observation) {
9270
9637
  if (observation.sourceDetail === "hook") return "hook";
9271
9638
  return observation.source ?? "agent";
9272
9639
  }
9640
+ function buildEvidenceCardId(projectId, candidateKind, candidateId) {
9641
+ return `evidence:${candidateKind}:${projectId}:${candidateId}`;
9642
+ }
9273
9643
  var EvidenceCardStore;
9274
9644
  var init_evidence_store = __esm({
9275
9645
  "src/store/evidence-store.ts"() {
@@ -9410,7 +9780,7 @@ var init_evidence_store = __esm({
9410
9780
  }
9411
9781
  recordEvent(projectId, cardId, kind, detail) {
9412
9782
  const event = {
9413
- id: randomUUID3(),
9783
+ id: randomUUID4(),
9414
9784
  projectId,
9415
9785
  cardId,
9416
9786
  kind,
@@ -9478,7 +9848,7 @@ var store_exports = {};
9478
9848
  __export(store_exports, {
9479
9849
  CodeGraphStore: () => CodeGraphStore
9480
9850
  });
9481
- import { randomUUID as randomUUID4 } from "crypto";
9851
+ import { randomUUID as randomUUID5 } from "crypto";
9482
9852
  import { posix as pathPosix } from "path";
9483
9853
  function rowToFile(row) {
9484
9854
  return {
@@ -10407,7 +10777,7 @@ var init_store = __esm({
10407
10777
  * so an interrupted scan cannot be advertised as complete.
10408
10778
  */
10409
10779
  recordCodeStateSnapshot(input) {
10410
- const id = randomUUID4();
10780
+ const id = randomUUID5();
10411
10781
  let snapshot;
10412
10782
  let compactNeeded = false;
10413
10783
  const tx = this.db.transaction(() => {
@@ -10807,24 +11177,40 @@ function queueVectorBackfill(projectId, options = {}) {
10807
11177
  });
10808
11178
  }
10809
11179
  async function bindObservationCodeRefsBestEffort(observation) {
10810
- if (!projectDir) return;
11180
+ if (!projectDir) return true;
10811
11181
  try {
10812
11182
  const { CodeGraphStore: CodeGraphStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
10813
11183
  const { bindObservationToCode: bindObservationToCode2 } = await Promise.resolve().then(() => (init_binder(), binder_exports));
10814
11184
  const codeStore = new CodeGraphStore2();
10815
11185
  await codeStore.init(projectDir);
10816
11186
  await bindObservationToCode2(codeStore, observation);
11187
+ return true;
10817
11188
  } catch {
11189
+ return false;
10818
11190
  }
10819
11191
  }
10820
11192
  async function persistEvidenceCard(observation) {
10821
- if (!projectDir) return;
11193
+ if (!projectDir) return true;
10822
11194
  try {
10823
11195
  const evidence = new EvidenceCardStore();
10824
11196
  await evidence.init(projectDir);
10825
11197
  evidence.upsertObservation(observation);
11198
+ return true;
10826
11199
  } catch (error) {
10827
11200
  console.error(`[memorix] Evidence card projection failed for obs-${observation.id}: ${error instanceof Error ? error.message : String(error)}`);
11201
+ return false;
11202
+ }
11203
+ }
11204
+ async function acknowledgeObservationProjection(observation) {
11205
+ if (!projectDir) return;
11206
+ try {
11207
+ const { MaintenanceJobStore: MaintenanceJobStore2 } = await Promise.resolve().then(() => (init_maintenance_jobs(), maintenance_jobs_exports));
11208
+ new MaintenanceJobStore2(projectDir).acknowledgePending(
11209
+ observation.projectId,
11210
+ "observation-project",
11211
+ "observation-project:" + observation.id
11212
+ );
11213
+ } catch {
10828
11214
  }
10829
11215
  }
10830
11216
  function queueClaimDerivation(observation) {
@@ -10853,6 +11239,41 @@ function queueObservationQualification(observation) {
10853
11239
  } catch {
10854
11240
  }
10855
11241
  }
11242
+ async function enqueueObservationDerivedWork(tx, observation) {
11243
+ if (!tx.enqueueMaintenanceJob) return false;
11244
+ if (!isEmbeddingExplicitlyDisabled()) {
11245
+ await tx.enqueueMaintenanceJob({
11246
+ projectId: observation.projectId,
11247
+ kind: "vector-backfill",
11248
+ dedupeKey: "vector-backfill",
11249
+ payload: { limit: 12 }
11250
+ });
11251
+ }
11252
+ if (observation.admissionState === "candidate") {
11253
+ await tx.enqueueMaintenanceJob({
11254
+ projectId: observation.projectId,
11255
+ kind: "observation-qualify",
11256
+ dedupeKey: "observation-qualify",
11257
+ payload: { source: "automatic-capture:" + observation.id, limit: 100 }
11258
+ });
11259
+ }
11260
+ const claimSource = observation.sourceDetail === "explicit" || observation.source === "git" || observation.sourceDetail === "git-ingest";
11261
+ if (claimSource && resolveObservationVisibility(observation) === "project") {
11262
+ await tx.enqueueMaintenanceJob({
11263
+ projectId: observation.projectId,
11264
+ kind: "claim-derive",
11265
+ dedupeKey: "claim-derive:" + observation.id,
11266
+ payload: { observationId: observation.id }
11267
+ });
11268
+ }
11269
+ await tx.enqueueMaintenanceJob({
11270
+ projectId: observation.projectId,
11271
+ kind: "observation-project",
11272
+ dedupeKey: "observation-project:" + observation.id,
11273
+ payload: { observationId: observation.id }
11274
+ });
11275
+ return true;
11276
+ }
10856
11277
  function isVectorCompatibleWithCurrentIndex(embedding) {
10857
11278
  if (!embedding) return false;
10858
11279
  const vectorDimensions = getVectorDimensions();
@@ -11031,7 +11452,6 @@ async function storeObservation(input) {
11031
11452
  throw new Error("Cannot update a memory outside this session's write scope.");
11032
11453
  }
11033
11454
  const observation2 = await upsertObservation(existing, input, now3);
11034
- await input.onPersisted?.(observation2);
11035
11455
  return { observation: observation2, upserted: true };
11036
11456
  }
11037
11457
  }
@@ -11058,6 +11478,7 @@ async function storeObservation(input) {
11058
11478
  let upsertedInsideLock = false;
11059
11479
  let reloadCacheAfterCommit = false;
11060
11480
  let persistedCallbackInvoked = false;
11481
+ let derivedJobsCommitted = false;
11061
11482
  const assignAndPersist = async () => {
11062
11483
  if (projectDir) {
11063
11484
  const store = getObservationStore();
@@ -11113,6 +11534,7 @@ async function storeObservation(input) {
11113
11534
  writeGeneration: transactionGeneration + 1
11114
11535
  };
11115
11536
  await tx.insert(observation);
11537
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, observation);
11116
11538
  await input.onPersisted?.(observation);
11117
11539
  persistedCallbackInvoked = true;
11118
11540
  await tx.saveIdCounter(id + 1);
@@ -11211,15 +11633,17 @@ async function storeObservation(input) {
11211
11633
  await assignAndPersist();
11212
11634
  if (upsertedInsideLock) {
11213
11635
  const updated = await upsertObservation(observation, input, now3);
11214
- await input.onPersisted?.(updated);
11215
11636
  return { observation: updated, upserted: true };
11216
11637
  }
11217
11638
  if (!persistedCallbackInvoked) await input.onPersisted?.(observation);
11218
- await bindObservationCodeRefsBestEffort(observation);
11219
- await persistEvidenceCard(observation);
11220
- queueObservationQualification(observation);
11221
- if (resolveObservationVisibility(observation) === "project") {
11222
- queueClaimDerivation(observation);
11639
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(observation);
11640
+ const evidenceProjected = await persistEvidenceCard(observation);
11641
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(observation);
11642
+ if (!derivedJobsCommitted) {
11643
+ queueObservationQualification(observation);
11644
+ if (resolveObservationVisibility(observation) === "project") {
11645
+ queueClaimDerivation(observation);
11646
+ }
11223
11647
  }
11224
11648
  scheduleObservationEmbedding({
11225
11649
  observationId: observation.id,
@@ -11241,86 +11665,115 @@ async function upsertObservation(existing, input, now3) {
11241
11665
  }
11242
11666
  const fullText = [input.title, input.narrative, ...input.facts ?? [], ...enrichedFiles, ...enrichedConcepts].join(" ");
11243
11667
  const tokens = countTextTokens(fullText);
11244
- existing.entityName = input.entityName;
11245
- existing.type = input.type;
11246
- existing.title = input.title;
11247
- existing.narrative = input.narrative;
11248
- existing.facts = input.facts ?? [];
11249
- existing.attachments = input.attachments;
11250
- existing.filesModified = enrichedFiles;
11251
- existing.concepts = enrichedConcepts;
11252
- existing.tokens = tokens;
11253
- existing.updatedAt = now3;
11254
- existing.hasCausalLanguage = extracted.hasCausalLanguage;
11255
- existing.revisionCount = (existing.revisionCount ?? 1) + 1;
11256
- existing.status = "active";
11257
- if (input.sessionId) existing.sessionId = input.sessionId;
11258
- if (input.progress) existing.progress = input.progress;
11259
- if (input.sourceDetail !== void 0) existing.sourceDetail = input.sourceDetail;
11260
- if (input.valueCategory !== void 0) existing.valueCategory = input.valueCategory;
11261
- if (input.admissionState !== void 0) existing.admissionState = input.admissionState;
11262
- if (input.admissionReason !== void 0) existing.admissionReason = sanitizeCredentials(input.admissionReason);
11263
- if (input.visibility !== void 0) existing.visibility = input.visibility;
11264
- if (input.sharedWithAgentIds !== void 0) existing.sharedWithAgentIds = input.sharedWithAgentIds;
11668
+ const applyUpdate = (current) => ({
11669
+ ...current,
11670
+ entityName: input.entityName,
11671
+ type: input.type,
11672
+ title: input.title,
11673
+ narrative: input.narrative,
11674
+ facts: input.facts ?? [],
11675
+ attachments: input.attachments,
11676
+ filesModified: enrichedFiles,
11677
+ concepts: enrichedConcepts,
11678
+ tokens,
11679
+ updatedAt: now3,
11680
+ hasCausalLanguage: extracted.hasCausalLanguage,
11681
+ revisionCount: (current.revisionCount ?? 1) + 1,
11682
+ status: "active",
11683
+ ...input.sessionId ? { sessionId: input.sessionId } : {},
11684
+ ...input.progress ? { progress: input.progress } : {},
11685
+ ...input.sourceDetail !== void 0 ? { sourceDetail: input.sourceDetail } : {},
11686
+ ...input.valueCategory !== void 0 ? { valueCategory: input.valueCategory } : {},
11687
+ ...input.admissionState !== void 0 ? { admissionState: input.admissionState } : {},
11688
+ ...input.admissionReason !== void 0 ? { admissionReason: sanitizeCredentials(input.admissionReason) } : {},
11689
+ ...input.visibility !== void 0 ? { visibility: input.visibility } : {},
11690
+ ...input.sharedWithAgentIds !== void 0 ? { sharedWithAgentIds: input.sharedWithAgentIds } : {}
11691
+ });
11692
+ let updated = applyUpdate(existing);
11693
+ let derivedJobsCommitted = false;
11694
+ if (projectDir) {
11695
+ const store = getObservationStore();
11696
+ await store.atomic(async (tx) => {
11697
+ const current = await tx.getById(existing.id);
11698
+ if (!current || current.projectId !== existing.projectId) {
11699
+ throw new Error("Topic observation changed before update");
11700
+ }
11701
+ updated = applyUpdate(current);
11702
+ updated.writeGeneration = await tx.getGeneration() + 1;
11703
+ await tx.update(updated);
11704
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, updated);
11705
+ await input.onPersisted?.(updated);
11706
+ });
11707
+ updated.writeGeneration = store.getGeneration();
11708
+ } else {
11709
+ await input.onPersisted?.(updated);
11710
+ }
11711
+ if (corpusLoaded) {
11712
+ const cacheIndex = observations.findIndex((observation) => observation.id === updated.id);
11713
+ if (cacheIndex >= 0) observations[cacheIndex] = updated;
11714
+ }
11265
11715
  const doc = {
11266
- id: makeOramaObservationId(existing.projectId, existing.id),
11267
- observationId: existing.id,
11268
- entityName: existing.entityName,
11269
- type: existing.type,
11270
- title: existing.title,
11271
- narrative: existing.narrative,
11272
- facts: existing.facts.join("\n"),
11716
+ id: makeOramaObservationId(updated.projectId, updated.id),
11717
+ observationId: updated.id,
11718
+ entityName: updated.entityName,
11719
+ type: updated.type,
11720
+ title: updated.title,
11721
+ narrative: updated.narrative,
11722
+ facts: updated.facts.join("\n"),
11273
11723
  filesModified: enrichedFiles.join("\n"),
11274
11724
  concepts: enrichedConcepts.map((c) => c.replace(/-/g, " ")).join(", "),
11275
- attachments: formatAttachmentProvenance(existing.attachments),
11725
+ attachments: formatAttachmentProvenance(updated.attachments),
11276
11726
  tokens,
11277
- createdAt: existing.createdAt,
11278
- projectId: existing.projectId,
11727
+ createdAt: updated.createdAt,
11728
+ projectId: updated.projectId,
11279
11729
  accessCount: 0,
11280
11730
  lastAccessedAt: "",
11281
11731
  status: "active",
11282
- source: existing.source ?? "agent",
11283
- sourceDetail: existing.sourceDetail ?? "",
11284
- valueCategory: existing.valueCategory ?? "",
11285
- admissionState: existing.admissionState ?? "",
11286
- admissionReason: existing.admissionReason ?? "",
11287
- visibility: existing.visibility ?? "project",
11288
- createdByAgentId: existing.createdByAgentId ?? "",
11289
- sharedWithAgentIds: JSON.stringify(existing.sharedWithAgentIds ?? [])
11290
- };
11291
- const oramaId = makeOramaObservationId(existing.projectId, existing.id);
11292
- try {
11293
- const { removeObservation: removeObservation2 } = await Promise.resolve().then(() => (init_orama_store(), orama_store_exports));
11294
- await removeObservation2(oramaId);
11295
- } catch {
11296
- }
11297
- try {
11298
- await insertObservation(doc);
11299
- } catch {
11732
+ source: updated.source ?? "agent",
11733
+ sourceDetail: updated.sourceDetail ?? "",
11734
+ valueCategory: updated.valueCategory ?? "",
11735
+ admissionState: updated.admissionState ?? "",
11736
+ admissionReason: updated.admissionReason ?? "",
11737
+ visibility: updated.visibility ?? "project",
11738
+ createdByAgentId: updated.createdByAgentId ?? "",
11739
+ sharedWithAgentIds: JSON.stringify(updated.sharedWithAgentIds ?? [])
11740
+ };
11741
+ if (corpusLoaded) {
11742
+ const oramaId = makeOramaObservationId(updated.projectId, updated.id);
11300
11743
  try {
11301
- const { removeObservation: removeObs } = await Promise.resolve().then(() => (init_orama_store(), orama_store_exports));
11302
- await removeObs(oramaId);
11744
+ try {
11745
+ await removeObservation(oramaId);
11746
+ } catch {
11747
+ }
11303
11748
  await insertObservation(doc);
11304
11749
  } catch {
11750
+ try {
11751
+ try {
11752
+ await removeObservation(oramaId);
11753
+ } catch {
11754
+ }
11755
+ await insertObservation(doc);
11756
+ } catch (error) {
11757
+ console.error(`[memorix] Observation index projection failed for obs-${updated.id}: ${sanitizeCredentials(error instanceof Error ? error.message : String(error))}`);
11758
+ }
11305
11759
  }
11306
11760
  }
11307
- if (projectDir) {
11308
- const store = getObservationStore();
11309
- await store.update(existing);
11310
- }
11311
- await bindObservationCodeRefsBestEffort(existing);
11312
- await persistEvidenceCard(existing);
11313
- queueObservationQualification(existing);
11314
- if (resolveObservationVisibility(existing) === "project") {
11315
- queueClaimDerivation(existing);
11761
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(updated);
11762
+ const evidenceProjected = await persistEvidenceCard(updated);
11763
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(updated);
11764
+ if (!derivedJobsCommitted) {
11765
+ queueObservationQualification(updated);
11766
+ if (resolveObservationVisibility(updated) === "project") {
11767
+ queueClaimDerivation(updated);
11768
+ }
11316
11769
  }
11317
11770
  scheduleObservationEmbedding({
11318
- observationId: existing.id,
11319
- projectId: existing.projectId,
11771
+ observationId: updated.id,
11772
+ projectId: updated.projectId,
11320
11773
  searchableText: [input.title, input.narrative, ...input.facts ?? []].join(" "),
11321
11774
  doc
11322
11775
  });
11323
- return existing;
11776
+ return updated;
11324
11777
  }
11325
11778
  function getObservation(id, projectId) {
11326
11779
  return observations.find((o) => o.id === id && (projectId ? o.projectId === projectId : true));
@@ -11664,7 +12117,7 @@ function getSearchIndexStatus(projectId) {
11664
12117
  };
11665
12118
  }
11666
12119
  async function probeSearchIndex(projectId) {
11667
- await searchObservations({
12120
+ const result = await searchObservationsDetailed({
11668
12121
  query: "semantic memory retrieval status",
11669
12122
  projectId,
11670
12123
  reader: { projectId },
@@ -11672,7 +12125,7 @@ async function probeSearchIndex(projectId) {
11672
12125
  status: "all",
11673
12126
  trackAccess: false
11674
12127
  });
11675
- return getLastSearchMode(projectId);
12128
+ return result.diagnostics.mode;
11676
12129
  }
11677
12130
  async function backfillVectorEmbeddings(options = {}) {
11678
12131
  if (vectorBackfillRunning) {
@@ -11899,7 +12352,7 @@ var init_maintenance_targets = __esm({
11899
12352
  });
11900
12353
 
11901
12354
  // src/knowledge/workspace-store.ts
11902
- import { randomUUID as randomUUID5 } from "crypto";
12355
+ import { randomUUID as randomUUID6 } from "crypto";
11903
12356
  function arrayValue(raw) {
11904
12357
  if (typeof raw !== "string" || !raw) return [];
11905
12358
  try {
@@ -12040,7 +12493,7 @@ var init_workspace_store = __esm({
12040
12493
  }
12041
12494
  createProposal(input) {
12042
12495
  const proposal = {
12043
- id: input.id ?? randomUUID5(),
12496
+ id: input.id ?? randomUUID6(),
12044
12497
  ...input,
12045
12498
  status: input.status ?? "pending",
12046
12499
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
@@ -12326,11 +12779,11 @@ __export(consolidation_exports, {
12326
12779
  });
12327
12780
  function tokenize(text2) {
12328
12781
  return new Set(
12329
- text2.toLowerCase().replace(/[^a-z0-9\u4e00-\u9fff\s-]/g, " ").split(/\s+/).filter((t2) => t2.length > 1)
12782
+ text2.normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, " ").split(/\s+/).filter((t2) => t2.length > 1)
12330
12783
  );
12331
12784
  }
12332
12785
  function jaccardSimilarity(a, b) {
12333
- if (a.size === 0 && b.size === 0) return 1;
12786
+ if (a.size === 0 && b.size === 0) return 0;
12334
12787
  let intersection = 0;
12335
12788
  for (const token of a) {
12336
12789
  if (b.has(token)) intersection++;
@@ -12696,7 +13149,7 @@ Respond in JSON only:
12696
13149
  });
12697
13150
 
12698
13151
  // src/media/media-store.ts
12699
- import { randomUUID as randomUUID6 } from "crypto";
13152
+ import { randomUUID as randomUUID7 } from "crypto";
12700
13153
  function asOptionalText(value) {
12701
13154
  return typeof value === "string" && value.length > 0 ? value : void 0;
12702
13155
  }
@@ -12866,7 +13319,7 @@ var init_media_store = __esm({
12866
13319
  return { asset: this.getAsset(input.projectId, existing.id), deduplicated: true };
12867
13320
  }
12868
13321
  const asset = {
12869
- id: randomUUID6(),
13322
+ id: randomUUID7(),
12870
13323
  ...input,
12871
13324
  createdAt: now3,
12872
13325
  updatedAt: now3
@@ -12946,7 +13399,7 @@ var init_media_store = __esm({
12946
13399
  `).get(input.assetId, input.observationId ?? null, input.role);
12947
13400
  if (existing) return rowToLink(existing);
12948
13401
  const link = {
12949
- id: randomUUID6(),
13402
+ id: randomUUID7(),
12950
13403
  assetId: input.assetId,
12951
13404
  projectId: input.projectId,
12952
13405
  ...input.observationId !== void 0 ? { observationId: input.observationId } : {},
@@ -12985,7 +13438,7 @@ var init_media_store = __esm({
12985
13438
  return rowToDerivation(this.db.prepare("SELECT * FROM media_derivations WHERE id = ?").get(existing.id));
12986
13439
  }
12987
13440
  const derivation = {
12988
- id: randomUUID6(),
13441
+ id: randomUUID7(),
12989
13442
  ...input,
12990
13443
  content,
12991
13444
  ...error ? { error } : {},
@@ -13072,7 +13525,7 @@ var init_media_store = __esm({
13072
13525
  createJob(input) {
13073
13526
  const now3 = Date.now();
13074
13527
  const job = {
13075
- id: randomUUID6(),
13528
+ id: randomUUID7(),
13076
13529
  projectId: input.projectId,
13077
13530
  kind: input.kind,
13078
13531
  status: "queued",
@@ -13234,7 +13687,7 @@ var init_types2 = __esm({
13234
13687
  });
13235
13688
 
13236
13689
  // src/media/asset-store.ts
13237
- import { createHash as createHash8, randomUUID as randomUUID7 } from "crypto";
13690
+ import { createHash as createHash8, randomUUID as randomUUID8 } from "crypto";
13238
13691
  import { copyFile, lstat, mkdir as mkdir3, open, readFile as readFile3, readdir, rename as rename2, rm, stat as stat2, writeFile as writeFile3 } from "fs/promises";
13239
13692
  import path11 from "path";
13240
13693
  function mediaRoot(dataDir) {
@@ -13305,7 +13758,7 @@ async function destinationExists(destination) {
13305
13758
  async function persistBuffer(bytes, destination) {
13306
13759
  await mkdir3(path11.dirname(destination), { recursive: true });
13307
13760
  if (await destinationExists(destination)) return false;
13308
- const temporary = `${destination}.${randomUUID7()}.tmp`;
13761
+ const temporary = `${destination}.${randomUUID8()}.tmp`;
13309
13762
  try {
13310
13763
  await writeFile3(temporary, bytes, { flag: "wx" });
13311
13764
  await rename2(temporary, destination);
@@ -66207,7 +66660,7 @@ var require_gaxios = __commonJS({
66207
66660
  var retry_js_1 = require_retry3();
66208
66661
  var stream_1 = __require("stream");
66209
66662
  var interceptor_js_1 = require_interceptor();
66210
- var randomUUID16 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
66663
+ var randomUUID17 = async () => globalThis.crypto?.randomUUID() || (await import("crypto")).randomUUID();
66211
66664
  var HTTP_STATUS_NO_CONTENT = 204;
66212
66665
  var Gaxios = class {
66213
66666
  agentCache = /* @__PURE__ */ new Map();
@@ -66480,7 +66933,7 @@ var require_gaxios = __commonJS({
66480
66933
  */
66481
66934
  ["Blob", "File", "FormData"].includes(opts.data?.constructor?.name || "");
66482
66935
  if (opts.multipart?.length) {
66483
- const boundary = await randomUUID16();
66936
+ const boundary = await randomUUID17();
66484
66937
  preparedHeaders.set("content-type", `multipart/related; boundary=${boundary}`);
66485
66938
  opts.body = stream_1.Readable.from(this.getMultipartRequest(opts.multipart, boundary));
66486
66939
  } else if (shouldDirectlyPassData) {
@@ -147235,14 +147688,23 @@ var init_audio_jobs = __esm({
147235
147688
  }
147236
147689
  });
147237
147690
 
147238
- // src/memory/feedback-model.ts
147691
+ // src/core/retrieval-policy.ts
147239
147692
  function feedbackWeightMultiplier(weight) {
147240
147693
  return Math.max(0.35, Math.min(1.4, 0.35 + Math.max(0, Math.min(2, weight)) * 0.525));
147241
147694
  }
147695
+ var init_retrieval_policy = __esm({
147696
+ "src/core/retrieval-policy.ts"() {
147697
+ "use strict";
147698
+ init_esm_shims();
147699
+ }
147700
+ });
147701
+
147702
+ // src/memory/feedback-model.ts
147242
147703
  var init_feedback_model = __esm({
147243
147704
  "src/memory/feedback-model.ts"() {
147244
147705
  "use strict";
147245
147706
  init_esm_shims();
147707
+ init_retrieval_policy();
147246
147708
  }
147247
147709
  });
147248
147710
 
@@ -147254,7 +147716,7 @@ __export(feedback_exports, {
147254
147716
  applyMemoryFeedback: () => applyMemoryFeedback,
147255
147717
  feedbackWeightMultiplier: () => feedbackWeightMultiplier
147256
147718
  });
147257
- import { randomUUID as randomUUID8 } from "crypto";
147719
+ import { randomUUID as randomUUID9 } from "crypto";
147258
147720
  function applyMemoryFeedback(current, event) {
147259
147721
  const delta = event.signal === "revoke" ? 0 : FEEDBACK_DELTAS[event.signal];
147260
147722
  const weight = Math.max(0, Math.min(2, current.weight + delta));
@@ -147372,7 +147834,7 @@ var init_feedback = __esm({
147372
147834
  if (!target) throw new Error("The feedback event to revoke was not found in the same candidate scope.");
147373
147835
  }
147374
147836
  const event = {
147375
- id: randomUUID8(),
147837
+ id: randomUUID9(),
147376
147838
  projectId: input.projectId,
147377
147839
  candidateKind: input.candidateKind,
147378
147840
  candidateId: input.candidateId,
@@ -147760,7 +148222,7 @@ var init_retention = __esm({
147760
148222
  });
147761
148223
 
147762
148224
  // src/memory/owner.ts
147763
- import { randomUUID as randomUUID9 } from "crypto";
148225
+ import { randomUUID as randomUUID10 } from "crypto";
147764
148226
  import { promises as fs9 } from "fs";
147765
148227
  import path17 from "path";
147766
148228
  function ownerPath(dataDir) {
@@ -147790,7 +148252,7 @@ async function resolveLocalMemoryOwner(dataDir, options = {}) {
147790
148252
  await fs9.mkdir(path17.dirname(filePath), { recursive: true });
147791
148253
  const created = {
147792
148254
  version: 1,
147793
- id: "local-" + randomUUID9(),
148255
+ id: "local-" + randomUUID10(),
147794
148256
  createdAt: (/* @__PURE__ */ new Date()).toISOString()
147795
148257
  };
147796
148258
  try {
@@ -147813,7 +148275,7 @@ var init_owner = __esm({
147813
148275
  });
147814
148276
 
147815
148277
  // src/memory/long-term-store.ts
147816
- import { randomUUID as randomUUID10 } from "crypto";
148278
+ import { randomUUID as randomUUID11 } from "crypto";
147817
148279
  function optionalText2(value) {
147818
148280
  return typeof value === "string" && value.trim() ? value : void 0;
147819
148281
  }
@@ -147973,7 +148435,7 @@ var init_long_term_store = __esm({
147973
148435
  }
147974
148436
  insertEvidence(input) {
147975
148437
  const evidence = {
147976
- id: randomUUID10(),
148438
+ id: randomUUID11(),
147977
148439
  ...input,
147978
148440
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
147979
148441
  };
@@ -148000,7 +148462,7 @@ var init_long_term_store = __esm({
148000
148462
  }
148001
148463
  recordEvent(input) {
148002
148464
  const event = {
148003
- id: randomUUID10(),
148465
+ id: randomUUID11(),
148004
148466
  ...input,
148005
148467
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
148006
148468
  };
@@ -148090,7 +148552,7 @@ __export(long_term_exports, {
148090
148552
  selectLongTermMemoriesForTask: () => selectLongTermMemoriesForTask,
148091
148553
  supersedeLongTermMemory: () => supersedeLongTermMemory
148092
148554
  });
148093
- import { randomUUID as randomUUID11 } from "crypto";
148555
+ import { randomUUID as randomUUID12 } from "crypto";
148094
148556
  function isOneOf(value, values) {
148095
148557
  return typeof value === "string" && values.includes(value);
148096
148558
  }
@@ -148272,7 +148734,7 @@ async function createManualLongTermMemory(input) {
148272
148734
  const owner = await resolveLocalMemoryOwner(input.dataDir, { create: true });
148273
148735
  if (!owner) throw new Error("Memorix could not resolve a local memory owner.");
148274
148736
  assertScope(input.scope);
148275
- const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID11(), relation: "supports" }];
148737
+ const evidence = input.scope === "user" ? [{ kind: "user", referenceId: owner.id, relation: "user-confirmed" }] : [{ kind: "manual", referenceId: "manual:" + randomUUID12(), relation: "supports" }];
148276
148738
  return createLongTermMemoryWithDataDir({
148277
148739
  dataDir: input.dataDir,
148278
148740
  originProjectId: input.projectId,
@@ -148327,7 +148789,7 @@ async function createLongTermMemoryWithDataDir(input) {
148327
148789
  assertPortableEvidence(input.scope, portability, evidenceInputs);
148328
148790
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
148329
148791
  const memory = {
148330
- id: randomUUID11(),
148792
+ id: randomUUID12(),
148331
148793
  originProjectId: compactText(input.originProjectId, "origin project id", 1e3),
148332
148794
  ownerId: compactText(input.ownerId, "owner id", 160),
148333
148795
  scope: input.scope,
@@ -149599,7 +150061,7 @@ var claim_store_exports = {};
149599
150061
  __export(claim_store_exports, {
149600
150062
  ClaimStore: () => ClaimStore
149601
150063
  });
149602
- import { createHash as createHash12, randomUUID as randomUUID12 } from "crypto";
150064
+ import { createHash as createHash12, randomUUID as randomUUID13 } from "crypto";
149603
150065
  function optionalText3(value) {
149604
150066
  return typeof value === "string" && value ? value : void 0;
149605
150067
  }
@@ -149783,7 +150245,7 @@ var init_claim_store = __esm({
149783
150245
  locator, capturedHash, evidenceKey, createdAt
149784
150246
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
149785
150247
  `).run(
149786
- randomUUID12(),
150248
+ randomUUID13(),
149787
150249
  input.claimId,
149788
150250
  input.evidenceKind,
149789
150251
  input.evidenceId,
@@ -149805,7 +150267,7 @@ var init_claim_store = __esm({
149805
150267
  }
149806
150268
  recordEvent(input) {
149807
150269
  const event = {
149808
- id: randomUUID12(),
150270
+ id: randomUUID13(),
149809
150271
  ...input,
149810
150272
  ...input.detail ? { detail: sanitizeCredentials(input.detail) } : {},
149811
150273
  createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString()
@@ -149850,7 +150312,7 @@ __export(claims_exports, {
149850
150312
  supersedeClaim: () => supersedeClaim,
149851
150313
  writeClaim: () => writeClaim
149852
150314
  });
149853
- import { createHash as createHash13, randomUUID as randomUUID13 } from "crypto";
150315
+ import { createHash as createHash13, randomUUID as randomUUID14 } from "crypto";
149854
150316
  function compactText2(value, field) {
149855
150317
  if (typeof value !== "string") throw new Error("Claim " + field + " must be text");
149856
150318
  const sanitized = sanitizeCredentials(value).trim().replace(/\s+/g, " ");
@@ -149936,7 +150398,7 @@ function normalizeClaimInput(input) {
149936
150398
  const now3 = (/* @__PURE__ */ new Date()).toISOString();
149937
150399
  return {
149938
150400
  claim: {
149939
- id: randomUUID13(),
150401
+ id: randomUUID14(),
149940
150402
  projectId,
149941
150403
  subject,
149942
150404
  predicate,
@@ -151021,7 +151483,7 @@ var init_workflow_sync = __esm({
151021
151483
  });
151022
151484
 
151023
151485
  // src/knowledge/workflow-store.ts
151024
- import { randomUUID as randomUUID14 } from "crypto";
151486
+ import { randomUUID as randomUUID15 } from "crypto";
151025
151487
  function parseJson(value, fallback) {
151026
151488
  if (typeof value !== "string" || !value) return fallback;
151027
151489
  try {
@@ -151121,7 +151583,7 @@ var init_workflow_store = __esm({
151121
151583
  }
151122
151584
  recordRun(input) {
151123
151585
  const run = {
151124
- id: randomUUID14(),
151586
+ id: randomUUID15(),
151125
151587
  workflowId: input.workflowId,
151126
151588
  projectId: input.projectId,
151127
151589
  task: input.task.trim(),
@@ -151189,7 +151651,7 @@ var init_outcome_types = __esm({
151189
151651
  });
151190
151652
 
151191
151653
  // src/knowledge/outcome-store.ts
151192
- import { randomUUID as randomUUID15 } from "crypto";
151654
+ import { randomUUID as randomUUID16 } from "crypto";
151193
151655
  function optionalText5(value) {
151194
151656
  return typeof value === "string" && value.trim() ? value : void 0;
151195
151657
  }
@@ -151233,7 +151695,7 @@ var init_outcome_store = __esm({
151233
151695
  }
151234
151696
  record(input) {
151235
151697
  const signal = {
151236
- id: randomUUID15(),
151698
+ id: randomUUID16(),
151237
151699
  projectId: text(input.projectId, "project id"),
151238
151700
  candidateKind: oneOf(input.candidateKind, MEMORY_OUTCOME_CANDIDATE_KINDS, "candidate kind"),
151239
151701
  candidateId: text(input.candidateId, "candidate id"),
@@ -152067,6 +152529,15 @@ function observationId(payload) {
152067
152529
  const value = payload.observationId;
152068
152530
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
152069
152531
  }
152532
+ async function automaticCleanupEnabled(projectRoot) {
152533
+ if (!projectRoot) return true;
152534
+ try {
152535
+ const { getResolvedConfig: getResolvedConfig2 } = await Promise.resolve().then(() => (init_resolved_config(), resolved_config_exports));
152536
+ return getResolvedConfig2({ projectRoot }).memory.autoCleanup !== false;
152537
+ } catch {
152538
+ return true;
152539
+ }
152540
+ }
152070
152541
  function workspaceMode(payload) {
152071
152542
  return payload.workspaceMode === "local" || payload.workspaceMode === "versioned" ? payload.workspaceMode : void 0;
152072
152543
  }
@@ -152155,6 +152626,9 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
152155
152626
  if (job.projectId !== projectId) {
152156
152627
  return { action: "reschedule", delayMs: VECTOR_RETRY_DELAY_MS };
152157
152628
  }
152629
+ if ((job.kind === "retention-archive" || job.kind === "consolidation" || job.kind === "long-term-maintenance") && !await automaticCleanupEnabled(projectRoot)) {
152630
+ return { action: "complete" };
152631
+ }
152158
152632
  if (job.kind === "media-video-generation") {
152159
152633
  const { runMiniMaxVideoGenerationJob: runMiniMaxVideoGenerationJob2 } = await Promise.resolve().then(() => (init_video_jobs(), video_jobs_exports));
152160
152634
  return runMiniMaxVideoGenerationJob2(job, { dataDir: projectDir2, projectId });
@@ -152247,6 +152721,33 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
152247
152721
  });
152248
152722
  return { action: "complete" };
152249
152723
  }
152724
+ if (job.kind === "observation-project") {
152725
+ if (!projectRoot) {
152726
+ throw new Error(`Observation projection requires a project root for ${projectId}`);
152727
+ }
152728
+ const id = observationId(job.payload);
152729
+ if (!id) return { action: "complete" };
152730
+ const [
152731
+ { CodeGraphStore: CodeGraphStore2 },
152732
+ { bindObservationToCode: bindObservationToCode2 },
152733
+ { EvidenceCardStore: EvidenceCardStore2 },
152734
+ { getObservationStore: getObservationStore2 }
152735
+ ] = await Promise.all([
152736
+ Promise.resolve().then(() => (init_store(), store_exports)),
152737
+ Promise.resolve().then(() => (init_binder(), binder_exports)),
152738
+ Promise.resolve().then(() => (init_evidence_store(), evidence_store_exports)),
152739
+ Promise.resolve().then(() => (init_obs_store(), obs_store_exports))
152740
+ ]);
152741
+ const observation = await getObservationStore2().getById(id);
152742
+ if (!observation || observation.projectId !== projectId) return { action: "complete" };
152743
+ const codeStore = new CodeGraphStore2();
152744
+ await codeStore.init(projectDir2);
152745
+ await bindObservationToCode2(codeStore, observation);
152746
+ const evidence = new EvidenceCardStore2();
152747
+ await evidence.init(projectDir2);
152748
+ evidence.upsertObservation(observation);
152749
+ return { action: "complete" };
152750
+ }
152250
152751
  if (job.kind === "observation-qualify") {
152251
152752
  const [
152252
152753
  { CodeGraphStore: CodeGraphStore2 },
@@ -152454,7 +152955,15 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
152454
152955
  const after = getVectorStatus2(projectId);
152455
152956
  if (after.missing === 0) {
152456
152957
  resolveSupersededVectorFailures(projectDir2, projectId);
152457
- return { action: "complete" };
152958
+ return {
152959
+ action: "complete",
152960
+ progress: {
152961
+ attempted: result.attempted,
152962
+ succeeded: result.succeeded,
152963
+ failed: result.failed,
152964
+ remaining: 0
152965
+ }
152966
+ };
152458
152967
  }
152459
152968
  if (result.failed > 0 && result.succeeded === 0) {
152460
152969
  const streak = vectorBackfillFailureStreak(job.payload) + 1;
@@ -152469,6 +152978,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
152469
152978
  ...job.payload,
152470
152979
  vectorBackfillFailureStreak: streak
152471
152980
  },
152981
+ progress: {
152982
+ attempted: result.attempted,
152983
+ succeeded: result.succeeded,
152984
+ failed: result.failed,
152985
+ remaining: after.missing
152986
+ },
152472
152987
  lastError: result.lastError ?? `vector backfill made no progress (${result.failed}/${result.attempted} failed)`
152473
152988
  };
152474
152989
  }
@@ -152478,6 +152993,12 @@ function createProjectMaintenanceHandler(projectId, projectDir2, projectRoot, op
152478
152993
  action: "reschedule",
152479
152994
  delayMs: result.attempted === 0 ? VECTOR_RETRY_DELAY_MS : 0,
152480
152995
  resetAttempts: result.succeeded > 0,
152996
+ progress: {
152997
+ attempted: result.attempted,
152998
+ succeeded: result.succeeded,
152999
+ failed: result.failed,
153000
+ remaining: after.missing
153001
+ },
152481
153002
  ...result.succeeded > 0 ? {
152482
153003
  ...priorFailureStreak > 0 ? { payload } : {},
152483
153004
  ...result.failed > 0 && result.lastError ? { lastError: result.lastError } : priorFailureStreak > 0 ? { clearLastError: true } : {}