memorix 1.10.1 → 1.10.2

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 (34) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/cli/index.js +416 -167
  3. package/dist/index.js +232 -106
  4. package/dist/maintenance-runner.js +167 -57
  5. package/dist/media-audio-runner.js +139 -29
  6. package/dist/media-video-runner.js +166 -56
  7. package/dist/memcode-runtime/CHANGELOG.md +14 -0
  8. package/dist/sdk.js +283 -106
  9. package/dist/vector-backfill-runner.js +166 -56
  10. package/docs/DEVELOPMENT.md +3 -4
  11. package/docs/PERFORMANCE.md +23 -0
  12. package/docs/README.md +2 -2
  13. package/docs/ROADMAP-1.9.12-2.0.md +2 -2
  14. package/package.json +1 -1
  15. package/plugins/antigravity/memorix/plugin.json +1 -1
  16. package/plugins/claude/memorix/.claude-plugin/plugin.json +1 -1
  17. package/plugins/codebuddy/memorix/.codebuddy-plugin/plugin.json +1 -1
  18. package/plugins/codex/memorix/.codex-plugin/plugin.json +1 -1
  19. package/plugins/copilot/memorix/plugin.json +1 -1
  20. package/plugins/gemini/memorix/gemini-extension.json +1 -1
  21. package/plugins/hermes/memorix/__init__.py +1 -2
  22. package/plugins/hermes/memorix/plugin.yaml +1 -1
  23. package/plugins/omp/memorix/package.json +1 -1
  24. package/plugins/openclaw/memorix/.codex-plugin/plugin.json +1 -1
  25. package/plugins/pi/memorix/package.json +1 -1
  26. package/server.json +2 -2
  27. package/src/cli/commands/repair.ts +17 -3
  28. package/src/compact/index-format.ts +1 -1
  29. package/src/knowledge/context-receipt.ts +6 -3
  30. package/src/memory/observations.ts +7 -5
  31. package/src/search/derived-view-receipt.ts +40 -0
  32. package/src/search/semantic-index.ts +149 -1
  33. package/src/server.ts +18 -3
  34. package/src/store/orama-store.ts +32 -16
@@ -1,5 +1,8 @@
1
1
  import type { CodeGraphProviderQuality } from '../codegraph/types.js';
2
- import type { RetrievalDerivedViewReceipt } from '../search/derived-view-receipt.js';
2
+ import {
3
+ sanitizeDerivedViewFailureReason,
4
+ type RetrievalDerivedViewReceipt,
5
+ } from '../search/derived-view-receipt.js';
3
6
  import type { TaskWorkset } from './workset.js';
4
7
  import type { TaskContinuityLedger } from './task-continuity.js';
5
8
 
@@ -44,7 +47,7 @@ export function buildCodeGraphDerivedView(input: {
44
47
  ...(snapshot.incomplete
45
48
  ? { failureReason: 'latest CodeGraph snapshot is incomplete' }
46
49
  : externalFailure && provider?.external.reason
47
- ? { failureReason: provider.external.reason.slice(0, 240) }
50
+ ? { failureReason: sanitizeDerivedViewFailureReason(provider.external.reason) }
48
51
  : {}),
49
52
  };
50
53
  }
@@ -53,7 +56,7 @@ export function buildCodeGraphDerivedView(input: {
53
56
  freshness: 'unknown',
54
57
  rebuildStatus: externalFailure ? 'failed' : 'unavailable',
55
58
  ...(provider?.external.reason
56
- ? { failureReason: provider.external.reason.slice(0, 240) }
59
+ ? { failureReason: sanitizeDerivedViewFailureReason(provider.external.reason) }
57
60
  : { failureReason: 'CodeGraph snapshot is not initialized' }),
58
61
  };
59
62
  }
@@ -28,6 +28,7 @@ import {
28
28
  batchGenerateEmbeddings,
29
29
  getDb,
30
30
  getDeferredCachedVectorHydration,
31
+ getPersistentSemanticVectorIds,
31
32
  getVectorDimensions,
32
33
  queueSemanticVector,
33
34
  hydrateIndexForStartup,
@@ -1369,16 +1370,17 @@ export async function prepareSearchIndex(options: { skipCachedVectors?: boolean
1369
1370
  }
1370
1371
 
1371
1372
  const hydratedProjectDir = projectDir;
1372
- const queueMissingVectors = () => {
1373
- if (projectDir !== hydratedProjectDir) return;
1373
+ const queueMissingVectors = async () => {
1374
+ if (!hydratedProjectDir || projectDir !== hydratedProjectDir) return;
1374
1375
  vectorMissingIds.clear();
1375
1376
  if (!isEmbeddingExplicitlyDisabled()) {
1377
+ const persistedSemanticIds = await getPersistentSemanticVectorIds(hydratedProjectDir).catch(() => null);
1376
1378
  const projectsWithMissingVectors = new Set<string>();
1377
1379
  for (const obs of observations) {
1378
1380
  // Queue ALL statuses for vector backfill — status filtering happens at query time,
1379
1381
  // not at index time. Omitting non-active observations here would permanently
1380
1382
  // exclude resolved/archived memories from hybrid search after restart.
1381
- if (!hasObservationVector(obs.projectId, obs.id)) {
1383
+ if (!hasObservationVector(obs.projectId, obs.id) && !persistedSemanticIds?.has(obs.id)) {
1382
1384
  vectorMissingIds.add(obs.id);
1383
1385
  projectsWithMissingVectors.add(obs.projectId);
1384
1386
  }
@@ -1391,9 +1393,9 @@ export async function prepareSearchIndex(options: { skipCachedVectors?: boolean
1391
1393
  if (cacheHydration) {
1392
1394
  // Let the disk cache finish outside the interactive startup path. Misses are
1393
1395
  // queued only after it has had a chance to restore compatible vectors.
1394
- void cacheHydration.finally(queueMissingVectors);
1396
+ void cacheHydration.then(queueMissingVectors, queueMissingVectors).catch(() => undefined);
1395
1397
  } else {
1396
- queueMissingVectors();
1398
+ await queueMissingVectors();
1397
1399
  }
1398
1400
 
1399
1401
  searchIndexPrepared = true;
@@ -1,3 +1,6 @@
1
+ import { sanitizeCredentials } from '../memory/secret-filter.js';
2
+ import type { EmbeddingRuntimeHealth } from '../embedding/provider.js';
3
+
1
4
  /** Privacy-safe health metadata for retrieval's derived evidence views. */
2
5
  export type RetrievalDerivedViewName = 'fts' | 'orama' | 'embedding' | 'graph';
3
6
 
@@ -20,3 +23,40 @@ export interface RetrievalDerivedViewReceipt {
20
23
  }
21
24
 
22
25
  export type RetrievalDerivedViews = Partial<Record<RetrievalDerivedViewName, RetrievalDerivedViewReceipt>>;
26
+
27
+ /** Normalize an operator-facing failure without persisting credentials or host paths. */
28
+ export function sanitizeDerivedViewFailureReason(reason: string): string {
29
+ const safe = sanitizeCredentials(reason)
30
+ .replace(/(?:[A-Za-z]:[\\/]|\\\\[^\\/\s]+[\\/]|\/(?:home|Users|tmp|var|private|mnt|workspace|workspaces)\/)[^\s"'<>|]*/gi, '[path]')
31
+ .replace(/\s+/g, ' ')
32
+ .trim();
33
+ return safe.slice(0, 240) || 'derived view failed';
34
+ }
35
+
36
+ export function embeddingHealthReceipt(
37
+ health: EmbeddingRuntimeHealth | undefined,
38
+ embeddingEnabled: boolean,
39
+ ): RetrievalDerivedViewReceipt {
40
+ if (health?.status === 'disabled') {
41
+ return { freshness: 'current', rebuildStatus: 'disabled' };
42
+ }
43
+ if (health?.status === 'ready' || embeddingEnabled) {
44
+ return { freshness: 'current', rebuildStatus: 'idle' };
45
+ }
46
+ if (health?.status === 'degraded') {
47
+ return {
48
+ freshness: 'stale',
49
+ rebuildStatus: 'failed',
50
+ ...(health.failure
51
+ ? {
52
+ failureReason: `embedding ${health.failure.kind}; retry in ${health.failure.retryAfterMs}ms`,
53
+ }
54
+ : { failureReason: 'embedding provider degraded' }),
55
+ };
56
+ }
57
+ return {
58
+ freshness: 'unknown',
59
+ rebuildStatus: 'unavailable',
60
+ failureReason: 'embedding provider is not initialized',
61
+ };
62
+ }
@@ -1,4 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
+ import { existsSync } from 'node:fs';
2
3
  import { createRequire } from 'node:module';
3
4
  import path from 'node:path';
4
5
  import type { EmbeddingProvider } from '../embedding/provider.js';
@@ -29,6 +30,10 @@ const SEMANTIC_INDEX_DIR = 'semantic-index';
29
30
  const TABLE_PREFIX = 'observations_';
30
31
  const DEFAULT_INDEX_THRESHOLD = 10_000;
31
32
  const MAX_INDEX_PARTITIONS = 32;
33
+ const DEFAULT_WRITE_BATCH_SIZE = 100;
34
+ const DEFAULT_WRITE_FLUSH_MS = 50;
35
+ const DEFAULT_OPTIMIZE_EVERY = 20;
36
+ const DEFAULT_VERSION_RETENTION_MS = 24 * 60 * 60 * 1000;
32
37
 
33
38
  type SemanticIndexState = {
34
39
  key: string;
@@ -41,6 +46,15 @@ type SemanticIndexState = {
41
46
  const statePromises = new Map<string, Promise<SemanticIndexState | null>>();
42
47
  const writeQueues = new Map<string, Promise<void>>();
43
48
  const indexBuilds = new Map<string, Promise<boolean>>();
49
+ const mutationCounts = new Map<string, number>();
50
+ type PendingVectorBatch = {
51
+ dataDir: string;
52
+ profile: SemanticIndexProfile;
53
+ records: Map<string, SemanticVectorRecord>;
54
+ waiters: Array<{ resolve: () => void; reject: (error: unknown) => void }>;
55
+ timer?: ReturnType<typeof setTimeout>;
56
+ };
57
+ const pendingVectorBatches = new Map<string, PendingVectorBatch>();
44
58
  let availability: boolean | undefined;
45
59
  const requireFromHere = createRequire(import.meta.url);
46
60
 
@@ -176,6 +190,35 @@ function queueOperation(key: string, operation: () => Promise<void>): Promise<vo
176
190
  return run;
177
191
  }
178
192
 
193
+ function positiveEnvInt(name: string, fallback: number): number {
194
+ const value = Number.parseInt(process.env[name] ?? '', 10);
195
+ return Number.isSafeInteger(value) && value > 0 ? value : fallback;
196
+ }
197
+
198
+ function semanticWriteBatchSize(): number {
199
+ return positiveEnvInt('MEMORIX_SEMANTIC_WRITE_BATCH_SIZE', DEFAULT_WRITE_BATCH_SIZE);
200
+ }
201
+
202
+ function semanticWriteFlushMs(): number {
203
+ return positiveEnvInt('MEMORIX_SEMANTIC_WRITE_FLUSH_MS', DEFAULT_WRITE_FLUSH_MS);
204
+ }
205
+
206
+ function semanticOptimizeEvery(): number {
207
+ return positiveEnvInt('MEMORIX_SEMANTIC_OPTIMIZE_EVERY', DEFAULT_OPTIMIZE_EVERY);
208
+ }
209
+
210
+ function semanticVersionRetentionMs(): number {
211
+ return positiveEnvInt('MEMORIX_SEMANTIC_VERSION_RETENTION_MS', DEFAULT_VERSION_RETENTION_MS);
212
+ }
213
+
214
+ async function optimizeState(state: SemanticIndexState): Promise<void> {
215
+ if (!state.table || typeof state.table.optimize !== 'function') return;
216
+ await state.table.optimize({
217
+ cleanupOlderThan: new Date(Date.now() - semanticVersionRetentionMs()),
218
+ deleteUnverified: false,
219
+ });
220
+ }
221
+
179
222
  async function mergeVectors(dataDir: string, profile: SemanticIndexProfile, records: SemanticVectorRecord[]): Promise<void> {
180
223
  if (records.length === 0) return;
181
224
  const state = await getState(dataDir, profile, records);
@@ -186,18 +229,50 @@ async function mergeVectors(dataDir: string, profile: SemanticIndexProfile, reco
186
229
  .whenMatchedUpdateAll()
187
230
  .whenNotMatchedInsertAll()
188
231
  .execute(rows);
232
+ const key = stateKey(dataDir, profile);
233
+ const mutationCount = (mutationCounts.get(key) ?? 0) + 1;
234
+ if (mutationCount >= semanticOptimizeEvery()) {
235
+ mutationCounts.set(key, 0);
236
+ await optimizeState(state).catch(() => undefined);
237
+ } else {
238
+ mutationCounts.set(key, mutationCount);
239
+ }
189
240
  // Build the ANN index asynchronously once the table is large enough. The
190
241
  // current write remains cheap and the unindexed tail stays queryable while
191
242
  // LanceDB trains the derived HNSW/SQ index.
192
243
  void ensureSemanticIndex(dataDir, profile);
193
244
  }
194
245
 
246
+ function flushPendingVectorBatch(key: string): Promise<void> {
247
+ const pending = pendingVectorBatches.get(key);
248
+ if (!pending) return Promise.resolve();
249
+ if (pending.timer) clearTimeout(pending.timer);
250
+ pendingVectorBatches.delete(key);
251
+ const records = [...pending.records.values()];
252
+ const waiters = pending.waiters.splice(0);
253
+ return queueOperation(key, () => mergeVectors(pending.dataDir, pending.profile, records))
254
+ .then(() => waiters.forEach((waiter) => waiter.resolve()))
255
+ .catch((error) => {
256
+ waiters.forEach((waiter) => waiter.reject(error));
257
+ });
258
+ }
259
+
195
260
  export function upsertSemanticVector(
196
261
  dataDir: string,
197
262
  profile: SemanticIndexProfile,
198
263
  record: SemanticVectorRecord,
199
264
  ): Promise<void> {
200
- return queueOperation(stateKey(dataDir, profile), () => mergeVectors(dataDir, profile, [record]));
265
+ const key = stateKey(dataDir, profile);
266
+ let pending = pendingVectorBatches.get(key);
267
+ if (!pending) {
268
+ pending = { dataDir, profile, records: new Map(), waiters: [] };
269
+ pendingVectorBatches.set(key, pending);
270
+ }
271
+ pending.records.set(`${record.projectId}:${record.observationId}`, record);
272
+ const promise = new Promise<void>((resolve, reject) => pending!.waiters.push({ resolve, reject }));
273
+ if (pending.records.size >= semanticWriteBatchSize()) void flushPendingVectorBatch(key);
274
+ else if (!pending.timer) pending.timer = setTimeout(() => { void flushPendingVectorBatch(key); }, semanticWriteFlushMs());
275
+ return promise;
201
276
  }
202
277
 
203
278
  export function upsertSemanticVectors(
@@ -208,6 +283,68 @@ export function upsertSemanticVectors(
208
283
  return queueOperation(stateKey(dataDir, profile), () => mergeVectors(dataDir, profile, records));
209
284
  }
210
285
 
286
+ /** Return persisted vector IDs without loading vector payloads. */
287
+ export async function listSemanticVectorIds(
288
+ dataDir: string,
289
+ profile: SemanticIndexProfile,
290
+ ): Promise<Set<number> | null> {
291
+ const state = await getState(dataDir, profile);
292
+ if (!state?.table) return null;
293
+ const rows = await state.table.query().select(['observation_id']).toArray();
294
+ return new Set(rows.map((row: any) => Number(row.observation_id)).filter(Number.isSafeInteger));
295
+ }
296
+
297
+ /** Read small, operator-safe table statistics without exposing vector data. */
298
+ export async function getSemanticIndexStats(
299
+ dataDir: string,
300
+ profile: SemanticIndexProfile,
301
+ ): Promise<{ rowCount: number; version: number } | null> {
302
+ const state = await getState(dataDir, profile);
303
+ if (!state?.table) return null;
304
+ return {
305
+ rowCount: await state.table.countRows(),
306
+ version: typeof state.table.version === 'function' ? await state.table.version() : 0,
307
+ };
308
+ }
309
+
310
+ /** Compact Lance fragments and prune old manifests for a semantic profile. */
311
+ export function optimizeSemanticIndex(
312
+ dataDir: string,
313
+ profile: SemanticIndexProfile,
314
+ ): Promise<void> {
315
+ const key = stateKey(dataDir, profile);
316
+ return queueOperation(key, async () => {
317
+ const state = await getState(dataDir, profile);
318
+ if (state) await optimizeState(state);
319
+ mutationCounts.set(key, 0);
320
+ });
321
+ }
322
+
323
+ /** Repair all persisted semantic tables without needing an active embedding provider. */
324
+ export async function optimizeSemanticIndexes(dataDir: string): Promise<string[]> {
325
+ if (!existsSync(indexRoot(dataDir))) return [];
326
+ const lance = await loadLanceDb();
327
+ if (!lance) throw new Error('LanceDB is unavailable; install the optional @lancedb/lancedb package');
328
+ const connection = await lance.connect(indexRoot(dataDir));
329
+ try {
330
+ const names: string[] = typeof connection.tableNames === 'function'
331
+ ? await connection.tableNames()
332
+ : (await connection.listTables()).tables;
333
+ const optimized: string[] = [];
334
+ for (const name of names.filter((value) => value.startsWith(TABLE_PREFIX))) {
335
+ const table = await connection.openTable(name);
336
+ await table.optimize({
337
+ cleanupOlderThan: new Date(Date.now() - semanticVersionRetentionMs()),
338
+ deleteUnverified: false,
339
+ });
340
+ optimized.push(name);
341
+ }
342
+ return optimized;
343
+ } finally {
344
+ try { connection.close?.(); } catch { /* best effort */ }
345
+ }
346
+ }
347
+
211
348
  export function deleteSemanticVector(
212
349
  dataDir: string,
213
350
  profile: SemanticIndexProfile,
@@ -309,6 +446,8 @@ export async function searchSemanticVectors(options: {
309
446
 
310
447
  /** Close native connections and release this process's derived-index cache. */
311
448
  export async function closeSemanticIndexes(): Promise<void> {
449
+ await Promise.all([...pendingVectorBatches.keys()].map((key) => flushPendingVectorBatch(key)));
450
+ await Promise.all([...writeQueues.values()]);
312
451
  for (const statePromise of statePromises.values()) {
313
452
  const state = await statePromise.catch(() => null);
314
453
  try { state?.connection?.close?.(); } catch { /* best effort */ }
@@ -316,11 +455,14 @@ export async function closeSemanticIndexes(): Promise<void> {
316
455
  statePromises.clear();
317
456
  writeQueues.clear();
318
457
  indexBuilds.clear();
458
+ mutationCounts.clear();
319
459
  }
320
460
 
321
461
  /** Close only the semantic tables rooted in one Memorix data directory. */
322
462
  export async function closeSemanticIndex(dataDir: string): Promise<void> {
323
463
  const prefix = `${path.resolve(dataDir)}::`;
464
+ await Promise.all([...pendingVectorBatches.keys()].filter((key) => key.startsWith(prefix)).map(flushPendingVectorBatch));
465
+ await Promise.all([...writeQueues.entries()].filter(([key]) => key.startsWith(prefix)).map(([, queue]) => queue));
324
466
  for (const [key, statePromise] of statePromises.entries()) {
325
467
  if (!key.startsWith(prefix)) continue;
326
468
  const state = await statePromise.catch(() => null);
@@ -328,13 +470,19 @@ export async function closeSemanticIndex(dataDir: string): Promise<void> {
328
470
  statePromises.delete(key);
329
471
  writeQueues.delete(key);
330
472
  indexBuilds.delete(key);
473
+ mutationCounts.delete(key);
331
474
  }
332
475
  }
333
476
 
334
477
  /** @internal Reset state for isolated tests. */
335
478
  export function resetSemanticIndexRuntime(): void {
479
+ for (const pending of pendingVectorBatches.values()) {
480
+ if (pending.timer) clearTimeout(pending.timer);
481
+ }
482
+ pendingVectorBatches.clear();
336
483
  statePromises.clear();
337
484
  writeQueues.clear();
338
485
  indexBuilds.clear();
486
+ mutationCounts.clear();
339
487
  availability = undefined;
340
488
  }
package/src/server.ts CHANGED
@@ -31,6 +31,7 @@ import { extractEntities } from './memory/entity-extractor.js';
31
31
  import { scopeKnowledgeGraphToProject } from './memory/graph-scope.js';
32
32
  import { canManageObservation, canReadObservation, filterReadableObservations, resolveObservationVisibility } from './memory/visibility.js';
33
33
  import { compactSearch, compactTimeline, compactDetail } from './compact/engine.js';
34
+ import { formatEntryRef } from './compact/index-format.js';
34
35
  import { buildGraphContextPacket, formatGraphContextPrompt } from './memory/graph-context.js';
35
36
  import { detectProject } from './project/detector.js';
36
37
  import { homeProjectRootError, isHomeDirectory, writeLastProjectRoot } from './project/launch-root.js';
@@ -1562,7 +1563,18 @@ export async function createMemorixServer(
1562
1563
  text,
1563
1564
  },
1564
1565
  ],
1565
- structuredContent: { retrieval: result.receipt },
1566
+ // Clients that surface only structuredContent (e.g. Claude Code) must
1567
+ // still see the results, not just the retrieval diagnostics.
1568
+ structuredContent: {
1569
+ results: result.entries.map(entry => ({
1570
+ ref: formatEntryRef(entry),
1571
+ title: entry.title,
1572
+ type: entry.type,
1573
+ time: entry.time,
1574
+ tokens: entry.tokens,
1575
+ })),
1576
+ retrieval: result.receipt,
1577
+ },
1566
1578
  };
1567
1579
  }, { loadCorpus: false }); // withFreshIndex
1568
1580
  },
@@ -4086,9 +4098,12 @@ export async function createMemorixServer(
4086
4098
  }
4087
4099
  } catch { /* team context injection is optional */ }
4088
4100
 
4101
+ const card = lines.filter(Boolean).join('\n');
4089
4102
  return {
4090
- content: [{ type: 'text' as const, text: lines.filter(Boolean).join('\n') }],
4091
- structuredContent: { binding: bindingReceipt },
4103
+ content: [{ type: 'text' as const, text: card }],
4104
+ // Clients that surface only structuredContent (e.g. Claude Code) must
4105
+ // still see the session card, not just the binding receipt.
4106
+ structuredContent: { card, binding: bindingReceipt },
4092
4107
  };
4093
4108
  },
4094
4109
  );
@@ -19,7 +19,9 @@ import {
19
19
  type EmbeddingInput,
20
20
  type EmbeddingOptions,
21
21
  type EmbeddingProvider,
22
+ type EmbeddingRuntimeHealth,
22
23
  } from '../embedding/provider.js';
24
+ import * as embeddingRuntime from '../embedding/provider.js';
23
25
  import { calculateProjectAffinity, extractProjectKeywords, type AffinityContext, type MemoryContent } from './project-affinity.js';
24
26
  import { detectQueryIntent, applyIntentBoost } from '../search/intent-detector.js';
25
27
  import { maybeExpandSearchQuery } from '../search/query-expansion.js';
@@ -29,11 +31,17 @@ import { getObservationStore } from './obs-store.js';
29
31
  import {
30
32
  createSemanticIndexProfile,
31
33
  searchSemanticVectors,
34
+ listSemanticVectorIds,
35
+ upsertSemanticVector,
32
36
  upsertSemanticVectors,
33
37
  type SemanticIndexProfile,
34
38
  type SemanticVectorRecord,
35
39
  } from '../search/semantic-index.js';
36
- import type { RetrievalDerivedViews } from '../search/derived-view-receipt.js';
40
+ import {
41
+ embeddingHealthReceipt,
42
+ sanitizeDerivedViewFailureReason,
43
+ type RetrievalDerivedViews,
44
+ } from '../search/derived-view-receipt.js';
37
45
 
38
46
  let db: AnyOrama | null = null;
39
47
  let dbInitPromise: Promise<AnyOrama> | null = null;
@@ -96,14 +104,16 @@ export function getSearchDerivedViews(): RetrievalDerivedViews {
96
104
  generation,
97
105
  freshness: 'unknown',
98
106
  rebuildStatus: 'unavailable',
99
- failureReason: store.getBackendReason?.() ?? 'persistent lexical index unavailable',
107
+ failureReason: sanitizeDerivedViewFailureReason(
108
+ store.getBackendReason?.() ?? 'persistent lexical index unavailable',
109
+ ),
100
110
  };
101
111
  }
102
112
  } catch (error) {
103
113
  views.fts = {
104
114
  freshness: 'unknown',
105
115
  rebuildStatus: 'failed',
106
- failureReason: error instanceof Error ? error.message.slice(0, 240) : String(error).slice(0, 240),
116
+ failureReason: sanitizeDerivedViewFailureReason(error instanceof Error ? error.message : String(error)),
107
117
  };
108
118
  }
109
119
  } else {
@@ -123,18 +133,15 @@ export function getSearchDerivedViews(): RetrievalDerivedViews {
123
133
  failureReason: 'Orama index is not initialized',
124
134
  };
125
135
 
126
- const configuredEmbeddingMode = process.env.MEMORIX_EMBEDDING?.trim().toLowerCase();
127
- if (configuredEmbeddingMode === 'off') {
128
- views.embedding = { freshness: 'current', rebuildStatus: 'disabled' };
129
- } else if (embeddingEnabled) {
130
- views.embedding = { freshness: 'current', rebuildStatus: 'idle' };
131
- } else {
132
- views.embedding = {
133
- freshness: 'unknown',
134
- rebuildStatus: 'unavailable',
135
- failureReason: 'embedding provider is not initialized',
136
- };
136
+ let embeddingHealth: EmbeddingRuntimeHealth | undefined;
137
+ try {
138
+ embeddingHealth = (embeddingRuntime as unknown as {
139
+ getEmbeddingRuntimeHealth?: () => EmbeddingRuntimeHealth;
140
+ }).getEmbeddingRuntimeHealth?.();
141
+ } catch {
142
+ // Legacy provider mocks/adapters may not expose health metadata.
137
143
  }
144
+ views.embedding = embeddingHealthReceipt(embeddingHealth, embeddingEnabled);
138
145
 
139
146
  return views;
140
147
  }
@@ -610,6 +617,12 @@ export function getActiveSemanticIndexProfile(): SemanticIndexProfile | null {
610
617
  return indexEmbeddingProvider ? createSemanticIndexProfile(indexEmbeddingProvider) : null;
611
618
  }
612
619
 
620
+ /** Read the durable semantic shadow's IDs without loading vector payloads. */
621
+ export async function getPersistentSemanticVectorIds(dataDir: string): Promise<Set<number> | null> {
622
+ if (!indexEmbeddingProvider) return null;
623
+ return listSemanticVectorIds(dataDir, createSemanticIndexProfile(indexEmbeddingProvider));
624
+ }
625
+
613
626
  /** Queue one derived vector without delaying the durable observation write. */
614
627
  export async function queueSemanticVector(
615
628
  dataDir: string,
@@ -622,7 +635,7 @@ export async function queueSemanticVector(
622
635
  const profile = provider ? createSemanticIndexProfile(provider) : null;
623
636
  if (!profile) return;
624
637
  try {
625
- await upsertSemanticVectors(dataDir, profile, [record]);
638
+ await upsertSemanticVector(dataDir, profile, record);
626
639
  } catch {
627
640
  // The vector index is rebuildable; lexical memory remains authoritative.
628
641
  }
@@ -729,6 +742,9 @@ async function attachCachedVectors(
729
742
  ): Promise<void> {
730
743
  const semanticDataDir = (await import('../memory/observations.js')).getObservationDataDir();
731
744
  const semanticProfile = getActiveSemanticIndexProfile();
745
+ const persistedSemanticIds = semanticDataDir && semanticProfile
746
+ ? await listSemanticVectorIds(semanticDataDir, semanticProfile).catch(() => null)
747
+ : null;
732
748
  const batchSize = 200;
733
749
  for (let start = 0; start < observations.length; start += batchSize) {
734
750
  // Keep cache lookup and the temporary vector array bounded to one batch.
@@ -744,7 +760,7 @@ async function attachCachedVectors(
744
760
  const vector = cachedVectors[index];
745
761
  if (!isCompatibleCachedVector(vector)) continue;
746
762
  const observation = batch[index];
747
- if (semanticDataDir && semanticProfile) {
763
+ if (semanticDataDir && semanticProfile && !persistedSemanticIds?.has(observation.id)) {
748
764
  semanticRecords.push({
749
765
  observationId: observation.id,
750
766
  projectId: observation.projectId,