memorix 1.10.2 → 1.10.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/CHANGELOG.md +82 -1
  2. package/README.md +3 -1
  3. package/README.zh-CN.md +3 -1
  4. package/dist/cli/index.js +2281 -1486
  5. package/dist/cli/memcode.js +0 -0
  6. package/dist/index.js +1874 -1126
  7. package/dist/{maintenance-jobs-DVRF-46r.d.ts → maintenance-jobs-DweoCoTT.d.ts} +25 -15
  8. package/dist/maintenance-runner.d.ts +1 -1
  9. package/dist/maintenance-runner.js +802 -194
  10. package/dist/media-audio-runner.js +793 -186
  11. package/dist/media-video-runner.js +801 -194
  12. package/dist/memcode-runtime/CHANGELOG.md +64 -1
  13. package/dist/sdk.js +14036 -13317
  14. package/dist/types.d.ts +1 -1
  15. package/dist/vector-backfill-runner.d.ts +1 -1
  16. package/dist/vector-backfill-runner.js +801 -194
  17. package/docs/ARCHITECTURE.md +219 -0
  18. package/docs/CONFIGURATION.md +49 -0
  19. package/docs/DESIGN_DECISIONS.md +37 -0
  20. package/docs/DEVELOPMENT.md +1 -1
  21. package/docs/INTEGRATIONS.md +1 -1
  22. package/docs/MODULES.md +7 -1
  23. package/docs/PERFORMANCE.md +14 -0
  24. package/docs/README.md +2 -1
  25. package/docs/ROADMAP-1.9.12-2.0.md +18 -2
  26. package/docs/SETUP.md +19 -4
  27. package/package.json +1 -1
  28. package/plugins/antigravity/memorix/plugin.json +1 -1
  29. package/plugins/claude/memorix/.claude-plugin/plugin.json +1 -1
  30. package/plugins/codebuddy/memorix/.codebuddy-plugin/plugin.json +1 -1
  31. package/plugins/codex/memorix/.codex-plugin/plugin.json +1 -1
  32. package/plugins/copilot/memorix/plugin.json +1 -1
  33. package/plugins/gemini/memorix/gemini-extension.json +1 -1
  34. package/plugins/hermes/memorix/plugin.yaml +1 -1
  35. package/plugins/omp/memorix/package.json +1 -1
  36. package/plugins/openclaw/memorix/.codex-plugin/plugin.json +1 -1
  37. package/plugins/pi/memorix/package.json +1 -1
  38. package/server.json +2 -2
  39. package/src/cli/commands/agent-integrations.ts +1 -1
  40. package/src/cli/commands/background.ts +1 -1
  41. package/src/cli/commands/context.ts +3 -2
  42. package/src/cli/commands/doctor.ts +9 -0
  43. package/src/cli/commands/explain.ts +3 -2
  44. package/src/cli/commands/init.ts +6 -2
  45. package/src/cli/commands/setup.ts +9 -6
  46. package/src/cli/commands/uninstall.ts +15 -0
  47. package/src/cli/tui/App.tsx +9 -16
  48. package/src/cli/tui/ConfigureView.tsx +2 -0
  49. package/src/cli/tui/chat-service.ts +6 -9
  50. package/src/cli/tui/data.ts +2 -2
  51. package/src/codegraph/auto-context.ts +10 -3
  52. package/src/codegraph/derived-view.ts +63 -0
  53. package/src/codegraph/store.ts +37 -0
  54. package/src/codegraph/types.ts +3 -0
  55. package/src/compact/engine.ts +10 -33
  56. package/src/config/dotenv-loader.ts +1 -0
  57. package/src/config/resolved-config.ts +18 -2
  58. package/src/config/retrieval-strategy.ts +22 -0
  59. package/src/config/toml-loader.ts +6 -0
  60. package/src/config/yaml-loader.ts +11 -2
  61. package/src/core/derived-view.ts +15 -0
  62. package/src/core/maintenance-result.ts +33 -0
  63. package/src/core/retrieval-contracts.ts +57 -0
  64. package/src/core/retrieval-facade.ts +18 -0
  65. package/src/core/retrieval-policy.ts +44 -0
  66. package/src/core/runtime-context.ts +42 -0
  67. package/src/dashboard/server.ts +5 -6
  68. package/src/embedding/api-provider.ts +18 -8
  69. package/src/hooks/handler.ts +0 -1
  70. package/src/integrations/registry.ts +2 -1
  71. package/src/knowledge/workset.ts +0 -2
  72. package/src/llm/provider.ts +2 -1
  73. package/src/memory/consolidation.ts +3 -2
  74. package/src/memory/feedback-model.ts +1 -4
  75. package/src/memory/observations.ts +226 -104
  76. package/src/multimodal/image-loader.ts +2 -2
  77. package/src/runtime/control-plane-maintenance.ts +1 -0
  78. package/src/runtime/isolated-maintenance.ts +1 -0
  79. package/src/runtime/maintenance-jobs.ts +123 -32
  80. package/src/runtime/open-browser.ts +25 -0
  81. package/src/runtime/project-maintenance.ts +69 -1
  82. package/src/sdk.ts +3 -2
  83. package/src/search/fts-view.ts +53 -0
  84. package/src/search/orama-view.ts +40 -0
  85. package/src/search/retrieval-facade.ts +38 -0
  86. package/src/search/semantic-index.ts +13 -0
  87. package/src/search/semantic-view.ts +34 -0
  88. package/src/server.ts +21 -9
  89. package/src/store/obs-store.ts +15 -0
  90. package/src/store/orama-store.ts +143 -45
  91. package/src/store/sqlite-db.ts +22 -0
  92. package/src/store/sqlite-store.ts +27 -0
  93. package/src/types.ts +1 -1
  94. package/src/workspace/mcp-adapters/pi.ts +58 -0
  95. package/plugins/pi/memorix/skills/memorix-git-memory/SKILL.md +0 -26
  96. package/plugins/pi/memorix/skills/memorix-memory/SKILL.md +0 -51
  97. package/plugins/pi/memorix/skills/memorix-mini-skills/SKILL.md +0 -31
  98. package/plugins/pi/memorix/skills/memorix-orchestrate/SKILL.md +0 -28
  99. package/plugins/pi/memorix/skills/memorix-reasoning/SKILL.md +0 -30
  100. package/plugins/pi/memorix/skills/memorix-sessions/SKILL.md +0 -25
  101. package/plugins/pi/memorix/skills/memorix-troubleshooting/SKILL.md +0 -27
@@ -41,8 +41,9 @@ const MAX_BATCH_SIZE = 500;
41
41
  function tokenize(text: string): Set<string> {
42
42
  return new Set(
43
43
  text
44
+ .normalize('NFKC')
44
45
  .toLowerCase()
45
- .replace(/[^a-z0-9\u4e00-\u9fff\s-]/g, ' ')
46
+ .replace(/[^\p{L}\p{N}\s-]/gu, ' ')
46
47
  .split(/\s+/)
47
48
  .filter(t => t.length > 1),
48
49
  );
@@ -52,7 +53,7 @@ function tokenize(text: string): Set<string> {
52
53
  * Compute Jaccard similarity between two sets of tokens.
53
54
  */
54
55
  function jaccardSimilarity(a: Set<string>, b: Set<string>): number {
55
- if (a.size === 0 && b.size === 0) return 1;
56
+ if (a.size === 0 && b.size === 0) return 0;
56
57
  let intersection = 0;
57
58
  for (const token of a) {
58
59
  if (b.has(token)) intersection++;
@@ -1,4 +1 @@
1
- /** Pure feedback math shared by retrieval/retention without opening SQLite. */
2
- export function feedbackWeightMultiplier(weight: number): number {
3
- return Math.max(0.35, Math.min(1.4, 0.35 + Math.max(0, Math.min(2, weight)) * 0.525));
4
- }
1
+ export { feedbackWeightMultiplier } from '../core/retrieval-policy.js';
@@ -36,10 +36,10 @@ import {
36
36
  isEmbeddingEnabled,
37
37
  makeOramaObservationId,
38
38
  getLastSearchMode,
39
- searchObservations,
39
+ searchObservationsDetailed,
40
40
  updateObservationMetadata,
41
41
  } from '../store/orama-store.js';
42
- import { getObservationStore, initObservationStore, type ObservationStore } from '../store/obs-store.js';
42
+ import { getObservationStore, initObservationStore, type ObservationStore, type StoreTransaction } from '../store/obs-store.js';
43
43
  import { countTextTokens } from '../compact/token-budget.js';
44
44
  import { extractEntities, enrichConcepts } from './entity-extractor.js';
45
45
  import { getEmbeddingProvider, isEmbeddingExplicitlyDisabled, validateEmbeddingInput } from '../embedding/provider.js';
@@ -96,7 +96,7 @@ export function resetObservationRuntime(): void {
96
96
  loadedObservationStore = null;
97
97
  embeddingWriteMode = 'background';
98
98
  embeddingWorkerProjectRoot = undefined;
99
- vectorMissingIds.clear();
99
+ clearVectorMissingIds();
100
100
  vectorSchemaUpgradePromise = null;
101
101
  embeddingFailureLogTimestamps.clear();
102
102
  }
@@ -105,6 +105,22 @@ export function resetObservationRuntime(): void {
105
105
  // Tracks observation IDs whose async embedding write failed or was skipped.
106
106
  // Enables observability ("how many memories lack vectors?") and backfill.
107
107
  const vectorMissingIds = new Set<number>();
108
+ const vectorMissingProjectIds = new Map<number, string>();
109
+
110
+ function markVectorMissing(observationId: number, projectId: string): void {
111
+ vectorMissingIds.add(observationId);
112
+ vectorMissingProjectIds.set(observationId, projectId);
113
+ }
114
+
115
+ function clearVectorMissing(observationId: number): void {
116
+ vectorMissingIds.delete(observationId);
117
+ vectorMissingProjectIds.delete(observationId);
118
+ }
119
+
120
+ function clearVectorMissingIds(): void {
121
+ vectorMissingIds.clear();
122
+ vectorMissingProjectIds.clear();
123
+ }
108
124
  let vectorBackfillRunning = false;
109
125
  let vectorSchemaUpgradePromise: Promise<boolean> | null = null;
110
126
  let lastVectorBackfill: {
@@ -218,30 +234,48 @@ function queueVectorBackfill(
218
234
  });
219
235
  }
220
236
 
221
- async function bindObservationCodeRefsBestEffort(observation: Observation): Promise<void> {
222
- if (!projectDir) return;
237
+ async function bindObservationCodeRefsBestEffort(observation: Observation): Promise<boolean> {
238
+ if (!projectDir) return true;
223
239
  try {
224
240
  const { CodeGraphStore } = await import('../codegraph/store.js');
225
241
  const { bindObservationToCode } = await import('../codegraph/binder.js');
226
242
  const codeStore = new CodeGraphStore();
227
243
  await codeStore.init(projectDir);
228
244
  await bindObservationToCode(codeStore, observation);
245
+ return true;
229
246
  } catch {
230
247
  // Code refs enrich memory retrieval, but memory writes must remain durable without them.
248
+ return false;
231
249
  }
232
250
  }
233
251
 
234
- async function persistEvidenceCard(observation: Observation): Promise<void> {
235
- if (!projectDir) return;
252
+ async function persistEvidenceCard(observation: Observation): Promise<boolean> {
253
+ if (!projectDir) return true;
236
254
  try {
237
255
  const evidence = new EvidenceCardStore();
238
256
  await evidence.init(projectDir);
239
257
  evidence.upsertObservation(observation);
258
+ return true;
240
259
  } catch (error) {
241
260
  // Evidence is a derived control-plane projection. A failed projection must
242
261
  // never roll back the canonical observation, but it must be visible for a
243
262
  // later repair/sync pass.
244
263
  console.error(`[memorix] Evidence card projection failed for obs-${observation.id}: ${error instanceof Error ? error.message : String(error)}`);
264
+ return false;
265
+ }
266
+ }
267
+
268
+ async function acknowledgeObservationProjection(observation: Observation): Promise<void> {
269
+ if (!projectDir) return;
270
+ try {
271
+ const { MaintenanceJobStore } = await import('../runtime/maintenance-jobs.js');
272
+ new MaintenanceJobStore(projectDir).acknowledgePending(
273
+ observation.projectId,
274
+ 'observation-project',
275
+ 'observation-project:' + observation.id,
276
+ );
277
+ } catch {
278
+ // The pending outbox row remains recoverable by the maintenance worker.
245
279
  }
246
280
  }
247
281
 
@@ -275,6 +309,44 @@ function queueObservationQualification(observation: Observation): void {
275
309
  }
276
310
  }
277
311
 
312
+ async function enqueueObservationDerivedWork(tx: StoreTransaction, observation: Observation): Promise<boolean> {
313
+ if (!tx.enqueueMaintenanceJob) return false;
314
+ if (!isEmbeddingExplicitlyDisabled()) {
315
+ await tx.enqueueMaintenanceJob({
316
+ projectId: observation.projectId,
317
+ kind: 'vector-backfill',
318
+ dedupeKey: 'vector-backfill',
319
+ payload: { limit: 12 },
320
+ });
321
+ }
322
+ if (observation.admissionState === 'candidate') {
323
+ await tx.enqueueMaintenanceJob({
324
+ projectId: observation.projectId,
325
+ kind: 'observation-qualify',
326
+ dedupeKey: 'observation-qualify',
327
+ payload: { source: 'automatic-capture:' + observation.id, limit: 100 },
328
+ });
329
+ }
330
+ const claimSource = observation.sourceDetail === 'explicit'
331
+ || observation.source === 'git'
332
+ || observation.sourceDetail === 'git-ingest';
333
+ if (claimSource && resolveObservationVisibility(observation) === 'project') {
334
+ await tx.enqueueMaintenanceJob({
335
+ projectId: observation.projectId,
336
+ kind: 'claim-derive',
337
+ dedupeKey: 'claim-derive:' + observation.id,
338
+ payload: { observationId: observation.id },
339
+ });
340
+ }
341
+ await tx.enqueueMaintenanceJob({
342
+ projectId: observation.projectId,
343
+ kind: 'observation-project',
344
+ dedupeKey: 'observation-project:' + observation.id,
345
+ payload: { observationId: observation.id },
346
+ });
347
+ return true;
348
+ }
349
+
278
350
  function isVectorCompatibleWithCurrentIndex(embedding: number[] | null): boolean {
279
351
  if (!embedding) return false;
280
352
  const vectorDimensions = getVectorDimensions();
@@ -290,12 +362,18 @@ function isVectorCompatibleWithCurrentIndex(embedding: number[] | null): boolean
290
362
  */
291
363
  async function upgradeVectorSchemaAfterFirstEmbedding(embedding: number[]): Promise<boolean> {
292
364
  if (isVectorCompatibleWithCurrentIndex(embedding)) return true;
293
- if (getVectorDimensions() !== null || !embedding.every(Number.isFinite)) return false;
365
+ if (!embedding.every(Number.isFinite)) return false;
294
366
 
295
367
  const targetProjectDir = projectDir;
296
368
  if (!vectorSchemaUpgradePromise) {
297
- vectorSchemaUpgradePromise = reindexObservations()
298
- .then(() => projectDir === targetProjectDir && isVectorCompatibleWithCurrentIndex(embedding))
369
+ vectorSchemaUpgradePromise = getDb()
370
+ .then(async () => {
371
+ // Lazy corpus mode intentionally has no in-memory observations. The
372
+ // provider dimensions are enough to create the Orama schema; a full
373
+ // corpus rebuild would be both unnecessary and impossible here.
374
+ if (getVectorDimensions() === null && observations.length > 0) await reindexObservations();
375
+ return projectDir === targetProjectDir && isVectorCompatibleWithCurrentIndex(embedding);
376
+ })
299
377
  .catch(() => false)
300
378
  .finally(() => {
301
379
  vectorSchemaUpgradePromise = null;
@@ -359,13 +437,13 @@ function scheduleObservationEmbedding(input: {
359
437
  doc: MemorixDocument;
360
438
  }): void {
361
439
  const { observationId, projectId, searchableText, doc } = input;
362
- vectorMissingIds.add(observationId);
440
+ markVectorMissing(observationId, projectId);
363
441
 
364
442
  // Ordinary store must not pay embedding-provider or cache I/O when vectors
365
443
  // are disabled. Check before generateEmbedding() so MEMORIX_EMBEDDING=off
366
444
  // stays on the lexical write path.
367
445
  if (isEmbeddingExplicitlyDisabled()) {
368
- vectorMissingIds.delete(observationId);
446
+ clearVectorMissing(observationId);
369
447
  return;
370
448
  }
371
449
 
@@ -405,13 +483,13 @@ function scheduleObservationEmbedding(input: {
405
483
  vector: embedding,
406
484
  });
407
485
  }
408
- vectorMissingIds.delete(observationId);
486
+ clearVectorMissing(observationId);
409
487
  } catch {
410
488
  console.error(`[memorix] Embedding index update failed for obs-${observationId} (kept in backfill queue)`);
411
489
  queueVectorBackfill(projectId);
412
490
  }
413
491
  } else if (isEmbeddingExplicitlyDisabled()) {
414
- vectorMissingIds.delete(observationId);
492
+ clearVectorMissing(observationId);
415
493
  } else {
416
494
  queueVectorBackfill(projectId);
417
495
  logEmbeddingFailureOnce(
@@ -577,7 +655,6 @@ export async function storeObservation(input: {
577
655
  throw new Error('Cannot update a memory outside this session\'s write scope.');
578
656
  }
579
657
  const observation = await upsertObservation(existing, input, now);
580
- await input.onPersisted?.(observation);
581
658
  return { observation, upserted: true };
582
659
  }
583
660
  }
@@ -608,6 +685,7 @@ export async function storeObservation(input: {
608
685
  let upsertedInsideLock = false;
609
686
  let reloadCacheAfterCommit = false;
610
687
  let persistedCallbackInvoked = false;
688
+ let derivedJobsCommitted = false;
611
689
  const assignAndPersist = async () => {
612
690
  if (projectDir) {
613
691
  const store = getObservationStore();
@@ -676,6 +754,7 @@ export async function storeObservation(input: {
676
754
  };
677
755
 
678
756
  await tx.insert(observation);
757
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, observation);
679
758
  await input.onPersisted?.(observation);
680
759
  persistedCallbackInvoked = true;
681
760
  await tx.saveIdCounter(id + 1);
@@ -798,7 +877,6 @@ export async function storeObservation(input: {
798
877
  // If the lock discovered a topicKey duplicate on disk, delegate to upsert
799
878
  if (upsertedInsideLock) {
800
879
  const updated = await upsertObservation(observation, input, now);
801
- await input.onPersisted?.(updated);
802
880
  return { observation: updated, upserted: true };
803
881
  }
804
882
 
@@ -806,11 +884,14 @@ export async function storeObservation(input: {
806
884
  // transaction. Keep the in-memory fallback defensively covered too.
807
885
  if (!persistedCallbackInvoked) await input.onPersisted?.(observation);
808
886
 
809
- await bindObservationCodeRefsBestEffort(observation);
810
- await persistEvidenceCard(observation);
811
- queueObservationQualification(observation);
812
- if (resolveObservationVisibility(observation) === 'project') {
813
- queueClaimDerivation(observation);
887
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(observation);
888
+ const evidenceProjected = await persistEvidenceCard(observation);
889
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(observation);
890
+ if (!derivedJobsCommitted) {
891
+ queueObservationQualification(observation);
892
+ if (resolveObservationVisibility(observation) === 'project') {
893
+ queueClaimDerivation(observation);
894
+ }
814
895
  }
815
896
 
816
897
  scheduleObservationEmbedding({
@@ -848,6 +929,7 @@ async function upsertObservation(
848
929
  admissionReason?: string;
849
930
  visibility?: ObservationVisibility;
850
931
  sharedWithAgentIds?: string[];
932
+ onPersisted?: (observation: Observation) => void | Promise<void>;
851
933
  },
852
934
  now: string,
853
935
  ): Promise<Observation> {
@@ -866,98 +948,116 @@ async function upsertObservation(
866
948
  const fullText = [input.title, input.narrative, ...(input.facts ?? []), ...enrichedFiles, ...enrichedConcepts].join(' ');
867
949
  const tokens = countTextTokens(fullText);
868
950
 
869
- // Mark old observation as resolved (superseded by new version)
870
- // Note: topicKey upsert replaces in-place, so we just bump revision
871
-
872
- // Update in-place
873
- existing.entityName = input.entityName;
874
- existing.type = input.type;
875
- existing.title = input.title;
876
- existing.narrative = input.narrative;
877
- existing.facts = input.facts ?? [];
878
- existing.attachments = input.attachments;
879
- existing.filesModified = enrichedFiles;
880
- existing.concepts = enrichedConcepts;
881
- existing.tokens = tokens;
882
- existing.updatedAt = now;
883
- existing.hasCausalLanguage = extracted.hasCausalLanguage;
884
- existing.revisionCount = (existing.revisionCount ?? 1) + 1;
885
- existing.status = 'active';
886
- if (input.sessionId) existing.sessionId = input.sessionId;
887
- if (input.progress) existing.progress = input.progress;
888
- if (input.sourceDetail !== undefined) existing.sourceDetail = input.sourceDetail;
889
- if (input.valueCategory !== undefined) existing.valueCategory = input.valueCategory;
890
- if (input.admissionState !== undefined) existing.admissionState = input.admissionState;
891
- if (input.admissionReason !== undefined) existing.admissionReason = sanitizeCredentials(input.admissionReason);
892
- if (input.visibility !== undefined) existing.visibility = input.visibility;
893
- if (input.sharedWithAgentIds !== undefined) existing.sharedWithAgentIds = input.sharedWithAgentIds;
894
-
895
- // Re-index in Orama WITHOUT embedding first (non-blocking)
951
+ const applyUpdate = (current: Observation): Observation => ({
952
+ ...current,
953
+ entityName: input.entityName,
954
+ type: input.type,
955
+ title: input.title,
956
+ narrative: input.narrative,
957
+ facts: input.facts ?? [],
958
+ attachments: input.attachments,
959
+ filesModified: enrichedFiles,
960
+ concepts: enrichedConcepts,
961
+ tokens,
962
+ updatedAt: now,
963
+ hasCausalLanguage: extracted.hasCausalLanguage,
964
+ revisionCount: (current.revisionCount ?? 1) + 1,
965
+ status: 'active',
966
+ ...(input.sessionId ? { sessionId: input.sessionId } : {}),
967
+ ...(input.progress ? { progress: input.progress } : {}),
968
+ ...(input.sourceDetail !== undefined ? { sourceDetail: input.sourceDetail } : {}),
969
+ ...(input.valueCategory !== undefined ? { valueCategory: input.valueCategory } : {}),
970
+ ...(input.admissionState !== undefined ? { admissionState: input.admissionState } : {}),
971
+ ...(input.admissionReason !== undefined ? { admissionReason: sanitizeCredentials(input.admissionReason) } : {}),
972
+ ...(input.visibility !== undefined ? { visibility: input.visibility } : {}),
973
+ ...(input.sharedWithAgentIds !== undefined ? { sharedWithAgentIds: input.sharedWithAgentIds } : {}),
974
+ });
975
+
976
+ let updated = applyUpdate(existing);
977
+ let derivedJobsCommitted = false;
978
+ if (projectDir) {
979
+ const store = getObservationStore();
980
+ await store.atomic(async (tx) => {
981
+ const current = await tx.getById(existing.id);
982
+ if (!current || current.projectId !== existing.projectId) {
983
+ throw new Error('Topic observation changed before update');
984
+ }
985
+ updated = applyUpdate(current);
986
+ updated.writeGeneration = (await tx.getGeneration()) + 1;
987
+ await tx.update(updated);
988
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, updated);
989
+ await input.onPersisted?.(updated);
990
+ });
991
+ updated.writeGeneration = store.getGeneration();
992
+ } else {
993
+ await input.onPersisted?.(updated);
994
+ }
995
+ if (corpusLoaded) {
996
+ const cacheIndex = observations.findIndex((observation) => observation.id === updated.id);
997
+ if (cacheIndex >= 0) observations[cacheIndex] = updated;
998
+ }
999
+
1000
+ // The durable update has committed; the index can now be repaired independently.
896
1001
  const doc: MemorixDocument = {
897
- id: makeOramaObservationId(existing.projectId, existing.id),
898
- observationId: existing.id,
899
- entityName: existing.entityName,
900
- type: existing.type,
901
- title: existing.title,
902
- narrative: existing.narrative,
903
- facts: existing.facts.join('\n'),
1002
+ id: makeOramaObservationId(updated.projectId, updated.id),
1003
+ observationId: updated.id,
1004
+ entityName: updated.entityName,
1005
+ type: updated.type,
1006
+ title: updated.title,
1007
+ narrative: updated.narrative,
1008
+ facts: updated.facts.join('\n'),
904
1009
  filesModified: enrichedFiles.join('\n'),
905
1010
  concepts: enrichedConcepts.map(c => c.replace(/-/g, ' ')).join(', '),
906
- attachments: formatAttachmentProvenance(existing.attachments),
1011
+ attachments: formatAttachmentProvenance(updated.attachments),
907
1012
  tokens,
908
- createdAt: existing.createdAt,
909
- projectId: existing.projectId,
1013
+ createdAt: updated.createdAt,
1014
+ projectId: updated.projectId,
910
1015
  accessCount: 0,
911
1016
  lastAccessedAt: '',
912
1017
  status: 'active',
913
- source: existing.source ?? 'agent',
914
- sourceDetail: existing.sourceDetail ?? '',
915
- valueCategory: existing.valueCategory ?? '',
916
- admissionState: existing.admissionState ?? '',
917
- admissionReason: existing.admissionReason ?? '',
918
- visibility: existing.visibility ?? 'project',
919
- createdByAgentId: existing.createdByAgentId ?? '',
920
- sharedWithAgentIds: JSON.stringify(existing.sharedWithAgentIds ?? []),
1018
+ source: updated.source ?? 'agent',
1019
+ sourceDetail: updated.sourceDetail ?? '',
1020
+ valueCategory: updated.valueCategory ?? '',
1021
+ admissionState: updated.admissionState ?? '',
1022
+ admissionReason: updated.admissionReason ?? '',
1023
+ visibility: updated.visibility ?? 'project',
1024
+ createdByAgentId: updated.createdByAgentId ?? '',
1025
+ sharedWithAgentIds: JSON.stringify(updated.sharedWithAgentIds ?? []),
921
1026
  };
922
1027
 
923
- // Remove old doc and insert updated one (with retry for concurrent upsert race)
924
- const oramaId = makeOramaObservationId(existing.projectId, existing.id);
925
- try {
926
- const { removeObservation } = await import('../store/orama-store.js');
927
- await removeObservation(oramaId);
928
- } catch { /* may not exist in index */ }
929
- try {
930
- await insertObservation(doc);
931
- } catch {
932
- // Concurrent upsert may have already re-inserted — retry remove+insert once
1028
+ if (corpusLoaded) {
1029
+ const oramaId = makeOramaObservationId(updated.projectId, updated.id);
933
1030
  try {
934
- const { removeObservation: removeObs } = await import('../store/orama-store.js');
935
- await removeObs(oramaId);
1031
+ try { await removeObservation(oramaId); } catch { /* index row may be absent */ }
936
1032
  await insertObservation(doc);
937
- } catch { /* best effort — file persistence is the source of truth */ }
938
- }
939
-
940
- // Persist via ObservationStore
941
- if (projectDir) {
942
- const store = getObservationStore();
943
- await store.update(existing);
1033
+ } catch {
1034
+ try {
1035
+ try { await removeObservation(oramaId); } catch { /* index row may be absent */ }
1036
+ await insertObservation(doc);
1037
+ } catch (error) {
1038
+ console.error(`[memorix] Observation index projection failed for obs-${updated.id}: ${sanitizeCredentials(error instanceof Error ? error.message : String(error))}`);
1039
+ }
1040
+ }
944
1041
  }
945
1042
 
946
- await bindObservationCodeRefsBestEffort(existing);
947
- await persistEvidenceCard(existing);
948
- queueObservationQualification(existing);
949
- if (resolveObservationVisibility(existing) === 'project') {
950
- queueClaimDerivation(existing);
1043
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(updated);
1044
+ const evidenceProjected = await persistEvidenceCard(updated);
1045
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(updated);
1046
+ if (!derivedJobsCommitted) {
1047
+ queueObservationQualification(updated);
1048
+ if (resolveObservationVisibility(updated) === 'project') {
1049
+ queueClaimDerivation(updated);
1050
+ }
951
1051
  }
952
1052
 
953
1053
  scheduleObservationEmbedding({
954
- observationId: existing.id,
955
- projectId: existing.projectId,
1054
+ observationId: updated.id,
1055
+ projectId: updated.projectId,
956
1056
  searchableText: [input.title, input.narrative, ...(input.facts ?? [])].join(' '),
957
1057
  doc,
958
1058
  });
959
1059
 
960
- return existing;
1060
+ return updated;
961
1061
  }
962
1062
 
963
1063
  /**
@@ -1246,7 +1346,7 @@ export async function reindexObservations(): Promise<number> {
1246
1346
  // Reset the Orama index to ensure clean reindex (idempotent)
1247
1347
  await resetDb();
1248
1348
  searchIndexPrepared = false;
1249
- vectorMissingIds.clear();
1349
+ clearVectorMissingIds();
1250
1350
 
1251
1351
  // Prefer already-persisted vectors for remote providers. This restores semantic
1252
1352
  // recall after a restart without waiting on the network; cache misses remain
@@ -1327,7 +1427,7 @@ export async function reindexObservations(): Promise<number> {
1327
1427
  };
1328
1428
  await insertObservation(doc);
1329
1429
  if (!compatibleEmbedding && !isEmbeddingExplicitlyDisabled()) {
1330
- vectorMissingIds.add(obs.id);
1430
+ markVectorMissing(obs.id, obs.projectId);
1331
1431
  }
1332
1432
  count++;
1333
1433
  } catch (err) {
@@ -1356,7 +1456,21 @@ export async function prepareSearchIndex(options: { skipCachedVectors?: boolean
1356
1456
  if (!isEmbeddingExplicitlyDisabled()) {
1357
1457
  const store = getObservationStore();
1358
1458
  const projects = await store.listProjectIds?.() ?? [];
1359
- for (const projectId of projects) queueVectorBackfill(projectId);
1459
+ // Initialize the lightweight vector schema without hydrating the corpus.
1460
+ // The persistent Lance ID set is the source of truth in lazy mode.
1461
+ await getDb({ allowNetworkProbe: false }).catch(() => undefined);
1462
+ const persistedIds = projectDir
1463
+ ? await getPersistentSemanticVectorIds(projectDir).catch(() => null)
1464
+ : null;
1465
+ for (const projectId of projects) {
1466
+ const projectObservations = await store.loadByProject(projectId);
1467
+ for (const observation of projectObservations) {
1468
+ if (!persistedIds?.has(observation.id)) markVectorMissing(observation.id, observation.projectId);
1469
+ }
1470
+ if (projectObservations.some((observation) => !persistedIds?.has(observation.id))) {
1471
+ queueVectorBackfill(projectId);
1472
+ }
1473
+ }
1360
1474
  }
1361
1475
  return 0;
1362
1476
  }
@@ -1372,7 +1486,7 @@ export async function prepareSearchIndex(options: { skipCachedVectors?: boolean
1372
1486
  const hydratedProjectDir = projectDir;
1373
1487
  const queueMissingVectors = async () => {
1374
1488
  if (!hydratedProjectDir || projectDir !== hydratedProjectDir) return;
1375
- vectorMissingIds.clear();
1489
+ clearVectorMissingIds();
1376
1490
  if (!isEmbeddingExplicitlyDisabled()) {
1377
1491
  const persistedSemanticIds = await getPersistentSemanticVectorIds(hydratedProjectDir).catch(() => null);
1378
1492
  const projectsWithMissingVectors = new Set<string>();
@@ -1381,7 +1495,7 @@ export async function prepareSearchIndex(options: { skipCachedVectors?: boolean
1381
1495
  // not at index time. Omitting non-active observations here would permanently
1382
1496
  // exclude resolved/archived memories from hybrid search after restart.
1383
1497
  if (!hasObservationVector(obs.projectId, obs.id) && !persistedSemanticIds?.has(obs.id)) {
1384
- vectorMissingIds.add(obs.id);
1498
+ markVectorMissing(obs.id, obs.projectId);
1385
1499
  projectsWithMissingVectors.add(obs.projectId);
1386
1500
  }
1387
1501
  }
@@ -1410,6 +1524,9 @@ export async function prepareSearchIndex(options: { skipCachedVectors?: boolean
1410
1524
  */
1411
1525
  export function getVectorMissingIds(projectId?: string): number[] {
1412
1526
  if (!projectId) return [...vectorMissingIds];
1527
+ if (!corpusLoaded) {
1528
+ return [...vectorMissingIds].filter((id) => vectorMissingProjectIds.get(id) === projectId);
1529
+ }
1413
1530
  const observationById = new Map(observations.map((observation) => [observation.id, observation]));
1414
1531
  return [...vectorMissingIds].filter((id) => observationById.get(id)?.projectId === projectId);
1415
1532
  }
@@ -1459,7 +1576,7 @@ export function getSearchIndexStatus(projectId?: string): {
1459
1576
  * so status checks do not mutate retention/access metadata.
1460
1577
  */
1461
1578
  export async function probeSearchIndex(projectId: string): Promise<string> {
1462
- await searchObservations({
1579
+ const result = await searchObservationsDetailed({
1463
1580
  query: 'semantic memory retrieval status',
1464
1581
  projectId,
1465
1582
  reader: { projectId },
@@ -1467,7 +1584,7 @@ export async function probeSearchIndex(projectId: string): Promise<string> {
1467
1584
  status: 'all',
1468
1585
  trackAccess: false,
1469
1586
  });
1470
- return getLastSearchMode(projectId);
1587
+ return result.diagnostics.mode;
1471
1588
  }
1472
1589
 
1473
1590
  /**
@@ -1491,7 +1608,12 @@ export async function backfillVectorEmbeddings(options: {
1491
1608
  }
1492
1609
  vectorBackfillRunning = true;
1493
1610
 
1494
- const observationById = new Map(observations.map((observation) => [observation.id, observation]));
1611
+ const sourceObservations = corpusLoaded
1612
+ ? observations
1613
+ : options.projectId
1614
+ ? await getObservationStore().loadByProject(options.projectId, { status: 'active' })
1615
+ : await getObservationStore().loadAll();
1616
+ const observationById = new Map(sourceObservations.map((observation) => [observation.id, observation]));
1495
1617
  const limit = Number.isFinite(options.limit)
1496
1618
  ? Math.max(1, Math.floor(options.limit!))
1497
1619
  : Number.POSITIVE_INFINITY;
@@ -1512,7 +1634,7 @@ export async function backfillVectorEmbeddings(options: {
1512
1634
  for (const id of ids) {
1513
1635
  const observation = observationById.get(id);
1514
1636
  if (!observation) {
1515
- vectorMissingIds.delete(id);
1637
+ clearVectorMissing(id);
1516
1638
  continue;
1517
1639
  }
1518
1640
  candidates.push({
@@ -1532,7 +1654,7 @@ export async function backfillVectorEmbeddings(options: {
1532
1654
  const provider = await getEmbeddingProvider();
1533
1655
  if (!provider) {
1534
1656
  if (isEmbeddingExplicitlyDisabled()) {
1535
- for (const candidate of candidates) vectorMissingIds.delete(candidate.id);
1657
+ for (const candidate of candidates) clearVectorMissing(candidate.id);
1536
1658
  } else {
1537
1659
  recordFailure('embedding provider unavailable');
1538
1660
  failed += candidates.length;
@@ -1612,7 +1734,7 @@ export async function backfillVectorEmbeddings(options: {
1612
1734
  vector: embedding,
1613
1735
  });
1614
1736
  }
1615
- vectorMissingIds.delete(id);
1737
+ clearVectorMissing(id);
1616
1738
  succeeded++;
1617
1739
  } catch (error) {
1618
1740
  recordFailure(vectorBackfillError(error));
@@ -19,7 +19,7 @@ import {
19
19
  } from './image-payload.js';
20
20
 
21
21
  // Providers that use the OpenAI-compatible /chat/completions Vision endpoint
22
- const OPENAI_COMPATIBLE_PROVIDERS = new Set(['openai', 'openrouter', 'requesty', 'apiroute', 'cheaperinference', 'custom']);
22
+ const OPENAI_COMPATIBLE_PROVIDERS = new Set(['openai', 'openrouter', 'requesty', 'apiroute', 'cheaperinference', 'runcrate', 'custom']);
23
23
  const MAX_VISION_PROMPT_CHARS = 12_000;
24
24
  const MAX_VISION_DESCRIPTION_CHARS = 12_000;
25
25
  const MAX_VISION_LABELS = 50;
@@ -138,7 +138,7 @@ export async function analyzeImage(input: ImageInput): Promise<ImageAnalysisResu
138
138
  const config = getLLMConfig()!;
139
139
  if (!OPENAI_COMPATIBLE_PROVIDERS.has(config.provider)) {
140
140
  throw new Error(
141
- `Image analysis requires an OpenAI-compatible provider (openai, openrouter, requesty, apiroute, cheaperinference, or custom). ` +
141
+ `Image analysis requires an OpenAI-compatible provider (openai, openrouter, requesty, apiroute, cheaperinference, runcrate, or custom). ` +
142
142
  `Current provider "${config.provider}" uses a different API shape. ` +
143
143
  `Set MEMORIX_LLM_PROVIDER=openai or configure an OpenAI-compatible base URL.`,
144
144
  );
@@ -14,6 +14,7 @@ export const CONTROL_PLANE_MAINTENANCE_KINDS: readonly MaintenanceJobKind[] = [
14
14
  'consolidation',
15
15
  'codegraph-refresh',
16
16
  'observation-qualify',
17
+ 'observation-project',
17
18
  'claim-derive',
18
19
  'claim-requalification',
19
20
  'knowledge-compile',
@@ -16,6 +16,7 @@ export const ISOLATED_MAINTENANCE_JOB_KINDS: readonly MaintenanceJobKind[] = [
16
16
  'consolidation',
17
17
  'codegraph-refresh',
18
18
  'observation-qualify',
19
+ 'observation-project',
19
20
  'claim-derive',
20
21
  'claim-requalification',
21
22
  'knowledge-compile',