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
package/src/server.ts CHANGED
@@ -66,6 +66,8 @@ import {
66
66
  type ProjectBindingTransport,
67
67
  } from './server/request-context.js';
68
68
  import { getMcpServerInfo, registerMcpDiscovery } from './server/mcp-compat.js';
69
+ import { createRuntimeContext, type RuntimeContext } from './core/runtime-context.js';
70
+ import { getResolvedConfig } from './config/resolved-config.js';
69
71
 
70
72
  // ── Timeout budgets for LLM-heavy paths ──────────────────────────
71
73
  const FORMATION_TIMEOUT_MS = parseFormationTimeoutMs(process.env.MEMORIX_FORMATION_TIMEOUT_MS); // Formation pipeline (extract+resolve+evaluate)
@@ -337,6 +339,16 @@ export async function createMemorixServer(
337
339
  writeLastProjectRoot(project.rootPath);
338
340
  }
339
341
 
342
+ let runtimeContext: RuntimeContext;
343
+ const refreshRuntimeContext = (): void => {
344
+ runtimeContext = createRuntimeContext({
345
+ projectId: project.id,
346
+ projectRoot: project.rootPath,
347
+ dataDir: projectDir,
348
+ config: getResolvedConfig({ projectRoot: project.rootPath }),
349
+ });
350
+ };
351
+
340
352
  const registerMaintenanceTarget = async (): Promise<void> => {
341
353
  if (!projectResolved) return;
342
354
  try {
@@ -362,6 +374,7 @@ export async function createMemorixServer(
362
374
  const { loadDotenv } = await import('./config/dotenv-loader.js');
363
375
  loadDotenv(project.rootPath);
364
376
  } catch { /* config init is best-effort */ }
377
+ refreshRuntimeContext();
365
378
 
366
379
  // Initialize lightweight components. Full observation/graph indexing can be
367
380
  // deferred for stdio so MCP initialize/tools/list are not blocked by a large
@@ -532,6 +545,7 @@ export async function createMemorixServer(
532
545
  } catch {
533
546
  // Config activation is best-effort; durable project scoping remains explicit.
534
547
  }
548
+ refreshRuntimeContext();
535
549
  initLLM({ projectRoot: project.rootPath });
536
550
  };
537
551
 
@@ -1642,7 +1656,7 @@ export async function createMemorixServer(
1642
1656
  inputSchema: {
1643
1657
  task: z.string().optional().describe('Current coding task or question'),
1644
1658
  taskId: z.string().max(120).optional().describe('Optional task continuity ledger id to include in the brief'),
1645
- refresh: z.enum(['auto', 'always', 'never']).optional().default('auto').describe(
1659
+ refresh: z.enum(['auto', 'always', 'never']).optional().describe(
1646
1660
  'Code Memory refresh policy. auto refreshes only when missing or stale.',
1647
1661
  ),
1648
1662
  format: z.enum(['prompt', 'summary', 'json', 'receipt']).optional().default('prompt').describe(
@@ -1688,7 +1702,7 @@ export async function createMemorixServer(
1688
1702
  task,
1689
1703
  taskId,
1690
1704
  agent,
1691
- refresh: refresh ?? 'auto',
1705
+ ...(refresh ? { refresh } : {}),
1692
1706
  reader: getObservationReader(),
1693
1707
  enqueueRefresh: () => {
1694
1708
  enqueueCodegraphRefresh({
@@ -1739,15 +1753,14 @@ export async function createMemorixServer(
1739
1753
  const unresolved = requireResolvedProject('show CodeGraph Memory status for the current project');
1740
1754
  if (unresolved) return unresolved;
1741
1755
 
1742
- const [{ CodeGraphStore }, { getResolvedConfig }, { inspectExternalCodeGraph }] = await Promise.all([
1756
+ const [{ CodeGraphStore }, { inspectExternalCodeGraph }] = await Promise.all([
1743
1757
  import('./codegraph/store.js'),
1744
- import('./config/resolved-config.js'),
1745
1758
  import('./codegraph/external-provider.js'),
1746
1759
  ]);
1747
1760
  const store = new CodeGraphStore();
1748
1761
  await store.init(projectDir);
1749
1762
  const status = store.status(project.id);
1750
- const codegraphConfig = getResolvedConfig({ projectRoot: project.rootPath }).codegraph;
1763
+ const codegraphConfig = runtimeContext.config.codegraph;
1751
1764
  const providerQuality = await inspectExternalCodeGraph({
1752
1765
  projectRoot: project.rootPath,
1753
1766
  mode: codegraphConfig.externalContext,
@@ -1789,7 +1802,6 @@ export async function createMemorixServer(
1789
1802
  const [
1790
1803
  { CodeGraphStore },
1791
1804
  { assembleContextPackForTask, attachTaskWorkset, buildContextPackPrompt },
1792
- { getResolvedConfig },
1793
1805
  { getExternalCodeGraphContext },
1794
1806
  { getObservationStore },
1795
1807
  { collectCurrentProjectFacts, formatGitFact },
@@ -1797,7 +1809,6 @@ export async function createMemorixServer(
1797
1809
  ] = await Promise.all([
1798
1810
  import('./codegraph/store.js'),
1799
1811
  import('./codegraph/context-pack.js'),
1800
- import('./config/resolved-config.js'),
1801
1812
  import('./codegraph/external-provider.js'),
1802
1813
  import('./store/obs-store.js'),
1803
1814
  import('./codegraph/current-facts.js'),
@@ -1805,8 +1816,8 @@ export async function createMemorixServer(
1805
1816
  ]);
1806
1817
  const store = new CodeGraphStore();
1807
1818
  await store.init(projectDir);
1808
- const codegraphConfig = getResolvedConfig({ projectRoot: project.rootPath }).codegraph;
1809
- const exclude = codegraphConfig.excludePatterns;
1819
+ const codegraphConfig = runtimeContext.config.codegraph;
1820
+ const exclude = codegraphConfig.excludePatterns ? [...codegraphConfig.excludePatterns] : undefined;
1810
1821
  const observations = filterReadableObservations(
1811
1822
  await getObservationStore().loadByProject(project.id, { status: 'active' }),
1812
1823
  getObservationReader(),
@@ -5829,6 +5840,7 @@ export async function createMemorixServer(
5829
5840
  resetDotenv();
5830
5841
  loadDotenv(project.rootPath);
5831
5842
  } catch { /* best-effort */ }
5843
+ refreshRuntimeContext();
5832
5844
 
5833
5845
  // Reinitialize TeamStore for the new project (per-project isolation)
5834
5846
  // In HTTP mode, the shared TeamStore from serve-http is replaced with
@@ -22,6 +22,13 @@ import { degradedReadError, degradedWriteError, formatSqliteFailure, isSqliteUna
22
22
  * The outer `atomic()` already holds the lock / transaction.
23
23
  */
24
24
  export interface StoreTransaction {
25
+ /** Register rebuildable derived work inside the canonical transaction. */
26
+ enqueueMaintenanceJob?(input: {
27
+ projectId: string;
28
+ kind: string;
29
+ dedupeKey: string;
30
+ payload?: Record<string, unknown>;
31
+ }): Promise<void>;
25
32
  /** Load all observations (raw, no lock). */
26
33
  loadAll(): Promise<Observation[]>;
27
34
  /** Load one observation by its globally unique ID (raw, no lock). */
@@ -186,6 +193,14 @@ export function getObservationStore(): ObservationStore {
186
193
  return _store;
187
194
  }
188
195
 
196
+ /** Return the data directory bound to the active canonical store. */
197
+ export function getObservationStoreDataDir(): string {
198
+ if (!_store || !_storeDataDir) {
199
+ throw new Error('[memorix] ObservationStore data directory is not bound');
200
+ }
201
+ return _storeDataDir;
202
+ }
203
+
189
204
  /** Set the active ObservationStore singleton (called once during startup). */
190
205
  export function setObservationStore(store: ObservationStore): void {
191
206
  _store = store;
@@ -28,12 +28,14 @@ import { maybeExpandSearchQuery } from '../search/query-expansion.js';
28
28
  import { parseRerankTimeoutMs, shouldAttemptHttpRerank, shouldAttemptLlmRerank } from '../rerank/policy.js';
29
29
  import { withTimeout, withTimeoutSignal } from '../timeout.js';
30
30
  import { getObservationStore } from './obs-store.js';
31
+ import { getResolvedConfig } from '../config/resolved-config.js';
32
+ import { isCjkHeavyQuery } from '../config/retrieval-strategy.js';
33
+ import { createSemanticDerivedView } from '../search/semantic-view.js';
34
+ import { createRetrievalPlan, type RetrievalReceipt } from '../core/retrieval-contracts.js';
31
35
  import {
32
36
  createSemanticIndexProfile,
33
37
  searchSemanticVectors,
34
38
  listSemanticVectorIds,
35
- upsertSemanticVector,
36
- upsertSemanticVectors,
37
39
  type SemanticIndexProfile,
38
40
  type SemanticVectorRecord,
39
41
  } from '../search/semantic-index.js';
@@ -52,20 +54,27 @@ let indexEmbeddingProvider: EmbeddingProvider | null = null;
52
54
  let deferredCachedVectorHydration: Promise<void> | null = null;
53
55
  const NON_CJK_HYBRID_SIMILARITY = 0.45;
54
56
  const CJK_RUN = /[\u3400-\u4dbf\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]+/gu;
57
+
58
+ /** CJK tokenization already emits character and bigram tokens. Fuzzy matching
59
+ * those expanded tokens grows superlinearly on large Orama indexes. */
60
+ export function resolveSearchFuzzyTolerance(query: string, quality: 'fast' | 'balanced' | 'thorough'): number | undefined {
61
+ if (quality === 'fast') return undefined;
62
+ const characters = [...query];
63
+ const cjkCount = characters.filter((char) => /[\u3400-\u4dbf\u4e00-\u9fff\u3040-\u30ff\uac00-\ud7af]/u.test(char)).length;
64
+ if (characters.length > 0 && cjkCount / characters.length > 0.3) return undefined;
65
+ return query.length > 6 ? 2 : 1;
66
+ }
55
67
  const lastSearchModeByProject = new Map<string, string>();
56
- export interface SearchDiagnostics {
57
- version: '1';
58
- mode: string;
68
+ export interface SearchDiagnostics extends RetrievalReceipt {
59
69
  rawCandidateCount: number;
60
- candidateCount: number;
61
- selectedCount: number;
62
- omittedCount: number;
63
- omittedByTokenBudget: number;
64
- fallbackUsed: boolean;
65
- fallbackReason?: string;
66
- elapsedMs: number;
67
70
  }
68
71
  const lastSearchDiagnosticsByProject = new Map<string, SearchDiagnostics>();
72
+ export interface SearchExecution {
73
+ entries: IndexEntry[];
74
+ diagnostics: SearchDiagnostics;
75
+ derivedViews: RetrievalDerivedViews;
76
+ recordAccess?: (selected: IndexEntry[]) => void;
77
+ }
69
78
  const SEARCH_MODE_DEFAULT_KEY = '__global__';
70
79
  const MAX_SEARCH_MODE_KEYS = 4096;
71
80
 
@@ -327,6 +336,54 @@ async function searchPersistentLexically(
327
336
  * candidate list. The vector index is a derived accelerator; authoritative
328
337
  * observation rows still come from SQLite before visibility is applied.
329
338
  */
339
+ async function searchLanceInVectorOrder(
340
+ options: SearchOptions,
341
+ projectIds: string[] | null,
342
+ limit: number,
343
+ queryVector: number[],
344
+ provider: EmbeddingProvider,
345
+ ): Promise<SearchResultLike | null> {
346
+ try {
347
+ const { getObservationDataDir } = await import('../memory/observations.js');
348
+ const dataDir = getObservationDataDir();
349
+ if (!dataDir) return null;
350
+ const vectorHits = await searchSemanticVectors({
351
+ dataDir,
352
+ profile: createSemanticIndexProfile(provider),
353
+ vector: queryVector,
354
+ projectId: projectIds ?? options.projectId,
355
+ status: 'all',
356
+ limit: Math.min(10_000, Math.max(limit, 1) * 4),
357
+ });
358
+ if (!vectorHits || vectorHits.length === 0) return null;
359
+
360
+ const store = getObservationStore();
361
+ const hits: SearchHitLike[] = [];
362
+ const seen = new Set<number>();
363
+ for (const hit of vectorHits) {
364
+ if (seen.has(hit.observationId)) continue;
365
+ seen.add(hit.observationId);
366
+ const observation = await store.getById(hit.observationId);
367
+ if (!observation) continue;
368
+ if (projectIds && !projectIds.includes(observation.projectId)) continue;
369
+ if (options.status !== 'all' && (observation.status ?? 'active') !== (options.status ?? 'active')) continue;
370
+ if (options.type && observation.type !== options.type) continue;
371
+ if (options.source && observation.source !== options.source) continue;
372
+ const document = observationToSearchDocument(observation);
373
+ hits.push({
374
+ id: document.id,
375
+ score: 1 / (1 + hits.length),
376
+ document,
377
+ });
378
+ if (hits.length >= limit) break;
379
+ }
380
+ if (hits.length === 0) return null;
381
+ return { count: hits.length, hits };
382
+ } catch {
383
+ return null;
384
+ }
385
+ }
386
+
330
387
  async function searchPersistentSemantically(
331
388
  options: SearchOptions,
332
389
  projectIds: string[] | null,
@@ -582,6 +639,11 @@ export async function getDb(options: { allowNetworkProbe?: boolean } = {}): Prom
582
639
  }
583
640
  }
584
641
 
642
+ /** Return the number of documents currently held by the in-process derived index. */
643
+ export async function countIndexedDocuments(database?: AnyOrama): Promise<number> {
644
+ return count(database ?? await getDb({ allowNetworkProbe: false }));
645
+ }
646
+
585
647
  /**
586
648
  * Reset the database instance (useful for testing).
587
649
  */
@@ -635,7 +697,7 @@ export async function queueSemanticVector(
635
697
  const profile = provider ? createSemanticIndexProfile(provider) : null;
636
698
  if (!profile) return;
637
699
  try {
638
- await upsertSemanticVector(dataDir, profile, record);
700
+ await createSemanticDerivedView(dataDir, profile).refresh([record]);
639
701
  } catch {
640
702
  // The vector index is rebuildable; lexical memory remains authoritative.
641
703
  }
@@ -779,7 +841,7 @@ async function attachCachedVectors(
779
841
  }
780
842
  }
781
843
  if (semanticDataDir && semanticProfile && semanticRecords.length > 0) {
782
- void upsertSemanticVectors(semanticDataDir, semanticProfile, semanticRecords).catch(() => {
844
+ void createSemanticDerivedView(semanticDataDir, semanticProfile).refresh(semanticRecords).catch(() => {
783
845
  // A rebuildable semantic index must never make startup hydration fail.
784
846
  });
785
847
  }
@@ -948,7 +1010,9 @@ export async function removeObservation(oramaId: string): Promise<void> {
948
1010
  *
949
1011
  * Progressive Disclosure Layer 1 — adopted from claude-mem.
950
1012
  */
951
- export async function searchObservations(options: SearchOptions): Promise<IndexEntry[]> {
1013
+ export async function searchObservationsDetailed(options: SearchOptions): Promise<SearchExecution> {
1014
+ const retrievalPlan = createRetrievalPlan(options);
1015
+ options = { ...options, ...retrievalPlan } as SearchOptions;
952
1016
  const searchStartedAt = Date.now();
953
1017
  const perf = !!process.env.MEMORIX_PERF;
954
1018
  const t0 = perf ? performance.now() : 0;
@@ -956,10 +1020,12 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
956
1020
  const modeKey = options.projectId ?? SEARCH_MODE_DEFAULT_KEY;
957
1021
  const quality = options.quality ?? 'balanced';
958
1022
  const database = await getDb();
959
- rememberSearchMode(
960
- modeKey,
961
- quality === 'fast' ? 'fulltext (fast profile)' : embeddingEnabled ? 'hybrid' : 'fulltext',
962
- );
1023
+ let requestMode = quality === 'fast' ? 'fulltext (fast profile)' : embeddingEnabled ? 'hybrid' : 'fulltext';
1024
+ const setMode = (mode: string) => {
1025
+ requestMode = mode;
1026
+ rememberSearchMode(modeKey, mode);
1027
+ };
1028
+ setMode(requestMode);
963
1029
 
964
1030
  // Resolve project aliases — safety net for observations not yet migrated to canonical ID.
965
1031
  // After migration, this is typically a single-element array matching options.projectId.
@@ -987,7 +1053,7 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
987
1053
 
988
1054
  // Determine search mode: hybrid (with vector) or fulltext (default)
989
1055
  const hasQuery = options.query && options.query.trim().length > 0;
990
- const originalQuery = options.query;
1056
+ const originalQuery = retrievalPlan.query;
991
1057
  // The fast profile is a bounded local probe, not a lower-quality spelling
992
1058
  // corrector. Skip query classification and the expensive recall enrichments
993
1059
  // it would otherwise inherit from the balanced path.
@@ -1046,7 +1112,12 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1046
1112
  // Fuzzy tolerance: allow 1-char typos for short queries, 2 for longer
1047
1113
  // Fuzzy matching is useful for ordinary recall, but grows sharply with
1048
1114
  // corpus size. The fast profile deliberately uses exact lexical matching.
1049
- ...(hasQuery && quality !== 'fast' ? { tolerance: originalQuery!.length > 6 ? 2 : 1 } : {}),
1115
+ ...(hasQuery
1116
+ ? (() => {
1117
+ const tolerance = resolveSearchFuzzyTolerance(originalQuery!, quality);
1118
+ return tolerance === undefined ? {} : { tolerance };
1119
+ })()
1120
+ : {}),
1050
1121
  };
1051
1122
 
1052
1123
  // If embedding provider is available and query tier warrants it, use hybrid search
@@ -1070,10 +1141,7 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1070
1141
  embeddingUnavailable = true;
1071
1142
  fallbackUsed = true;
1072
1143
  fallbackReason = 'embedding dimension mismatch; lexical search used';
1073
- rememberSearchMode(
1074
- modeKey,
1075
- `fulltext (embedding dimension mismatch: provider ${provider.dimensions}d vs index ${activeVectorDimensions}d)`,
1076
- );
1144
+ setMode(`fulltext (embedding dimension mismatch: provider ${provider.dimensions}d vs index ${activeVectorDimensions}d)`);
1077
1145
  console.error(
1078
1146
  `[memorix] Embedding provider dimension mismatch (${provider.dimensions}d provider vs ${activeVectorDimensions}d index); using fulltext search`,
1079
1147
  );
@@ -1099,7 +1167,7 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1099
1167
  // Detect CJK-heavy queries: BM25 can't tokenize Chinese/Japanese/Korean well
1100
1168
  const cjkRatio = (originalQuery!.match(/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g) || []).length / originalQuery!.length;
1101
1169
  const isCJKHeavy = cjkRatio > 0.3;
1102
- rememberSearchMode(modeKey, 'hybrid');
1170
+ setMode('hybrid');
1103
1171
  searchParams = {
1104
1172
  ...searchParams,
1105
1173
  mode: 'hybrid',
@@ -1125,13 +1193,25 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1125
1193
  embeddingUnavailable = true;
1126
1194
  fallbackUsed = true;
1127
1195
  fallbackReason = 'embedding failed or timed out; lexical search used';
1128
- rememberSearchMode(modeKey, 'fulltext (embedding unavailable)');
1196
+ setMode('fulltext (embedding unavailable)');
1129
1197
  console.error('[memorix] Embedding failed or timed out, falling back to fulltext search');
1130
1198
  }
1131
1199
  }
1132
1200
 
1133
1201
  mark('preSearch');
1134
1202
  let results: SearchResultLike | Awaited<ReturnType<typeof search>>;
1203
+ const retrieval = getResolvedConfig().retrieval;
1204
+ const wantLanceOrder = (isCjkHeavyQuery(originalQuery ?? '') ? retrieval.cjk : retrieval.ascii) === 'vector';
1205
+ let lanceOrderUsed = false;
1206
+ let persistent: SearchResultLike | null = null;
1207
+ if (wantLanceOrder && queryVector && embeddingProviderForSearch) {
1208
+ persistent = await searchLanceInVectorOrder(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch);
1209
+ if (persistent) lanceOrderUsed = true;
1210
+ else {
1211
+ fallbackUsed = true;
1212
+ fallbackReason = fallbackReason ?? 'lance vector index empty; hybrid search used';
1213
+ }
1214
+ }
1135
1215
  const persistentCorpusEligible = await shouldUsePersistentSearch(projectIds, options.projectId);
1136
1216
  // `embeddingEnabled` alone misses the common case: embedding is configured
1137
1217
  // (enabled) but the current provider is unavailable, has incompatible
@@ -1141,7 +1221,7 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1141
1221
  // deterministic empty result despite the FTS5 index having real matches.
1142
1222
  const canUsePersistentLexical = persistentCorpusEligible && Boolean(hasQuery) && !queryVector &&
1143
1223
  (quality === 'fast' || tier === 'fast' || !embeddingEnabled || embeddingUnavailable);
1144
- let persistent = persistentCorpusEligible && queryVector && embeddingProviderForSearch
1224
+ if (!persistent) persistent = persistentCorpusEligible && queryVector && embeddingProviderForSearch
1145
1225
  ? await searchPersistentSemantically(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch)
1146
1226
  : canUsePersistentLexical
1147
1227
  ? await searchPersistentLexically(options, projectIds, requestLimit)
@@ -1159,17 +1239,14 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1159
1239
  results = persistent;
1160
1240
  // Keep the public mode label compatible with existing integrations while
1161
1241
  // exposing the concrete accelerator through performance marks/status.
1162
- rememberSearchMode(
1163
- modeKey,
1164
- queryVector ? 'hybrid' : quality === 'fast' ? 'fulltext (fast profile)' : 'fulltext',
1165
- );
1242
+ setMode(lanceOrderUsed ? 'vector' : queryVector ? 'hybrid' : quality === 'fast' ? 'fulltext (fast profile)' : 'fulltext');
1166
1243
  mark(queryVector ? 'persistentHybridSearch' : 'sqliteFtsSearch');
1167
1244
  } else {
1168
1245
  try {
1169
1246
  results = await search(database, searchParams);
1170
1247
  } catch (error) {
1171
1248
  if (queryVector && isVectorDimensionMismatchError(error)) {
1172
- rememberSearchMode(modeKey, 'fulltext (embedding dimension mismatch)');
1249
+ setMode('fulltext (embedding dimension mismatch)');
1173
1250
  console.error('[memorix] Vector search dimension mismatch detected, retrying without embeddings');
1174
1251
  results = await search(database, stripVectorSearchParams(searchParams));
1175
1252
  } else {
@@ -1194,7 +1271,7 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1194
1271
  },
1195
1272
  similarity: 0.25,
1196
1273
  };
1197
- rememberSearchMode(modeKey, 'vector-only (hybrid empty fallback)');
1274
+ setMode('vector-only (hybrid empty fallback)');
1198
1275
  fallbackUsed = true;
1199
1276
  fallbackReason = 'hybrid search returned no results; vector-only fallback used';
1200
1277
  results = await search(database, vectorOnlyParams);
@@ -1371,15 +1448,24 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1371
1448
  });
1372
1449
  }
1373
1450
 
1374
- // Apply affinity scoring to each result
1451
+ // Affinity is a tie-breaker, not a second relevance model. RRF scores are
1452
+ // intentionally flat; multiplying every result by 0.65 can demote a rank-1
1453
+ // exact lexical match below rank-30 noise. Only close candidates receive a
1454
+ // bounded affinity adjustment, while the primary retrieval score remains
1455
+ // the ordering authority.
1456
+ const topScore = Math.max(...intermediate.map((entry) => entry.score));
1457
+ const affinityTieWindow = topScore * 0.92;
1458
+
1459
+ // Apply affinity scoring only to close candidates.
1375
1460
  intermediate = intermediate.map(entry => {
1376
1461
  const memory = memoryContentMap.get(entry.id);
1377
1462
  if (!memory) return entry;
1378
1463
 
1379
1464
  const { score: affinityScore } = calculateProjectAffinity(memory, affinityContext);
1465
+ if (entry.score < affinityTieWindow) return entry;
1380
1466
  return {
1381
1467
  ...entry,
1382
- score: entry.score * affinityScore, // Apply affinity as multiplier
1468
+ score: entry.score * (0.98 + (affinityScore * 0.02)),
1383
1469
  };
1384
1470
  });
1385
1471
 
@@ -1548,7 +1634,7 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1548
1634
  .filter((entry): entry is NonNullable<typeof entry> => entry != null);
1549
1635
  if (rerankedTop.length > 0) {
1550
1636
  intermediate = [...rerankedTop, ...intermediate.slice(RERANK_TOP_K)];
1551
- rememberSearchMode(modeKey, (lastSearchModeByProject.get(modeKey) ?? 'fulltext') + ' + neural rerank');
1637
+ setMode(requestMode + ' + neural rerank');
1552
1638
  mark('rerank(usedNeural=true)');
1553
1639
  }
1554
1640
  }
@@ -1565,7 +1651,7 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1565
1651
  );
1566
1652
  mark(`rerank(usedLLM=${usedLLM})`);
1567
1653
  if (usedLLM) {
1568
- rememberSearchMode(modeKey, (lastSearchModeByProject.get(modeKey) ?? 'fulltext') + ' + LLM rerank');
1654
+ setMode(requestMode + ' + LLM rerank');
1569
1655
  const rerankedTop = reranked
1570
1656
  .map((row) => candidateMap.get(row.id))
1571
1657
  .filter((entry): entry is NonNullable<typeof entry> => entry != null);
@@ -1641,9 +1727,9 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1641
1727
  entries = applyTokenBudget(entries, options.maxTokens);
1642
1728
  }
1643
1729
 
1644
- rememberSearchDiagnostics(modeKey, {
1730
+ const diagnostics: SearchDiagnostics = {
1645
1731
  version: '1',
1646
- mode: getLastSearchMode(options.projectId),
1732
+ mode: requestMode,
1647
1733
  rawCandidateCount: results.hits.length,
1648
1734
  candidateCount,
1649
1735
  selectedCount: entries.length,
@@ -1652,18 +1738,30 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1652
1738
  fallbackUsed,
1653
1739
  ...(fallbackReason ? { fallbackReason } : {}),
1654
1740
  elapsedMs: Math.max(0, Date.now() - searchStartedAt),
1655
- });
1741
+ };
1742
+ rememberSearchDiagnostics(modeKey, diagnostics);
1656
1743
 
1657
- // Record access for returned results (fire-and-forget, non-blocking).
1658
- if (options.trackAccess !== false) {
1659
- const returnedKeys = new Set(entries.map((entry) => makeEntryKey(entry.projectId, entry.id)));
1744
+ const recordAccess = (selected: IndexEntry[]): void => {
1745
+ if (options.trackAccess === false || selected.length === 0) return;
1746
+ const returnedKeys = new Set(selected.map((entry) => makeEntryKey(entry.projectId, entry.id)));
1660
1747
  const hitDocs = results.hits
1661
1748
  .map((hit) => ({ id: hit.id, doc: hit.document as unknown as MemorixDocument }))
1662
1749
  .filter(({ doc }) => returnedKeys.has(makeEntryKey(doc.projectId, doc.observationId)));
1663
1750
  recordAccessBatch(hitDocs).catch(() => {});
1751
+ };
1752
+
1753
+ const derivedViews = getSearchDerivedViews();
1754
+ if (fallbackUsed && fallbackReason) {
1755
+ derivedViews.embedding = { freshness: 'stale', rebuildStatus: 'failed', failureReason: fallbackReason };
1664
1756
  }
1757
+ return { entries, diagnostics, derivedViews, recordAccess };
1758
+ }
1665
1759
 
1666
- return entries;
1760
+ /** Keep the historical array API for SDKs and integrations. */
1761
+ export async function searchObservations(options: SearchOptions): Promise<IndexEntry[]> {
1762
+ const result = await searchObservationsDetailed(options);
1763
+ result.recordAccess?.(result.entries);
1764
+ return result.entries;
1667
1765
  }
1668
1766
 
1669
1767
  /**
@@ -708,6 +708,12 @@ CREATE TABLE IF NOT EXISTS maintenance_jobs (
708
708
  lease_owner TEXT,
709
709
  lease_expires_at INTEGER,
710
710
  last_error TEXT,
711
+ attempted INTEGER NOT NULL DEFAULT 0,
712
+ succeeded INTEGER NOT NULL DEFAULT 0,
713
+ failed INTEGER NOT NULL DEFAULT 0,
714
+ remaining INTEGER NOT NULL DEFAULT 0,
715
+ progress_recorded INTEGER NOT NULL DEFAULT 0,
716
+ rerun_requested INTEGER NOT NULL DEFAULT 0,
711
717
  created_at INTEGER NOT NULL,
712
718
  updated_at INTEGER NOT NULL,
713
719
  completed_at INTEGER
@@ -1153,6 +1159,22 @@ const SCHEMA_MIGRATIONS: SchemaMigration[] = [
1153
1159
  WHERE event_key IS NOT NULL`);
1154
1160
  },
1155
1161
  },
1162
+ {
1163
+ id: '1.11-maintenance-progress',
1164
+ apply: (db) => {
1165
+ addColumnIfMissing(db, 'maintenance_jobs', 'attempted', 'attempted INTEGER NOT NULL DEFAULT 0');
1166
+ addColumnIfMissing(db, 'maintenance_jobs', 'succeeded', 'succeeded INTEGER NOT NULL DEFAULT 0');
1167
+ addColumnIfMissing(db, 'maintenance_jobs', 'failed', 'failed INTEGER NOT NULL DEFAULT 0');
1168
+ addColumnIfMissing(db, 'maintenance_jobs', 'remaining', 'remaining INTEGER NOT NULL DEFAULT 0');
1169
+ addColumnIfMissing(db, 'maintenance_jobs', 'progress_recorded', 'progress_recorded INTEGER NOT NULL DEFAULT 0');
1170
+ },
1171
+ },
1172
+ {
1173
+ id: '1.11-maintenance-rerun',
1174
+ apply: (db) => {
1175
+ addColumnIfMissing(db, 'maintenance_jobs', 'rerun_requested', 'rerun_requested INTEGER NOT NULL DEFAULT 0');
1176
+ },
1177
+ },
1156
1178
  ];
1157
1179
 
1158
1180
  function applySchemaMigrations(db: any): void {
@@ -15,6 +15,7 @@
15
15
  * mini-skills, and sessions all share one connection and one DB file.
16
16
  */
17
17
 
18
+ import { randomUUID } from 'node:crypto';
18
19
  import type { Observation } from '../types.js';
19
20
  import type { ObservationStore, StoreTransaction } from './obs-store.js';
20
21
  import { getDatabase, closeDatabase } from './sqlite-db.js';
@@ -488,6 +489,32 @@ export class SqliteBackend implements ObservationStore {
488
489
  }, 'Observation atomic write');
489
490
  try {
490
491
  const tx: StoreTransaction = {
492
+ enqueueMaintenanceJob: async (input) => {
493
+ const payloadJson = JSON.stringify(input.payload ?? {});
494
+ const existing = this.db.prepare(`
495
+ SELECT id, status FROM maintenance_jobs
496
+ WHERE project_id = ? AND kind = ? AND dedupe_key = ?
497
+ AND status IN ('pending', 'running', 'retry')
498
+ LIMIT 1
499
+ `).get(input.projectId, input.kind, input.dedupeKey);
500
+ if (existing) {
501
+ if (existing.status === 'running') {
502
+ this.db.prepare(`
503
+ UPDATE maintenance_jobs
504
+ SET rerun_requested = 1, payload_json = ?, updated_at = ?
505
+ WHERE id = ?
506
+ `).run(payloadJson, Date.now(), existing.id);
507
+ }
508
+ return;
509
+ }
510
+ const now = Date.now();
511
+ this.db.prepare(`
512
+ INSERT INTO maintenance_jobs (
513
+ id, project_id, kind, dedupe_key, payload_json, status, attempts,
514
+ max_attempts, run_after, created_at, updated_at
515
+ ) VALUES (?, ?, ?, ?, ?, 'pending', 0, 8, ?, ?, ?)
516
+ `).run(randomUUID(), input.projectId, input.kind, input.dedupeKey, payloadJson, now, now, now);
517
+ },
491
518
  loadAll: async () => this.rawLoadAll(),
492
519
  getById: async (id) => this.rawGetById(id),
493
520
  findByTopicKey: async (projectId, topicKey) => this.rawFindByTopicKey(projectId, topicKey),
package/src/types.ts CHANGED
@@ -670,7 +670,7 @@ export interface MemoryRef {
670
670
  /** MCP config format adapter interface */
671
671
  export interface MCPConfigAdapter {
672
672
  /** Setup-only adapters may support a host that does not participate in workspace sync. */
673
- readonly source: AgentTarget | 'codebuddy' | 'dsh' | 'workbuddy' | 'grok';
673
+ readonly source: AgentTarget | 'codebuddy' | 'dsh' | 'workbuddy' | 'grok' | 'pi';
674
674
  /** Parse MCP server entries from a config file */
675
675
  parse(content: string): MCPServerEntry[];
676
676
  /** Generate config file content from MCP server entries */
@@ -0,0 +1,58 @@
1
+ import type { MCPConfigAdapter, MCPServerEntry } from '../../types.js';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+
5
+ /**
6
+ * Native Pi MCP configuration (Pi 1.0+).
7
+ * Project: .pi/mcp.json; user: ~/.pi/agent/mcp.json.
8
+ * The extension/skills package is installed separately through `pi install`.
9
+ * https://github.com/earendil-works/pi/blob/v1.0.0/packages/coding-agent/docs/mcp.md
10
+ */
11
+ export class PiMCPAdapter implements MCPConfigAdapter {
12
+ readonly source = 'pi' as const;
13
+
14
+ parse(content: string): MCPServerEntry[] {
15
+ try {
16
+ const config = JSON.parse(content);
17
+ const servers = config.mcpServers;
18
+ if (!servers || typeof servers !== 'object' || Array.isArray(servers)) return [];
19
+
20
+ return Object.entries(servers).flatMap(([name, entry]: [string, any]) => {
21
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) return [];
22
+ return [{
23
+ name,
24
+ command: entry.command ?? '',
25
+ args: Array.isArray(entry.args) ? entry.args : [],
26
+ ...(entry.env && Object.keys(entry.env).length > 0 ? { env: entry.env } : {}),
27
+ ...(entry.url ? { url: entry.url } : {}),
28
+ ...(entry.headers && Object.keys(entry.headers).length > 0 ? { headers: entry.headers } : {}),
29
+ ...(entry.enabled === false ? { disabled: true } : {}),
30
+ }];
31
+ });
32
+ } catch {
33
+ return [];
34
+ }
35
+ }
36
+
37
+ generate(servers: MCPServerEntry[]): string {
38
+ const mcpServers: Record<string, unknown> = {};
39
+ for (const server of servers) {
40
+ const entry: Record<string, unknown> = server.url
41
+ ? { url: server.url }
42
+ : { command: server.command, args: server.args };
43
+ if (server.url && server.headers && Object.keys(server.headers).length > 0) {
44
+ entry.headers = server.headers;
45
+ }
46
+ if (server.env && Object.keys(server.env).length > 0) entry.env = server.env;
47
+ if (server.disabled === true) entry.enabled = false;
48
+ mcpServers[server.name] = entry;
49
+ }
50
+ return JSON.stringify({ mcpServers }, null, 2) + '\n';
51
+ }
52
+
53
+ getConfigPath(projectRoot?: string): string {
54
+ return projectRoot
55
+ ? join(projectRoot, '.pi', 'mcp.json')
56
+ : join(homedir(), '.pi', 'agent', 'mcp.json');
57
+ }
58
+ }