memorix 1.10.3 → 1.10.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +62 -1
  2. package/dist/cli/index.js +1886 -1273
  3. package/dist/index.js +1724 -1088
  4. package/dist/{maintenance-jobs-DVRF-46r.d.ts → maintenance-jobs-DweoCoTT.d.ts} +25 -15
  5. package/dist/maintenance-runner.d.ts +1 -1
  6. package/dist/maintenance-runner.js +694 -172
  7. package/dist/media-audio-runner.js +685 -164
  8. package/dist/media-video-runner.js +693 -172
  9. package/dist/memcode-runtime/CHANGELOG.md +44 -1
  10. package/dist/sdk.js +13952 -13345
  11. package/dist/vector-backfill-runner.d.ts +1 -1
  12. package/dist/vector-backfill-runner.js +693 -172
  13. package/docs/ARCHITECTURE.md +219 -0
  14. package/docs/CONFIGURATION.md +15 -0
  15. package/docs/DESIGN_DECISIONS.md +37 -0
  16. package/docs/DEVELOPMENT.md +1 -1
  17. package/docs/MODULES.md +7 -1
  18. package/docs/PERFORMANCE.md +14 -0
  19. package/docs/README.md +1 -1
  20. package/docs/ROADMAP-1.9.12-2.0.md +18 -2
  21. package/package.json +1 -1
  22. package/plugins/antigravity/memorix/plugin.json +1 -1
  23. package/plugins/claude/memorix/.claude-plugin/plugin.json +1 -1
  24. package/plugins/codebuddy/memorix/.codebuddy-plugin/plugin.json +1 -1
  25. package/plugins/codex/memorix/.codex-plugin/plugin.json +1 -1
  26. package/plugins/copilot/memorix/plugin.json +1 -1
  27. package/plugins/gemini/memorix/gemini-extension.json +1 -1
  28. package/plugins/hermes/memorix/plugin.yaml +1 -1
  29. package/plugins/omp/memorix/package.json +1 -1
  30. package/plugins/openclaw/memorix/.codex-plugin/plugin.json +1 -1
  31. package/plugins/pi/memorix/package.json +1 -1
  32. package/server.json +2 -2
  33. package/src/cli/tui/chat-service.ts +6 -9
  34. package/src/cli/tui/data.ts +2 -2
  35. package/src/codegraph/auto-context.ts +9 -2
  36. package/src/codegraph/derived-view.ts +63 -0
  37. package/src/compact/engine.ts +10 -33
  38. package/src/config/resolved-config.ts +11 -0
  39. package/src/config/retrieval-strategy.ts +22 -0
  40. package/src/config/toml-loader.ts +5 -0
  41. package/src/config/yaml-loader.ts +7 -0
  42. package/src/core/derived-view.ts +15 -0
  43. package/src/core/maintenance-result.ts +33 -0
  44. package/src/core/retrieval-contracts.ts +57 -0
  45. package/src/core/retrieval-facade.ts +18 -0
  46. package/src/core/retrieval-policy.ts +44 -0
  47. package/src/core/runtime-context.ts +42 -0
  48. package/src/embedding/api-provider.ts +18 -8
  49. package/src/knowledge/workset.ts +0 -2
  50. package/src/memory/consolidation.ts +3 -2
  51. package/src/memory/feedback-model.ts +1 -4
  52. package/src/memory/observations.ts +165 -87
  53. package/src/runtime/control-plane-maintenance.ts +1 -0
  54. package/src/runtime/isolated-maintenance.ts +1 -0
  55. package/src/runtime/maintenance-jobs.ts +123 -32
  56. package/src/runtime/project-maintenance.ts +69 -1
  57. package/src/sdk.ts +3 -2
  58. package/src/search/fts-view.ts +53 -0
  59. package/src/search/orama-view.ts +40 -0
  60. package/src/search/retrieval-facade.ts +38 -0
  61. package/src/search/semantic-index.ts +13 -0
  62. package/src/search/semantic-view.ts +34 -0
  63. package/src/server.ts +19 -7
  64. package/src/store/obs-store.ts +15 -0
  65. package/src/store/orama-store.ts +116 -42
  66. package/src/store/sqlite-db.ts +22 -0
  67. package/src/store/sqlite-store.ts +27 -0
@@ -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';
@@ -63,19 +65,16 @@ export function resolveSearchFuzzyTolerance(query: string, quality: 'fast' | 'ba
63
65
  return query.length > 6 ? 2 : 1;
64
66
  }
65
67
  const lastSearchModeByProject = new Map<string, string>();
66
- export interface SearchDiagnostics {
67
- version: '1';
68
- mode: string;
68
+ export interface SearchDiagnostics extends RetrievalReceipt {
69
69
  rawCandidateCount: number;
70
- candidateCount: number;
71
- selectedCount: number;
72
- omittedCount: number;
73
- omittedByTokenBudget: number;
74
- fallbackUsed: boolean;
75
- fallbackReason?: string;
76
- elapsedMs: number;
77
70
  }
78
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
+ }
79
78
  const SEARCH_MODE_DEFAULT_KEY = '__global__';
80
79
  const MAX_SEARCH_MODE_KEYS = 4096;
81
80
 
@@ -337,6 +336,54 @@ async function searchPersistentLexically(
337
336
  * candidate list. The vector index is a derived accelerator; authoritative
338
337
  * observation rows still come from SQLite before visibility is applied.
339
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
+
340
387
  async function searchPersistentSemantically(
341
388
  options: SearchOptions,
342
389
  projectIds: string[] | null,
@@ -592,6 +639,11 @@ export async function getDb(options: { allowNetworkProbe?: boolean } = {}): Prom
592
639
  }
593
640
  }
594
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
+
595
647
  /**
596
648
  * Reset the database instance (useful for testing).
597
649
  */
@@ -645,7 +697,7 @@ export async function queueSemanticVector(
645
697
  const profile = provider ? createSemanticIndexProfile(provider) : null;
646
698
  if (!profile) return;
647
699
  try {
648
- await upsertSemanticVector(dataDir, profile, record);
700
+ await createSemanticDerivedView(dataDir, profile).refresh([record]);
649
701
  } catch {
650
702
  // The vector index is rebuildable; lexical memory remains authoritative.
651
703
  }
@@ -789,7 +841,7 @@ async function attachCachedVectors(
789
841
  }
790
842
  }
791
843
  if (semanticDataDir && semanticProfile && semanticRecords.length > 0) {
792
- void upsertSemanticVectors(semanticDataDir, semanticProfile, semanticRecords).catch(() => {
844
+ void createSemanticDerivedView(semanticDataDir, semanticProfile).refresh(semanticRecords).catch(() => {
793
845
  // A rebuildable semantic index must never make startup hydration fail.
794
846
  });
795
847
  }
@@ -958,7 +1010,9 @@ export async function removeObservation(oramaId: string): Promise<void> {
958
1010
  *
959
1011
  * Progressive Disclosure Layer 1 — adopted from claude-mem.
960
1012
  */
961
- 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;
962
1016
  const searchStartedAt = Date.now();
963
1017
  const perf = !!process.env.MEMORIX_PERF;
964
1018
  const t0 = perf ? performance.now() : 0;
@@ -966,10 +1020,12 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
966
1020
  const modeKey = options.projectId ?? SEARCH_MODE_DEFAULT_KEY;
967
1021
  const quality = options.quality ?? 'balanced';
968
1022
  const database = await getDb();
969
- rememberSearchMode(
970
- modeKey,
971
- quality === 'fast' ? 'fulltext (fast profile)' : embeddingEnabled ? 'hybrid' : 'fulltext',
972
- );
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);
973
1029
 
974
1030
  // Resolve project aliases — safety net for observations not yet migrated to canonical ID.
975
1031
  // After migration, this is typically a single-element array matching options.projectId.
@@ -997,7 +1053,7 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
997
1053
 
998
1054
  // Determine search mode: hybrid (with vector) or fulltext (default)
999
1055
  const hasQuery = options.query && options.query.trim().length > 0;
1000
- const originalQuery = options.query;
1056
+ const originalQuery = retrievalPlan.query;
1001
1057
  // The fast profile is a bounded local probe, not a lower-quality spelling
1002
1058
  // corrector. Skip query classification and the expensive recall enrichments
1003
1059
  // it would otherwise inherit from the balanced path.
@@ -1085,10 +1141,7 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1085
1141
  embeddingUnavailable = true;
1086
1142
  fallbackUsed = true;
1087
1143
  fallbackReason = 'embedding dimension mismatch; lexical search used';
1088
- rememberSearchMode(
1089
- modeKey,
1090
- `fulltext (embedding dimension mismatch: provider ${provider.dimensions}d vs index ${activeVectorDimensions}d)`,
1091
- );
1144
+ setMode(`fulltext (embedding dimension mismatch: provider ${provider.dimensions}d vs index ${activeVectorDimensions}d)`);
1092
1145
  console.error(
1093
1146
  `[memorix] Embedding provider dimension mismatch (${provider.dimensions}d provider vs ${activeVectorDimensions}d index); using fulltext search`,
1094
1147
  );
@@ -1114,7 +1167,7 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1114
1167
  // Detect CJK-heavy queries: BM25 can't tokenize Chinese/Japanese/Korean well
1115
1168
  const cjkRatio = (originalQuery!.match(/[\u4e00-\u9fff\u3040-\u309f\u30a0-\u30ff\uac00-\ud7af]/g) || []).length / originalQuery!.length;
1116
1169
  const isCJKHeavy = cjkRatio > 0.3;
1117
- rememberSearchMode(modeKey, 'hybrid');
1170
+ setMode('hybrid');
1118
1171
  searchParams = {
1119
1172
  ...searchParams,
1120
1173
  mode: 'hybrid',
@@ -1140,13 +1193,25 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1140
1193
  embeddingUnavailable = true;
1141
1194
  fallbackUsed = true;
1142
1195
  fallbackReason = 'embedding failed or timed out; lexical search used';
1143
- rememberSearchMode(modeKey, 'fulltext (embedding unavailable)');
1196
+ setMode('fulltext (embedding unavailable)');
1144
1197
  console.error('[memorix] Embedding failed or timed out, falling back to fulltext search');
1145
1198
  }
1146
1199
  }
1147
1200
 
1148
1201
  mark('preSearch');
1149
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
+ }
1150
1215
  const persistentCorpusEligible = await shouldUsePersistentSearch(projectIds, options.projectId);
1151
1216
  // `embeddingEnabled` alone misses the common case: embedding is configured
1152
1217
  // (enabled) but the current provider is unavailable, has incompatible
@@ -1156,7 +1221,7 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1156
1221
  // deterministic empty result despite the FTS5 index having real matches.
1157
1222
  const canUsePersistentLexical = persistentCorpusEligible && Boolean(hasQuery) && !queryVector &&
1158
1223
  (quality === 'fast' || tier === 'fast' || !embeddingEnabled || embeddingUnavailable);
1159
- let persistent = persistentCorpusEligible && queryVector && embeddingProviderForSearch
1224
+ if (!persistent) persistent = persistentCorpusEligible && queryVector && embeddingProviderForSearch
1160
1225
  ? await searchPersistentSemantically(options, projectIds, requestLimit, queryVector, embeddingProviderForSearch)
1161
1226
  : canUsePersistentLexical
1162
1227
  ? await searchPersistentLexically(options, projectIds, requestLimit)
@@ -1174,17 +1239,14 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1174
1239
  results = persistent;
1175
1240
  // Keep the public mode label compatible with existing integrations while
1176
1241
  // exposing the concrete accelerator through performance marks/status.
1177
- rememberSearchMode(
1178
- modeKey,
1179
- queryVector ? 'hybrid' : quality === 'fast' ? 'fulltext (fast profile)' : 'fulltext',
1180
- );
1242
+ setMode(lanceOrderUsed ? 'vector' : queryVector ? 'hybrid' : quality === 'fast' ? 'fulltext (fast profile)' : 'fulltext');
1181
1243
  mark(queryVector ? 'persistentHybridSearch' : 'sqliteFtsSearch');
1182
1244
  } else {
1183
1245
  try {
1184
1246
  results = await search(database, searchParams);
1185
1247
  } catch (error) {
1186
1248
  if (queryVector && isVectorDimensionMismatchError(error)) {
1187
- rememberSearchMode(modeKey, 'fulltext (embedding dimension mismatch)');
1249
+ setMode('fulltext (embedding dimension mismatch)');
1188
1250
  console.error('[memorix] Vector search dimension mismatch detected, retrying without embeddings');
1189
1251
  results = await search(database, stripVectorSearchParams(searchParams));
1190
1252
  } else {
@@ -1209,7 +1271,7 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1209
1271
  },
1210
1272
  similarity: 0.25,
1211
1273
  };
1212
- rememberSearchMode(modeKey, 'vector-only (hybrid empty fallback)');
1274
+ setMode('vector-only (hybrid empty fallback)');
1213
1275
  fallbackUsed = true;
1214
1276
  fallbackReason = 'hybrid search returned no results; vector-only fallback used';
1215
1277
  results = await search(database, vectorOnlyParams);
@@ -1572,7 +1634,7 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1572
1634
  .filter((entry): entry is NonNullable<typeof entry> => entry != null);
1573
1635
  if (rerankedTop.length > 0) {
1574
1636
  intermediate = [...rerankedTop, ...intermediate.slice(RERANK_TOP_K)];
1575
- rememberSearchMode(modeKey, (lastSearchModeByProject.get(modeKey) ?? 'fulltext') + ' + neural rerank');
1637
+ setMode(requestMode + ' + neural rerank');
1576
1638
  mark('rerank(usedNeural=true)');
1577
1639
  }
1578
1640
  }
@@ -1589,7 +1651,7 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1589
1651
  );
1590
1652
  mark(`rerank(usedLLM=${usedLLM})`);
1591
1653
  if (usedLLM) {
1592
- rememberSearchMode(modeKey, (lastSearchModeByProject.get(modeKey) ?? 'fulltext') + ' + LLM rerank');
1654
+ setMode(requestMode + ' + LLM rerank');
1593
1655
  const rerankedTop = reranked
1594
1656
  .map((row) => candidateMap.get(row.id))
1595
1657
  .filter((entry): entry is NonNullable<typeof entry> => entry != null);
@@ -1665,9 +1727,9 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1665
1727
  entries = applyTokenBudget(entries, options.maxTokens);
1666
1728
  }
1667
1729
 
1668
- rememberSearchDiagnostics(modeKey, {
1730
+ const diagnostics: SearchDiagnostics = {
1669
1731
  version: '1',
1670
- mode: getLastSearchMode(options.projectId),
1732
+ mode: requestMode,
1671
1733
  rawCandidateCount: results.hits.length,
1672
1734
  candidateCount,
1673
1735
  selectedCount: entries.length,
@@ -1676,18 +1738,30 @@ export async function searchObservations(options: SearchOptions): Promise<IndexE
1676
1738
  fallbackUsed,
1677
1739
  ...(fallbackReason ? { fallbackReason } : {}),
1678
1740
  elapsedMs: Math.max(0, Date.now() - searchStartedAt),
1679
- });
1741
+ };
1742
+ rememberSearchDiagnostics(modeKey, diagnostics);
1680
1743
 
1681
- // Record access for returned results (fire-and-forget, non-blocking).
1682
- if (options.trackAccess !== false) {
1683
- 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)));
1684
1747
  const hitDocs = results.hits
1685
1748
  .map((hit) => ({ id: hit.id, doc: hit.document as unknown as MemorixDocument }))
1686
1749
  .filter(({ doc }) => returnedKeys.has(makeEntryKey(doc.projectId, doc.observationId)));
1687
1750
  recordAccessBatch(hitDocs).catch(() => {});
1751
+ };
1752
+
1753
+ const derivedViews = getSearchDerivedViews();
1754
+ if (fallbackUsed && fallbackReason) {
1755
+ derivedViews.embedding = { freshness: 'stale', rebuildStatus: 'failed', failureReason: fallbackReason };
1688
1756
  }
1757
+ return { entries, diagnostics, derivedViews, recordAccess };
1758
+ }
1689
1759
 
1690
- 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;
1691
1765
  }
1692
1766
 
1693
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),