memorix 1.10.1 → 1.10.3

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 (73) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +3 -1
  3. package/README.zh-CN.md +3 -1
  4. package/dist/cli/index.js +810 -379
  5. package/dist/cli/memcode.js +0 -0
  6. package/dist/index.js +380 -142
  7. package/dist/maintenance-runner.js +275 -79
  8. package/dist/media-audio-runner.js +247 -51
  9. package/dist/media-video-runner.js +274 -78
  10. package/dist/memcode-runtime/CHANGELOG.md +34 -0
  11. package/dist/sdk.js +431 -142
  12. package/dist/types.d.ts +1 -1
  13. package/dist/vector-backfill-runner.js +274 -78
  14. package/docs/CONFIGURATION.md +34 -0
  15. package/docs/DEVELOPMENT.md +3 -4
  16. package/docs/INTEGRATIONS.md +1 -1
  17. package/docs/PERFORMANCE.md +23 -0
  18. package/docs/README.md +3 -2
  19. package/docs/ROADMAP-1.9.12-2.0.md +2 -2
  20. package/docs/SETUP.md +19 -4
  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/__init__.py +1 -2
  29. package/plugins/hermes/memorix/plugin.yaml +1 -1
  30. package/plugins/omp/memorix/package.json +1 -1
  31. package/plugins/openclaw/memorix/.codex-plugin/plugin.json +1 -1
  32. package/plugins/pi/memorix/package.json +1 -1
  33. package/server.json +2 -2
  34. package/src/cli/commands/agent-integrations.ts +1 -1
  35. package/src/cli/commands/background.ts +1 -1
  36. package/src/cli/commands/context.ts +3 -2
  37. package/src/cli/commands/doctor.ts +9 -0
  38. package/src/cli/commands/explain.ts +3 -2
  39. package/src/cli/commands/init.ts +6 -2
  40. package/src/cli/commands/repair.ts +17 -3
  41. package/src/cli/commands/setup.ts +9 -6
  42. package/src/cli/commands/uninstall.ts +15 -0
  43. package/src/cli/tui/App.tsx +9 -16
  44. package/src/cli/tui/ConfigureView.tsx +2 -0
  45. package/src/codegraph/auto-context.ts +1 -1
  46. package/src/codegraph/store.ts +37 -0
  47. package/src/codegraph/types.ts +3 -0
  48. package/src/compact/index-format.ts +1 -1
  49. package/src/config/dotenv-loader.ts +1 -0
  50. package/src/config/resolved-config.ts +7 -2
  51. package/src/config/toml-loader.ts +1 -0
  52. package/src/config/yaml-loader.ts +4 -2
  53. package/src/dashboard/server.ts +5 -6
  54. package/src/hooks/handler.ts +0 -1
  55. package/src/integrations/registry.ts +2 -1
  56. package/src/knowledge/context-receipt.ts +6 -3
  57. package/src/llm/provider.ts +2 -1
  58. package/src/memory/observations.ts +68 -22
  59. package/src/multimodal/image-loader.ts +2 -2
  60. package/src/runtime/open-browser.ts +25 -0
  61. package/src/search/derived-view-receipt.ts +40 -0
  62. package/src/search/semantic-index.ts +149 -1
  63. package/src/server.ts +20 -5
  64. package/src/store/orama-store.ts +59 -19
  65. package/src/types.ts +1 -1
  66. package/src/workspace/mcp-adapters/pi.ts +58 -0
  67. package/plugins/pi/memorix/skills/memorix-git-memory/SKILL.md +0 -26
  68. package/plugins/pi/memorix/skills/memorix-memory/SKILL.md +0 -51
  69. package/plugins/pi/memorix/skills/memorix-mini-skills/SKILL.md +0 -31
  70. package/plugins/pi/memorix/skills/memorix-orchestrate/SKILL.md +0 -28
  71. package/plugins/pi/memorix/skills/memorix-reasoning/SKILL.md +0 -30
  72. package/plugins/pi/memorix/skills/memorix-sessions/SKILL.md +0 -25
  73. package/plugins/pi/memorix/skills/memorix-troubleshooting/SKILL.md +0 -27
@@ -169,6 +169,7 @@ export function ConfigureView({ onBack }: ConfigureViewProps): React.ReactElemen
169
169
  { key: 'requesty', label: 'Requesty', hint: 'multi-provider' },
170
170
  { key: 'apiroute', label: 'API Route', hint: 'multi-provider' },
171
171
  { key: 'cheaperinference', label: 'Cheaper Inference', hint: 'multi-provider' },
172
+ { key: 'runcrate', label: 'Runcrate', hint: 'open-weight models' },
172
173
  { key: 'atlascloud', label: 'Atlas Cloud', hint: 'DeepSeek V3.2' },
173
174
  { key: 'custom', label: 'Custom endpoint', hint: 'OpenAI-compatible' },
174
175
  { key: 'disable', label: 'Disable LLM', hint: 'free heuristic mode', color: COLORS.warning },
@@ -453,6 +454,7 @@ function getDefaultModel(provider: string): string {
453
454
  if (provider === 'requesty') return 'openai/gpt-4o-mini';
454
455
  if (provider === 'apiroute') return 'deepseek-v4.1-flash';
455
456
  if (provider === 'cheaperinference') return 'gpt-5.4-mini';
457
+ if (provider === 'runcrate') return 'deepseek-ai/DeepSeek-V4.1-Flash';
456
458
  if (provider === 'atlascloud') return 'deepseek-ai/deepseek-v3.2';
457
459
  return 'gpt-4o-mini';
458
460
  }
@@ -224,13 +224,13 @@ export async function buildAutoProjectContext(input: {
224
224
  /** The caller surface is recorded in the Workset receipt, not its prompt. */
225
225
  deliveryTarget?: ContextDeliveryTarget;
226
226
  }): Promise<AutoProjectContext> {
227
- const refreshMode = input.refresh ?? 'auto';
228
227
  const now = input.now ?? new Date();
229
228
  const task = input.task?.trim();
230
229
  const lens = resolveTaskLens(task);
231
230
  const continuationRequested = input.continuation === 'always'
232
231
  || (input.continuation !== 'never' && isContinuationTask(task));
233
232
  const codegraphConfig = getResolvedConfig({ projectRoot: input.project.rootPath }).codegraph;
233
+ const refreshMode = input.refresh ?? codegraphConfig.autoRefresh ?? 'auto';
234
234
  const exclude = input.exclude ?? codegraphConfig.excludePatterns;
235
235
  const maxFileBytes = input.maxFileBytes ?? codegraphConfig.maxFileBytes;
236
236
  const store = new CodeGraphStore();
@@ -1039,6 +1039,7 @@ export class CodeGraphStore {
1039
1039
  recordCodeStateSnapshot(input: CodeStateSnapshotInput): CodeStateSnapshot {
1040
1040
  const id = randomUUID();
1041
1041
  let snapshot: CodeStateSnapshot | undefined;
1042
+ let compactNeeded = false;
1042
1043
  const tx = this.db.transaction(() => {
1043
1044
  const previous = this.db.prepare(
1044
1045
  'SELECT id, sourceEpoch FROM code_state_snapshots WHERE projectId = ? ORDER BY sourceEpoch DESC LIMIT 1',
@@ -1082,6 +1083,29 @@ export class CodeGraphStore {
1082
1083
  for (const file of snapshotFileRows) {
1083
1084
  insertSnapshotFile.run(id, file.projectId, file.id, file.path, file.contentHash);
1084
1085
  }
1086
+ // Codegraph facts are derived and the readers already ignore stale
1087
+ // symbols. Retain the latest two manifests, then remove dead symbols
1088
+ // and edges so repeated refreshes cannot grow the canonical SQLite file.
1089
+ const staleSymbolIds = this.db.prepare(
1090
+ 'SELECT id FROM code_symbols WHERE projectId = ? AND stale = 1',
1091
+ ).all(input.projectId).map((row: { id: string }) => row.id);
1092
+ if (staleSymbolIds.length > 0) {
1093
+ const placeholders = staleSymbolIds.map(() => '?').join(', ');
1094
+ this.db.prepare(
1095
+ `DELETE FROM code_edges WHERE projectId = ? AND (fromSymbolId IN (${placeholders}) OR toSymbolId IN (${placeholders}))`,
1096
+ ).run(input.projectId, ...staleSymbolIds, ...staleSymbolIds);
1097
+ this.db.prepare('DELETE FROM code_symbols WHERE projectId = ? AND stale = 1').run(input.projectId);
1098
+ compactNeeded = true;
1099
+ }
1100
+ const oldSnapshots = this.db.prepare(
1101
+ 'SELECT id FROM code_state_snapshots WHERE projectId = ? ORDER BY sourceEpoch DESC LIMIT -1 OFFSET 2',
1102
+ ).all(input.projectId).map((row: { id: string }) => row.id);
1103
+ if (oldSnapshots.length > 0) {
1104
+ const placeholders = oldSnapshots.map(() => '?').join(', ');
1105
+ this.db.prepare(`DELETE FROM code_state_snapshot_files WHERE snapshotId IN (${placeholders})`).run(...oldSnapshots);
1106
+ this.db.prepare(`DELETE FROM code_state_snapshots WHERE id IN (${placeholders})`).run(...oldSnapshots);
1107
+ compactNeeded = true;
1108
+ }
1085
1109
  snapshot = {
1086
1110
  ...input,
1087
1111
  id,
@@ -1090,12 +1114,20 @@ export class CodeGraphStore {
1090
1114
  };
1091
1115
  });
1092
1116
  tx();
1117
+ if (compactNeeded) this.compactStorage();
1093
1118
  return snapshot!;
1094
1119
  }
1095
1120
 
1121
+ /** Reclaim WAL/free pages after a derived codegraph sweep. */
1122
+ compactStorage(): void {
1123
+ try { this.db.pragma('wal_checkpoint(TRUNCATE)'); } catch { /* best effort */ }
1124
+ try { this.db.exec('VACUUM'); } catch { /* another reader may be active */ }
1125
+ }
1126
+
1096
1127
  status(projectId: string): CodeGraphStatus {
1097
1128
  const files = this.db.prepare(`SELECT COUNT(*) AS count FROM code_files WHERE projectId = ?`).get(projectId).count;
1098
1129
  const symbols = this.db.prepare(`SELECT COUNT(*) AS count FROM code_symbols WHERE projectId = ? AND stale = 0`).get(projectId).count;
1130
+ const staleSymbols = this.db.prepare(`SELECT COUNT(*) AS count FROM code_symbols WHERE projectId = ? AND stale = 1`).get(projectId).count;
1099
1131
  const edges = this.db.prepare(`SELECT COUNT(*) AS count FROM code_edges WHERE projectId = ?`).get(projectId).count;
1100
1132
  const refs = this.db.prepare(`SELECT COUNT(*) AS count FROM observation_code_refs WHERE projectId = ?`).get(projectId).count;
1101
1133
  const semanticSymbols = this.db.prepare(`SELECT COUNT(*) AS count FROM code_symbols WHERE projectId = ? AND stale = 0 AND source = 'typescript-compiler'`).get(projectId).count;
@@ -1103,6 +1135,8 @@ export class CodeGraphStore {
1103
1135
  const parserErrors = this.db.prepare(`SELECT COUNT(*) AS count FROM code_files WHERE projectId = ? AND parserError IS NOT NULL`).get(projectId).count;
1104
1136
  const latest = this.db.prepare(`SELECT MAX(indexedAt) AS indexedAt FROM code_files WHERE projectId = ?`).get(projectId);
1105
1137
  const latestSnapshot = this.latestSnapshot(projectId);
1138
+ const snapshots = this.db.prepare(`SELECT COUNT(*) AS count FROM code_state_snapshots WHERE projectId = ?`).get(projectId).count;
1139
+ const snapshotFiles = this.db.prepare(`SELECT COUNT(*) AS count FROM code_state_snapshot_files WHERE projectId = ?`).get(projectId).count;
1106
1140
  return {
1107
1141
  provider: 'lite',
1108
1142
  files,
@@ -1112,6 +1146,9 @@ export class CodeGraphStore {
1112
1146
  semanticSymbols,
1113
1147
  semanticEdges,
1114
1148
  parserErrors,
1149
+ staleSymbols,
1150
+ snapshots,
1151
+ snapshotFiles,
1115
1152
  ...(latest?.indexedAt ? { indexedAt: latest.indexedAt } : {}),
1116
1153
  ...(latestSnapshot ? { latestSnapshot } : {}),
1117
1154
  };
@@ -176,6 +176,9 @@ export interface CodeGraphStatus {
176
176
  semanticSymbols: number;
177
177
  semanticEdges: number;
178
178
  parserErrors: number;
179
+ staleSymbols?: number;
180
+ snapshots?: number;
181
+ snapshotFiles?: number;
179
182
  indexedAt?: string;
180
183
  latestSnapshot?: CodeStateSnapshot;
181
184
  }
@@ -348,7 +348,7 @@ function getProgressiveDisclosureHint(hasProject: boolean, surface: RetrievalSur
348
348
  // ── Phase 3a display helpers ──────────────────────────────────────
349
349
 
350
350
  /** Format an entry reference as a canonical typed ref usable in memorix_detail */
351
- function formatEntryRef(entry: IndexEntry): string {
351
+ export function formatEntryRef(entry: IndexEntry): string {
352
352
  if (entry.documentType === 'mini-skill') return `skill:${entry.id}`;
353
353
  return entry.projectId ? `obs:${entry.id}@${entry.projectId}` : `obs:${entry.id}`;
354
354
  }
@@ -146,6 +146,7 @@ export function getLoadedEnvValue(key: string): string | undefined {
146
146
  // REQUESTY_API_KEY - Requesty memory preset and embedding endpoint key
147
147
  // API_ROUTE_API_KEY - API Route memory preset key (only when selected)
148
148
  // CHEAPER_INFERENCE_API_KEY - Cheaper Inference memory preset key (only when selected)
149
+ // RUNCRATE_API_KEY - Runcrate memory preset key (only when selected)
149
150
  // MINIMAX_API_KEY — MiniMax global image/video generation key
150
151
  // MINIMAX_CN_API_KEY — MiniMax China-region image/video generation key
151
152
  // MINIMAX_REGION — MiniMax region: global or cn
@@ -63,6 +63,7 @@ export interface ResolvedMemorixConfig {
63
63
  codegraph: {
64
64
  excludePatterns?: string[];
65
65
  maxFileBytes?: number;
66
+ autoRefresh: 'auto' | 'always' | 'never';
66
67
  externalContext: 'auto' | 'off';
67
68
  externalCommand?: string;
68
69
  externalTimeoutMs?: number;
@@ -122,7 +123,8 @@ export function getResolvedConfig(options: ResolvedLaneOptions = {}): ResolvedMe
122
123
  const isRequesty = memoryLlmProvider === 'requesty';
123
124
  const isApiRoute = memoryLlmProvider === 'apiroute';
124
125
  const isCheaperInference = memoryLlmProvider === 'cheaperinference';
125
- const usesPresetKeyOnly = isAtlasCloud || isRequesty || isApiRoute || isCheaperInference;
126
+ const isRuncrate = memoryLlmProvider === 'runcrate';
127
+ const usesPresetKeyOnly = isAtlasCloud || isRequesty || isApiRoute || isCheaperInference || isRuncrate;
126
128
  const memoryLlmApiKey = first(
127
129
  process.env.MEMORIX_LLM_API_KEY,
128
130
  process.env.MEMORIX_API_KEY,
@@ -133,7 +135,8 @@ export function getResolvedConfig(options: ResolvedLaneOptions = {}): ResolvedMe
133
135
  isAtlasCloud ? process.env.ATLASCLOUD_API_KEY
134
136
  : isRequesty ? process.env.REQUESTY_API_KEY
135
137
  : isApiRoute ? process.env.API_ROUTE_API_KEY
136
- : isCheaperInference ? process.env.CHEAPER_INFERENCE_API_KEY : process.env.OPENAI_API_KEY,
138
+ : isCheaperInference ? process.env.CHEAPER_INFERENCE_API_KEY
139
+ : isRuncrate ? process.env.RUNCRATE_API_KEY : process.env.OPENAI_API_KEY,
137
140
  usesPresetKeyOnly ? undefined : process.env.ANTHROPIC_API_KEY,
138
141
  usesPresetKeyOnly ? undefined : openRouterMemoryLlmApiKey,
139
142
  );
@@ -205,6 +208,7 @@ export function getResolvedConfig(options: ResolvedLaneOptions = {}): ResolvedMe
205
208
  codegraph: {
206
209
  excludePatterns: firstArray(toml.codegraph?.exclude_patterns, yaml.codegraph?.excludePatterns),
207
210
  maxFileBytes: firstNumber(toml.codegraph?.max_file_bytes, yaml.codegraph?.maxFileBytes),
211
+ autoRefresh: first(toml.codegraph?.auto_refresh, yaml.codegraph?.autoRefresh, 'auto')!,
208
212
  externalContext: first(
209
213
  normalizeExternalContext(process.env.MEMORIX_CODEGRAPH_EXTERNAL_CONTEXT),
210
214
  toml.codegraph?.external_context,
@@ -334,6 +338,7 @@ function getEnvSourceNames(): string[] {
334
338
  'REQUESTY_API_KEY',
335
339
  'API_ROUTE_API_KEY',
336
340
  'CHEAPER_INFERENCE_API_KEY',
341
+ 'RUNCRATE_API_KEY',
337
342
  'ATLASCLOUD_API_KEY',
338
343
  ].filter((name) => process.env[name]);
339
344
  }
@@ -50,6 +50,7 @@ export interface MemorixTomlConfig {
50
50
  codegraph?: {
51
51
  exclude_patterns?: string[];
52
52
  max_file_bytes?: number;
53
+ auto_refresh?: 'auto' | 'always' | 'never';
53
54
  external_context?: 'auto' | 'off';
54
55
  external_command?: string;
55
56
  external_timeout_ms?: number;
@@ -25,7 +25,7 @@ import { getGlobalYamlPath, getProjectYamlPath } from './config-paths.js';
25
25
  export interface MemorixYamlConfig {
26
26
  /** LLM provider configuration */
27
27
  llm?: {
28
- provider?: 'openai' | 'anthropic' | 'openrouter' | 'requesty' | 'apiroute' | 'cheaperinference' | string;
28
+ provider?: 'openai' | 'anthropic' | 'openrouter' | 'requesty' | 'apiroute' | 'cheaperinference' | 'runcrate' | string;
29
29
  model?: string;
30
30
  apiKey?: string;
31
31
  baseUrl?: string;
@@ -33,7 +33,7 @@ export interface MemorixYamlConfig {
33
33
 
34
34
  /** TUI / chat agent LLM provider configuration */
35
35
  agent?: {
36
- provider?: 'openai' | 'anthropic' | 'openrouter' | 'requesty' | 'apiroute' | 'cheaperinference' | string;
36
+ provider?: 'openai' | 'anthropic' | 'openrouter' | 'requesty' | 'apiroute' | 'cheaperinference' | 'runcrate' | string;
37
37
  model?: string;
38
38
  apiKey?: string;
39
39
  baseUrl?: string;
@@ -78,6 +78,8 @@ export interface MemorixYamlConfig {
78
78
  excludePatterns?: string[];
79
79
  /** Maximum source file size to parse into CodeGraph Memory */
80
80
  maxFileBytes?: number;
81
+ /** Automatic built-in CodeGraph refresh policy. */
82
+ autoRefresh?: 'auto' | 'always' | 'never';
81
83
  /** Use a healthy pre-existing local CodeGraph index when present (default: auto). */
82
84
  externalContext?: 'auto' | 'off';
83
85
  /** Optional CodeGraph executable path when it is not available on PATH. */
@@ -11,7 +11,7 @@
11
11
  import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
12
12
  import { promises as fs } from 'node:fs';
13
13
  import path from 'node:path';
14
- import { exec } from 'node:child_process';
14
+ import { openLocalBrowser } from '../runtime/open-browser.js';
15
15
 
16
16
  import { getBaseDataDir } from '../store/persistence.js';
17
17
  import { getObservationStore, initObservationStore } from '../store/obs-store.js';
@@ -691,6 +691,9 @@ async function handleApi(
691
691
  ...(resolved.memory.llm.provider === 'cheaperinference'
692
692
  ? ['CHEAPER_INFERENCE_API_KEY']
693
693
  : []),
694
+ ...(resolved.memory.llm.provider === 'runcrate'
695
+ ? ['RUNCRATE_API_KEY']
696
+ : []),
694
697
  ];
695
698
  if (llmKey) {
696
699
  const src = resolveDashboardKeySource({ value: llmKey, envKeys: memoryKeyEnv, configSource });
@@ -957,11 +960,7 @@ async function serveStatic(req: IncomingMessage, res: ServerResponse, staticDir:
957
960
 
958
961
  /** Cross-platform open URL in default browser */
959
962
  function openBrowser(url: string) {
960
- const cmd =
961
- process.platform === 'win32' ? `start "" "${url}"` :
962
- process.platform === 'darwin' ? `open "${url}"` :
963
- `xdg-open "${url}"`;
964
- exec(cmd, { windowsHide: true }, () => { /* ignore errors */ });
963
+ try { openLocalBrowser(url); } catch { /* best effort */ }
965
964
  }
966
965
 
967
966
  /** Mutable dashboard state — updated at runtime when project changes */
@@ -342,7 +342,6 @@ async function buildHookProjectContext(
342
342
  dataDir,
343
343
  observations: activeObservations,
344
344
  task,
345
- refresh: 'auto',
346
345
  reader: { projectId: canonicalId },
347
346
  continuation: 'always',
348
347
  ...(input.sessionId
@@ -246,7 +246,8 @@ const integrationEntries: Array<Omit<MemorixIntegration, 'capabilities'>> = [
246
246
  entry: 'official-package',
247
247
  status: 'ready',
248
248
  install: 'memorix setup --agent pi',
249
- surfaces: ['Pi package', 'extension API', 'skills', 'hooks'],
249
+ surfaces: ['MCP', 'Pi package', 'extension API', 'skills', 'hooks'],
250
+ note: 'Requires Pi 1.0+. Uses native .pi/mcp.json or ~/.pi/agent/mcp.json alongside the extension/skills package.',
250
251
  },
251
252
  {
252
253
  agent: 'any-mcp',
@@ -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
  }
@@ -20,7 +20,7 @@ import {
20
20
  } from '../config.js';
21
21
 
22
22
  export interface LLMConfig {
23
- provider: 'openai' | 'anthropic' | 'openrouter' | 'requesty' | 'apiroute' | 'cheaperinference' | 'atlascloud' | 'custom';
23
+ provider: 'openai' | 'anthropic' | 'openrouter' | 'requesty' | 'apiroute' | 'cheaperinference' | 'runcrate' | 'atlascloud' | 'custom';
24
24
  apiKey: string;
25
25
  model?: string;
26
26
  baseUrl?: string;
@@ -204,6 +204,7 @@ const PROVIDER_DEFAULTS: Record<string, { baseUrl: string; model: string }> = {
204
204
  requesty: { baseUrl: 'https://router.requesty.ai/v1', model: 'openai/gpt-4.1-nano' },
205
205
  apiroute: { baseUrl: 'https://global.api-route.com/v1', model: 'deepseek-v4.1-flash' },
206
206
  cheaperinference: { baseUrl: 'https://api.cheaperinference.com/v1', model: 'gpt-5.4-mini' },
207
+ runcrate: { baseUrl: 'https://api.runcrate.ai/v1', model: 'deepseek-ai/DeepSeek-V4.1-Flash' },
207
208
  atlascloud: { baseUrl: 'https://api.atlascloud.ai/v1', model: 'deepseek-ai/deepseek-v3.2' },
208
209
  custom: { baseUrl: 'http://localhost:11434/v1', model: 'llama3' },
209
210
  };
@@ -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,
@@ -95,7 +96,7 @@ export function resetObservationRuntime(): void {
95
96
  loadedObservationStore = null;
96
97
  embeddingWriteMode = 'background';
97
98
  embeddingWorkerProjectRoot = undefined;
98
- vectorMissingIds.clear();
99
+ clearVectorMissingIds();
99
100
  vectorSchemaUpgradePromise = null;
100
101
  embeddingFailureLogTimestamps.clear();
101
102
  }
@@ -104,6 +105,22 @@ export function resetObservationRuntime(): void {
104
105
  // Tracks observation IDs whose async embedding write failed or was skipped.
105
106
  // Enables observability ("how many memories lack vectors?") and backfill.
106
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
+ }
107
124
  let vectorBackfillRunning = false;
108
125
  let vectorSchemaUpgradePromise: Promise<boolean> | null = null;
109
126
  let lastVectorBackfill: {
@@ -289,12 +306,18 @@ function isVectorCompatibleWithCurrentIndex(embedding: number[] | null): boolean
289
306
  */
290
307
  async function upgradeVectorSchemaAfterFirstEmbedding(embedding: number[]): Promise<boolean> {
291
308
  if (isVectorCompatibleWithCurrentIndex(embedding)) return true;
292
- if (getVectorDimensions() !== null || !embedding.every(Number.isFinite)) return false;
309
+ if (!embedding.every(Number.isFinite)) return false;
293
310
 
294
311
  const targetProjectDir = projectDir;
295
312
  if (!vectorSchemaUpgradePromise) {
296
- vectorSchemaUpgradePromise = reindexObservations()
297
- .then(() => projectDir === targetProjectDir && isVectorCompatibleWithCurrentIndex(embedding))
313
+ vectorSchemaUpgradePromise = getDb()
314
+ .then(async () => {
315
+ // Lazy corpus mode intentionally has no in-memory observations. The
316
+ // provider dimensions are enough to create the Orama schema; a full
317
+ // corpus rebuild would be both unnecessary and impossible here.
318
+ if (getVectorDimensions() === null && observations.length > 0) await reindexObservations();
319
+ return projectDir === targetProjectDir && isVectorCompatibleWithCurrentIndex(embedding);
320
+ })
298
321
  .catch(() => false)
299
322
  .finally(() => {
300
323
  vectorSchemaUpgradePromise = null;
@@ -358,13 +381,13 @@ function scheduleObservationEmbedding(input: {
358
381
  doc: MemorixDocument;
359
382
  }): void {
360
383
  const { observationId, projectId, searchableText, doc } = input;
361
- vectorMissingIds.add(observationId);
384
+ markVectorMissing(observationId, projectId);
362
385
 
363
386
  // Ordinary store must not pay embedding-provider or cache I/O when vectors
364
387
  // are disabled. Check before generateEmbedding() so MEMORIX_EMBEDDING=off
365
388
  // stays on the lexical write path.
366
389
  if (isEmbeddingExplicitlyDisabled()) {
367
- vectorMissingIds.delete(observationId);
390
+ clearVectorMissing(observationId);
368
391
  return;
369
392
  }
370
393
 
@@ -404,13 +427,13 @@ function scheduleObservationEmbedding(input: {
404
427
  vector: embedding,
405
428
  });
406
429
  }
407
- vectorMissingIds.delete(observationId);
430
+ clearVectorMissing(observationId);
408
431
  } catch {
409
432
  console.error(`[memorix] Embedding index update failed for obs-${observationId} (kept in backfill queue)`);
410
433
  queueVectorBackfill(projectId);
411
434
  }
412
435
  } else if (isEmbeddingExplicitlyDisabled()) {
413
- vectorMissingIds.delete(observationId);
436
+ clearVectorMissing(observationId);
414
437
  } else {
415
438
  queueVectorBackfill(projectId);
416
439
  logEmbeddingFailureOnce(
@@ -1245,7 +1268,7 @@ export async function reindexObservations(): Promise<number> {
1245
1268
  // Reset the Orama index to ensure clean reindex (idempotent)
1246
1269
  await resetDb();
1247
1270
  searchIndexPrepared = false;
1248
- vectorMissingIds.clear();
1271
+ clearVectorMissingIds();
1249
1272
 
1250
1273
  // Prefer already-persisted vectors for remote providers. This restores semantic
1251
1274
  // recall after a restart without waiting on the network; cache misses remain
@@ -1326,7 +1349,7 @@ export async function reindexObservations(): Promise<number> {
1326
1349
  };
1327
1350
  await insertObservation(doc);
1328
1351
  if (!compatibleEmbedding && !isEmbeddingExplicitlyDisabled()) {
1329
- vectorMissingIds.add(obs.id);
1352
+ markVectorMissing(obs.id, obs.projectId);
1330
1353
  }
1331
1354
  count++;
1332
1355
  } catch (err) {
@@ -1355,7 +1378,21 @@ export async function prepareSearchIndex(options: { skipCachedVectors?: boolean
1355
1378
  if (!isEmbeddingExplicitlyDisabled()) {
1356
1379
  const store = getObservationStore();
1357
1380
  const projects = await store.listProjectIds?.() ?? [];
1358
- for (const projectId of projects) queueVectorBackfill(projectId);
1381
+ // Initialize the lightweight vector schema without hydrating the corpus.
1382
+ // The persistent Lance ID set is the source of truth in lazy mode.
1383
+ await getDb({ allowNetworkProbe: false }).catch(() => undefined);
1384
+ const persistedIds = projectDir
1385
+ ? await getPersistentSemanticVectorIds(projectDir).catch(() => null)
1386
+ : null;
1387
+ for (const projectId of projects) {
1388
+ const projectObservations = await store.loadByProject(projectId);
1389
+ for (const observation of projectObservations) {
1390
+ if (!persistedIds?.has(observation.id)) markVectorMissing(observation.id, observation.projectId);
1391
+ }
1392
+ if (projectObservations.some((observation) => !persistedIds?.has(observation.id))) {
1393
+ queueVectorBackfill(projectId);
1394
+ }
1395
+ }
1359
1396
  }
1360
1397
  return 0;
1361
1398
  }
@@ -1369,17 +1406,18 @@ export async function prepareSearchIndex(options: { skipCachedVectors?: boolean
1369
1406
  }
1370
1407
 
1371
1408
  const hydratedProjectDir = projectDir;
1372
- const queueMissingVectors = () => {
1373
- if (projectDir !== hydratedProjectDir) return;
1374
- vectorMissingIds.clear();
1409
+ const queueMissingVectors = async () => {
1410
+ if (!hydratedProjectDir || projectDir !== hydratedProjectDir) return;
1411
+ clearVectorMissingIds();
1375
1412
  if (!isEmbeddingExplicitlyDisabled()) {
1413
+ const persistedSemanticIds = await getPersistentSemanticVectorIds(hydratedProjectDir).catch(() => null);
1376
1414
  const projectsWithMissingVectors = new Set<string>();
1377
1415
  for (const obs of observations) {
1378
1416
  // Queue ALL statuses for vector backfill — status filtering happens at query time,
1379
1417
  // not at index time. Omitting non-active observations here would permanently
1380
1418
  // exclude resolved/archived memories from hybrid search after restart.
1381
- if (!hasObservationVector(obs.projectId, obs.id)) {
1382
- vectorMissingIds.add(obs.id);
1419
+ if (!hasObservationVector(obs.projectId, obs.id) && !persistedSemanticIds?.has(obs.id)) {
1420
+ markVectorMissing(obs.id, obs.projectId);
1383
1421
  projectsWithMissingVectors.add(obs.projectId);
1384
1422
  }
1385
1423
  }
@@ -1391,9 +1429,9 @@ export async function prepareSearchIndex(options: { skipCachedVectors?: boolean
1391
1429
  if (cacheHydration) {
1392
1430
  // Let the disk cache finish outside the interactive startup path. Misses are
1393
1431
  // queued only after it has had a chance to restore compatible vectors.
1394
- void cacheHydration.finally(queueMissingVectors);
1432
+ void cacheHydration.then(queueMissingVectors, queueMissingVectors).catch(() => undefined);
1395
1433
  } else {
1396
- queueMissingVectors();
1434
+ await queueMissingVectors();
1397
1435
  }
1398
1436
 
1399
1437
  searchIndexPrepared = true;
@@ -1408,6 +1446,9 @@ export async function prepareSearchIndex(options: { skipCachedVectors?: boolean
1408
1446
  */
1409
1447
  export function getVectorMissingIds(projectId?: string): number[] {
1410
1448
  if (!projectId) return [...vectorMissingIds];
1449
+ if (!corpusLoaded) {
1450
+ return [...vectorMissingIds].filter((id) => vectorMissingProjectIds.get(id) === projectId);
1451
+ }
1411
1452
  const observationById = new Map(observations.map((observation) => [observation.id, observation]));
1412
1453
  return [...vectorMissingIds].filter((id) => observationById.get(id)?.projectId === projectId);
1413
1454
  }
@@ -1489,7 +1530,12 @@ export async function backfillVectorEmbeddings(options: {
1489
1530
  }
1490
1531
  vectorBackfillRunning = true;
1491
1532
 
1492
- const observationById = new Map(observations.map((observation) => [observation.id, observation]));
1533
+ const sourceObservations = corpusLoaded
1534
+ ? observations
1535
+ : options.projectId
1536
+ ? await getObservationStore().loadByProject(options.projectId, { status: 'active' })
1537
+ : await getObservationStore().loadAll();
1538
+ const observationById = new Map(sourceObservations.map((observation) => [observation.id, observation]));
1493
1539
  const limit = Number.isFinite(options.limit)
1494
1540
  ? Math.max(1, Math.floor(options.limit!))
1495
1541
  : Number.POSITIVE_INFINITY;
@@ -1510,7 +1556,7 @@ export async function backfillVectorEmbeddings(options: {
1510
1556
  for (const id of ids) {
1511
1557
  const observation = observationById.get(id);
1512
1558
  if (!observation) {
1513
- vectorMissingIds.delete(id);
1559
+ clearVectorMissing(id);
1514
1560
  continue;
1515
1561
  }
1516
1562
  candidates.push({
@@ -1530,7 +1576,7 @@ export async function backfillVectorEmbeddings(options: {
1530
1576
  const provider = await getEmbeddingProvider();
1531
1577
  if (!provider) {
1532
1578
  if (isEmbeddingExplicitlyDisabled()) {
1533
- for (const candidate of candidates) vectorMissingIds.delete(candidate.id);
1579
+ for (const candidate of candidates) clearVectorMissing(candidate.id);
1534
1580
  } else {
1535
1581
  recordFailure('embedding provider unavailable');
1536
1582
  failed += candidates.length;
@@ -1610,7 +1656,7 @@ export async function backfillVectorEmbeddings(options: {
1610
1656
  vector: embedding,
1611
1657
  });
1612
1658
  }
1613
- vectorMissingIds.delete(id);
1659
+ clearVectorMissing(id);
1614
1660
  succeeded++;
1615
1661
  } catch (error) {
1616
1662
  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
  );
@@ -0,0 +1,25 @@
1
+ import { spawn } from 'node:child_process';
2
+
3
+ const LOCAL_HTTP_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']);
4
+
5
+ export function resolveLocalBrowserCommand(
6
+ target: string,
7
+ platform: NodeJS.Platform = process.platform,
8
+ ): { command: string; args: string[] } {
9
+ const url = new URL(target);
10
+ if (url.protocol !== 'http:' || !LOCAL_HTTP_HOSTS.has(url.hostname) || !url.port || url.username || url.password) {
11
+ throw new Error('Only unauthenticated loopback HTTP URLs can be opened automatically');
12
+ }
13
+ return platform === 'win32'
14
+ ? { command: 'explorer.exe', args: [url.toString()] }
15
+ : platform === 'darwin'
16
+ ? { command: 'open', args: [url.toString()] }
17
+ : { command: 'xdg-open', args: [url.toString()] };
18
+ }
19
+
20
+ export function openLocalBrowser(target: string): void {
21
+ const { command, args } = resolveLocalBrowserCommand(target);
22
+ const child = spawn(command, args, { detached: true, stdio: 'ignore', windowsHide: true });
23
+ child.once('error', () => undefined);
24
+ child.unref();
25
+ }
@@ -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
+ }