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
@@ -36,10 +36,10 @@ import {
36
36
  isEmbeddingEnabled,
37
37
  makeOramaObservationId,
38
38
  getLastSearchMode,
39
- searchObservations,
39
+ searchObservationsDetailed,
40
40
  updateObservationMetadata,
41
41
  } from '../store/orama-store.js';
42
- import { getObservationStore, initObservationStore, type ObservationStore } from '../store/obs-store.js';
42
+ import { getObservationStore, initObservationStore, type ObservationStore, type StoreTransaction } from '../store/obs-store.js';
43
43
  import { countTextTokens } from '../compact/token-budget.js';
44
44
  import { extractEntities, enrichConcepts } from './entity-extractor.js';
45
45
  import { getEmbeddingProvider, isEmbeddingExplicitlyDisabled, validateEmbeddingInput } from '../embedding/provider.js';
@@ -234,30 +234,48 @@ function queueVectorBackfill(
234
234
  });
235
235
  }
236
236
 
237
- async function bindObservationCodeRefsBestEffort(observation: Observation): Promise<void> {
238
- if (!projectDir) return;
237
+ async function bindObservationCodeRefsBestEffort(observation: Observation): Promise<boolean> {
238
+ if (!projectDir) return true;
239
239
  try {
240
240
  const { CodeGraphStore } = await import('../codegraph/store.js');
241
241
  const { bindObservationToCode } = await import('../codegraph/binder.js');
242
242
  const codeStore = new CodeGraphStore();
243
243
  await codeStore.init(projectDir);
244
244
  await bindObservationToCode(codeStore, observation);
245
+ return true;
245
246
  } catch {
246
247
  // Code refs enrich memory retrieval, but memory writes must remain durable without them.
248
+ return false;
247
249
  }
248
250
  }
249
251
 
250
- async function persistEvidenceCard(observation: Observation): Promise<void> {
251
- if (!projectDir) return;
252
+ async function persistEvidenceCard(observation: Observation): Promise<boolean> {
253
+ if (!projectDir) return true;
252
254
  try {
253
255
  const evidence = new EvidenceCardStore();
254
256
  await evidence.init(projectDir);
255
257
  evidence.upsertObservation(observation);
258
+ return true;
256
259
  } catch (error) {
257
260
  // Evidence is a derived control-plane projection. A failed projection must
258
261
  // never roll back the canonical observation, but it must be visible for a
259
262
  // later repair/sync pass.
260
263
  console.error(`[memorix] Evidence card projection failed for obs-${observation.id}: ${error instanceof Error ? error.message : String(error)}`);
264
+ return false;
265
+ }
266
+ }
267
+
268
+ async function acknowledgeObservationProjection(observation: Observation): Promise<void> {
269
+ if (!projectDir) return;
270
+ try {
271
+ const { MaintenanceJobStore } = await import('../runtime/maintenance-jobs.js');
272
+ new MaintenanceJobStore(projectDir).acknowledgePending(
273
+ observation.projectId,
274
+ 'observation-project',
275
+ 'observation-project:' + observation.id,
276
+ );
277
+ } catch {
278
+ // The pending outbox row remains recoverable by the maintenance worker.
261
279
  }
262
280
  }
263
281
 
@@ -291,6 +309,44 @@ function queueObservationQualification(observation: Observation): void {
291
309
  }
292
310
  }
293
311
 
312
+ async function enqueueObservationDerivedWork(tx: StoreTransaction, observation: Observation): Promise<boolean> {
313
+ if (!tx.enqueueMaintenanceJob) return false;
314
+ if (!isEmbeddingExplicitlyDisabled()) {
315
+ await tx.enqueueMaintenanceJob({
316
+ projectId: observation.projectId,
317
+ kind: 'vector-backfill',
318
+ dedupeKey: 'vector-backfill',
319
+ payload: { limit: 12 },
320
+ });
321
+ }
322
+ if (observation.admissionState === 'candidate') {
323
+ await tx.enqueueMaintenanceJob({
324
+ projectId: observation.projectId,
325
+ kind: 'observation-qualify',
326
+ dedupeKey: 'observation-qualify',
327
+ payload: { source: 'automatic-capture:' + observation.id, limit: 100 },
328
+ });
329
+ }
330
+ const claimSource = observation.sourceDetail === 'explicit'
331
+ || observation.source === 'git'
332
+ || observation.sourceDetail === 'git-ingest';
333
+ if (claimSource && resolveObservationVisibility(observation) === 'project') {
334
+ await tx.enqueueMaintenanceJob({
335
+ projectId: observation.projectId,
336
+ kind: 'claim-derive',
337
+ dedupeKey: 'claim-derive:' + observation.id,
338
+ payload: { observationId: observation.id },
339
+ });
340
+ }
341
+ await tx.enqueueMaintenanceJob({
342
+ projectId: observation.projectId,
343
+ kind: 'observation-project',
344
+ dedupeKey: 'observation-project:' + observation.id,
345
+ payload: { observationId: observation.id },
346
+ });
347
+ return true;
348
+ }
349
+
294
350
  function isVectorCompatibleWithCurrentIndex(embedding: number[] | null): boolean {
295
351
  if (!embedding) return false;
296
352
  const vectorDimensions = getVectorDimensions();
@@ -599,7 +655,6 @@ export async function storeObservation(input: {
599
655
  throw new Error('Cannot update a memory outside this session\'s write scope.');
600
656
  }
601
657
  const observation = await upsertObservation(existing, input, now);
602
- await input.onPersisted?.(observation);
603
658
  return { observation, upserted: true };
604
659
  }
605
660
  }
@@ -630,6 +685,7 @@ export async function storeObservation(input: {
630
685
  let upsertedInsideLock = false;
631
686
  let reloadCacheAfterCommit = false;
632
687
  let persistedCallbackInvoked = false;
688
+ let derivedJobsCommitted = false;
633
689
  const assignAndPersist = async () => {
634
690
  if (projectDir) {
635
691
  const store = getObservationStore();
@@ -698,6 +754,7 @@ export async function storeObservation(input: {
698
754
  };
699
755
 
700
756
  await tx.insert(observation);
757
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, observation);
701
758
  await input.onPersisted?.(observation);
702
759
  persistedCallbackInvoked = true;
703
760
  await tx.saveIdCounter(id + 1);
@@ -820,7 +877,6 @@ export async function storeObservation(input: {
820
877
  // If the lock discovered a topicKey duplicate on disk, delegate to upsert
821
878
  if (upsertedInsideLock) {
822
879
  const updated = await upsertObservation(observation, input, now);
823
- await input.onPersisted?.(updated);
824
880
  return { observation: updated, upserted: true };
825
881
  }
826
882
 
@@ -828,11 +884,14 @@ export async function storeObservation(input: {
828
884
  // transaction. Keep the in-memory fallback defensively covered too.
829
885
  if (!persistedCallbackInvoked) await input.onPersisted?.(observation);
830
886
 
831
- await bindObservationCodeRefsBestEffort(observation);
832
- await persistEvidenceCard(observation);
833
- queueObservationQualification(observation);
834
- if (resolveObservationVisibility(observation) === 'project') {
835
- queueClaimDerivation(observation);
887
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(observation);
888
+ const evidenceProjected = await persistEvidenceCard(observation);
889
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(observation);
890
+ if (!derivedJobsCommitted) {
891
+ queueObservationQualification(observation);
892
+ if (resolveObservationVisibility(observation) === 'project') {
893
+ queueClaimDerivation(observation);
894
+ }
836
895
  }
837
896
 
838
897
  scheduleObservationEmbedding({
@@ -870,6 +929,7 @@ async function upsertObservation(
870
929
  admissionReason?: string;
871
930
  visibility?: ObservationVisibility;
872
931
  sharedWithAgentIds?: string[];
932
+ onPersisted?: (observation: Observation) => void | Promise<void>;
873
933
  },
874
934
  now: string,
875
935
  ): Promise<Observation> {
@@ -888,98 +948,116 @@ async function upsertObservation(
888
948
  const fullText = [input.title, input.narrative, ...(input.facts ?? []), ...enrichedFiles, ...enrichedConcepts].join(' ');
889
949
  const tokens = countTextTokens(fullText);
890
950
 
891
- // Mark old observation as resolved (superseded by new version)
892
- // Note: topicKey upsert replaces in-place, so we just bump revision
893
-
894
- // Update in-place
895
- existing.entityName = input.entityName;
896
- existing.type = input.type;
897
- existing.title = input.title;
898
- existing.narrative = input.narrative;
899
- existing.facts = input.facts ?? [];
900
- existing.attachments = input.attachments;
901
- existing.filesModified = enrichedFiles;
902
- existing.concepts = enrichedConcepts;
903
- existing.tokens = tokens;
904
- existing.updatedAt = now;
905
- existing.hasCausalLanguage = extracted.hasCausalLanguage;
906
- existing.revisionCount = (existing.revisionCount ?? 1) + 1;
907
- existing.status = 'active';
908
- if (input.sessionId) existing.sessionId = input.sessionId;
909
- if (input.progress) existing.progress = input.progress;
910
- if (input.sourceDetail !== undefined) existing.sourceDetail = input.sourceDetail;
911
- if (input.valueCategory !== undefined) existing.valueCategory = input.valueCategory;
912
- if (input.admissionState !== undefined) existing.admissionState = input.admissionState;
913
- if (input.admissionReason !== undefined) existing.admissionReason = sanitizeCredentials(input.admissionReason);
914
- if (input.visibility !== undefined) existing.visibility = input.visibility;
915
- if (input.sharedWithAgentIds !== undefined) existing.sharedWithAgentIds = input.sharedWithAgentIds;
916
-
917
- // Re-index in Orama WITHOUT embedding first (non-blocking)
951
+ const applyUpdate = (current: Observation): Observation => ({
952
+ ...current,
953
+ entityName: input.entityName,
954
+ type: input.type,
955
+ title: input.title,
956
+ narrative: input.narrative,
957
+ facts: input.facts ?? [],
958
+ attachments: input.attachments,
959
+ filesModified: enrichedFiles,
960
+ concepts: enrichedConcepts,
961
+ tokens,
962
+ updatedAt: now,
963
+ hasCausalLanguage: extracted.hasCausalLanguage,
964
+ revisionCount: (current.revisionCount ?? 1) + 1,
965
+ status: 'active',
966
+ ...(input.sessionId ? { sessionId: input.sessionId } : {}),
967
+ ...(input.progress ? { progress: input.progress } : {}),
968
+ ...(input.sourceDetail !== undefined ? { sourceDetail: input.sourceDetail } : {}),
969
+ ...(input.valueCategory !== undefined ? { valueCategory: input.valueCategory } : {}),
970
+ ...(input.admissionState !== undefined ? { admissionState: input.admissionState } : {}),
971
+ ...(input.admissionReason !== undefined ? { admissionReason: sanitizeCredentials(input.admissionReason) } : {}),
972
+ ...(input.visibility !== undefined ? { visibility: input.visibility } : {}),
973
+ ...(input.sharedWithAgentIds !== undefined ? { sharedWithAgentIds: input.sharedWithAgentIds } : {}),
974
+ });
975
+
976
+ let updated = applyUpdate(existing);
977
+ let derivedJobsCommitted = false;
978
+ if (projectDir) {
979
+ const store = getObservationStore();
980
+ await store.atomic(async (tx) => {
981
+ const current = await tx.getById(existing.id);
982
+ if (!current || current.projectId !== existing.projectId) {
983
+ throw new Error('Topic observation changed before update');
984
+ }
985
+ updated = applyUpdate(current);
986
+ updated.writeGeneration = (await tx.getGeneration()) + 1;
987
+ await tx.update(updated);
988
+ derivedJobsCommitted = await enqueueObservationDerivedWork(tx, updated);
989
+ await input.onPersisted?.(updated);
990
+ });
991
+ updated.writeGeneration = store.getGeneration();
992
+ } else {
993
+ await input.onPersisted?.(updated);
994
+ }
995
+ if (corpusLoaded) {
996
+ const cacheIndex = observations.findIndex((observation) => observation.id === updated.id);
997
+ if (cacheIndex >= 0) observations[cacheIndex] = updated;
998
+ }
999
+
1000
+ // The durable update has committed; the index can now be repaired independently.
918
1001
  const doc: MemorixDocument = {
919
- id: makeOramaObservationId(existing.projectId, existing.id),
920
- observationId: existing.id,
921
- entityName: existing.entityName,
922
- type: existing.type,
923
- title: existing.title,
924
- narrative: existing.narrative,
925
- facts: existing.facts.join('\n'),
1002
+ id: makeOramaObservationId(updated.projectId, updated.id),
1003
+ observationId: updated.id,
1004
+ entityName: updated.entityName,
1005
+ type: updated.type,
1006
+ title: updated.title,
1007
+ narrative: updated.narrative,
1008
+ facts: updated.facts.join('\n'),
926
1009
  filesModified: enrichedFiles.join('\n'),
927
1010
  concepts: enrichedConcepts.map(c => c.replace(/-/g, ' ')).join(', '),
928
- attachments: formatAttachmentProvenance(existing.attachments),
1011
+ attachments: formatAttachmentProvenance(updated.attachments),
929
1012
  tokens,
930
- createdAt: existing.createdAt,
931
- projectId: existing.projectId,
1013
+ createdAt: updated.createdAt,
1014
+ projectId: updated.projectId,
932
1015
  accessCount: 0,
933
1016
  lastAccessedAt: '',
934
1017
  status: 'active',
935
- source: existing.source ?? 'agent',
936
- sourceDetail: existing.sourceDetail ?? '',
937
- valueCategory: existing.valueCategory ?? '',
938
- admissionState: existing.admissionState ?? '',
939
- admissionReason: existing.admissionReason ?? '',
940
- visibility: existing.visibility ?? 'project',
941
- createdByAgentId: existing.createdByAgentId ?? '',
942
- sharedWithAgentIds: JSON.stringify(existing.sharedWithAgentIds ?? []),
1018
+ source: updated.source ?? 'agent',
1019
+ sourceDetail: updated.sourceDetail ?? '',
1020
+ valueCategory: updated.valueCategory ?? '',
1021
+ admissionState: updated.admissionState ?? '',
1022
+ admissionReason: updated.admissionReason ?? '',
1023
+ visibility: updated.visibility ?? 'project',
1024
+ createdByAgentId: updated.createdByAgentId ?? '',
1025
+ sharedWithAgentIds: JSON.stringify(updated.sharedWithAgentIds ?? []),
943
1026
  };
944
1027
 
945
- // Remove old doc and insert updated one (with retry for concurrent upsert race)
946
- const oramaId = makeOramaObservationId(existing.projectId, existing.id);
947
- try {
948
- const { removeObservation } = await import('../store/orama-store.js');
949
- await removeObservation(oramaId);
950
- } catch { /* may not exist in index */ }
951
- try {
952
- await insertObservation(doc);
953
- } catch {
954
- // Concurrent upsert may have already re-inserted — retry remove+insert once
1028
+ if (corpusLoaded) {
1029
+ const oramaId = makeOramaObservationId(updated.projectId, updated.id);
955
1030
  try {
956
- const { removeObservation: removeObs } = await import('../store/orama-store.js');
957
- await removeObs(oramaId);
1031
+ try { await removeObservation(oramaId); } catch { /* index row may be absent */ }
958
1032
  await insertObservation(doc);
959
- } catch { /* best effort — file persistence is the source of truth */ }
960
- }
961
-
962
- // Persist via ObservationStore
963
- if (projectDir) {
964
- const store = getObservationStore();
965
- await store.update(existing);
1033
+ } catch {
1034
+ try {
1035
+ try { await removeObservation(oramaId); } catch { /* index row may be absent */ }
1036
+ await insertObservation(doc);
1037
+ } catch (error) {
1038
+ console.error(`[memorix] Observation index projection failed for obs-${updated.id}: ${sanitizeCredentials(error instanceof Error ? error.message : String(error))}`);
1039
+ }
1040
+ }
966
1041
  }
967
1042
 
968
- await bindObservationCodeRefsBestEffort(existing);
969
- await persistEvidenceCard(existing);
970
- queueObservationQualification(existing);
971
- if (resolveObservationVisibility(existing) === 'project') {
972
- queueClaimDerivation(existing);
1043
+ const codeRefsProjected = await bindObservationCodeRefsBestEffort(updated);
1044
+ const evidenceProjected = await persistEvidenceCard(updated);
1045
+ if (codeRefsProjected && evidenceProjected) await acknowledgeObservationProjection(updated);
1046
+ if (!derivedJobsCommitted) {
1047
+ queueObservationQualification(updated);
1048
+ if (resolveObservationVisibility(updated) === 'project') {
1049
+ queueClaimDerivation(updated);
1050
+ }
973
1051
  }
974
1052
 
975
1053
  scheduleObservationEmbedding({
976
- observationId: existing.id,
977
- projectId: existing.projectId,
1054
+ observationId: updated.id,
1055
+ projectId: updated.projectId,
978
1056
  searchableText: [input.title, input.narrative, ...(input.facts ?? [])].join(' '),
979
1057
  doc,
980
1058
  });
981
1059
 
982
- return existing;
1060
+ return updated;
983
1061
  }
984
1062
 
985
1063
  /**
@@ -1498,7 +1576,7 @@ export function getSearchIndexStatus(projectId?: string): {
1498
1576
  * so status checks do not mutate retention/access metadata.
1499
1577
  */
1500
1578
  export async function probeSearchIndex(projectId: string): Promise<string> {
1501
- await searchObservations({
1579
+ const result = await searchObservationsDetailed({
1502
1580
  query: 'semantic memory retrieval status',
1503
1581
  projectId,
1504
1582
  reader: { projectId },
@@ -1506,7 +1584,7 @@ export async function probeSearchIndex(projectId: string): Promise<string> {
1506
1584
  status: 'all',
1507
1585
  trackAccess: false,
1508
1586
  });
1509
- return getLastSearchMode(projectId);
1587
+ return result.diagnostics.mode;
1510
1588
  }
1511
1589
 
1512
1590
  /**
@@ -14,6 +14,7 @@ export const CONTROL_PLANE_MAINTENANCE_KINDS: readonly MaintenanceJobKind[] = [
14
14
  'consolidation',
15
15
  'codegraph-refresh',
16
16
  'observation-qualify',
17
+ 'observation-project',
17
18
  'claim-derive',
18
19
  'claim-requalification',
19
20
  'knowledge-compile',
@@ -16,6 +16,7 @@ export const ISOLATED_MAINTENANCE_JOB_KINDS: readonly MaintenanceJobKind[] = [
16
16
  'consolidation',
17
17
  'codegraph-refresh',
18
18
  'observation-qualify',
19
+ 'observation-project',
19
20
  'claim-derive',
20
21
  'claim-requalification',
21
22
  'knowledge-compile',
@@ -1,8 +1,11 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
 
3
+ import { assertMaintenanceProgress, type MaintenanceProgress, type MaintenanceResult } from '../core/maintenance-result.js';
3
4
  import { getDatabase } from '../store/sqlite-db.js';
4
5
  import { sanitizeCredentials } from '../memory/secret-filter.js';
5
6
 
7
+ export type { MaintenanceProgress } from '../core/maintenance-result.js';
8
+
6
9
  export const MAINTENANCE_JOB_KINDS = [
7
10
  'vector-backfill',
8
11
  'media-video-generation',
@@ -11,6 +14,7 @@ export const MAINTENANCE_JOB_KINDS = [
11
14
  'consolidation',
12
15
  'codegraph-refresh',
13
16
  'observation-qualify',
17
+ 'observation-project',
14
18
  'claim-derive',
15
19
  'claim-requalification',
16
20
  'knowledge-compile',
@@ -35,6 +39,7 @@ export interface MaintenanceJob {
35
39
  leaseOwner?: string;
36
40
  leaseExpiresAt?: number;
37
41
  lastError?: string;
42
+ progress?: MaintenanceProgress;
38
43
  createdAt: number;
39
44
  updatedAt: number;
40
45
  completedAt?: number;
@@ -68,20 +73,7 @@ export interface MaintenanceJobSummary {
68
73
  failed: number;
69
74
  }
70
75
 
71
- export type MaintenanceJobRunResult =
72
- | { action: 'complete' }
73
- | {
74
- action: 'reschedule';
75
- delayMs: number;
76
- resetAttempts?: boolean;
77
- payload?: Record<string, unknown>;
78
- /** Keep recoverable work out of the immediate pending queue during a cooldown. */
79
- status?: 'pending' | 'retry';
80
- /** Persist a sanitized diagnostic without consuming the job's retry budget. */
81
- lastError?: string;
82
- /** Clear a stale transient diagnostic after the job makes progress. */
83
- clearLastError?: boolean;
84
- };
76
+ export type MaintenanceJobRunResult = MaintenanceResult;
85
77
 
86
78
  export type MaintenanceJobHandler = (
87
79
  job: MaintenanceJob,
@@ -120,6 +112,14 @@ function rowToJob(row: any): MaintenanceJob {
120
112
  ...(row.lease_owner ? { leaseOwner: row.lease_owner } : {}),
121
113
  ...(row.lease_expires_at != null ? { leaseExpiresAt: Number(row.lease_expires_at) } : {}),
122
114
  ...(row.last_error ? { lastError: row.last_error } : {}),
115
+ ...(Number(row.progress_recorded ?? 0) === 1
116
+ ? { progress: {
117
+ attempted: Number(row.attempted ?? 0),
118
+ succeeded: Number(row.succeeded ?? 0),
119
+ failed: Number(row.failed ?? 0),
120
+ remaining: Number(row.remaining ?? 0),
121
+ } }
122
+ : {}),
123
123
  createdAt: Number(row.created_at),
124
124
  updatedAt: Number(row.updated_at),
125
125
  ...(row.completed_at != null ? { completedAt: Number(row.completed_at) } : {}),
@@ -181,6 +181,16 @@ export class MaintenanceJobStore {
181
181
  this.commit();
182
182
  return rowToJob(existing);
183
183
  }
184
+ if (existing.status === 'running') {
185
+ this.db.prepare(`
186
+ UPDATE maintenance_jobs
187
+ SET rerun_requested = 1, payload_json = ?, updated_at = ?
188
+ WHERE id = ?
189
+ `).run(payloadJson, now, existing.id);
190
+ const updated = this.getRow(existing.id)!;
191
+ this.commit();
192
+ return rowToJob(updated);
193
+ }
184
194
  const nextRunAfter = Math.min(Number(existing.run_after), runAfter);
185
195
  this.db.prepare(`
186
196
  UPDATE maintenance_jobs
@@ -327,8 +337,10 @@ export class MaintenanceJobStore {
327
337
  this.db.prepare(`
328
338
  UPDATE maintenance_jobs
329
339
  SET
330
- status = CASE WHEN attempts >= max_attempts THEN 'failed' ELSE 'retry' END,
331
- run_after = CASE WHEN attempts >= max_attempts THEN run_after ELSE ? END,
340
+ status = CASE WHEN attempts >= max_attempts AND rerun_requested = 0 THEN 'failed' ELSE 'retry' END,
341
+ run_after = CASE WHEN attempts >= max_attempts AND rerun_requested = 0 THEN run_after ELSE ? END,
342
+ attempts = CASE WHEN rerun_requested = 1 AND attempts >= max_attempts THEN 0 ELSE attempts END,
343
+ rerun_requested = 0,
332
344
  lease_owner = NULL,
333
345
  lease_expires_at = NULL,
334
346
  last_error = COALESCE(last_error, 'worker lease expired'),
@@ -398,14 +410,55 @@ export class MaintenanceJobStore {
398
410
  return Number(result.changes) > 0;
399
411
  }
400
412
 
401
- complete(id: string, workerId: string, now = Date.now()): MaintenanceJob | undefined {
402
- this.db.prepare(`
403
- UPDATE maintenance_jobs
404
- SET status = 'completed', lease_owner = NULL, lease_expires_at = NULL,
405
- completed_at = ?, updated_at = ?
406
- WHERE id = ? AND status = 'running' AND lease_owner = ?
407
- `).run(now, now, id, workerId);
408
- return this.get(id);
413
+ complete(id: string, workerId: string, now = Date.now(), progress?: MaintenanceProgress): MaintenanceJob | undefined {
414
+ assertMaintenanceProgress(progress);
415
+ this.begin();
416
+ try {
417
+ const current = this.db.prepare(`
418
+ SELECT rerun_requested FROM maintenance_jobs
419
+ WHERE id = ? AND status = 'running' AND lease_owner = ?
420
+ `).get(id, workerId);
421
+ if (!current) {
422
+ this.commit();
423
+ return undefined;
424
+ }
425
+ if (Number(current.rerun_requested) === 1) {
426
+ this.db.prepare(`
427
+ UPDATE maintenance_jobs
428
+ SET status = 'pending', attempts = 0, run_after = ?,
429
+ rerun_requested = 0, lease_owner = NULL, lease_expires_at = NULL,
430
+ attempted = 0, succeeded = 0, failed = 0, remaining = 0,
431
+ progress_recorded = 0, last_error = NULL, completed_at = NULL,
432
+ updated_at = ?
433
+ WHERE id = ?
434
+ `).run(now, now, id);
435
+ } else {
436
+ this.db.prepare(`
437
+ UPDATE maintenance_jobs
438
+ SET status = 'completed', lease_owner = NULL, lease_expires_at = NULL,
439
+ attempted = COALESCE(?, attempted), succeeded = COALESCE(?, succeeded),
440
+ failed = COALESCE(?, failed), remaining = COALESCE(?, remaining),
441
+ progress_recorded = CASE WHEN ? THEN 1 ELSE progress_recorded END,
442
+ completed_at = ?, updated_at = ?
443
+ WHERE id = ?
444
+ `).run(
445
+ progress?.attempted ?? null,
446
+ progress?.succeeded ?? null,
447
+ progress?.failed ?? null,
448
+ progress?.remaining ?? null,
449
+ progress ? 1 : 0,
450
+ now,
451
+ now,
452
+ id,
453
+ );
454
+ }
455
+ const updated = this.get(id);
456
+ this.commit();
457
+ return updated;
458
+ } catch (error) {
459
+ this.rollback();
460
+ throw error;
461
+ }
409
462
  }
410
463
 
411
464
  reschedule(
@@ -418,6 +471,7 @@ export class MaintenanceJobStore {
418
471
  status?: 'pending' | 'retry';
419
472
  lastError?: string;
420
473
  clearLastError?: boolean;
474
+ progress?: MaintenanceProgress;
421
475
  now?: number;
422
476
  },
423
477
  ): MaintenanceJob | undefined {
@@ -427,22 +481,37 @@ export class MaintenanceJobStore {
427
481
  const status = options.status === 'retry' ? 'retry' : 'pending';
428
482
  const hasLastError = options.lastError !== undefined;
429
483
  const lastError = hasLastError ? errorText(options.lastError) : null;
484
+ const progress = options.progress;
485
+ assertMaintenanceProgress(progress);
430
486
  this.db.prepare(`
431
487
  UPDATE maintenance_jobs
432
- SET status = ?, run_after = ?, attempts = CASE WHEN ? THEN 0 ELSE attempts END,
433
- payload_json = COALESCE(?, payload_json),
488
+ SET status = ?,
489
+ run_after = CASE WHEN rerun_requested = 1 AND ? = 0 THEN ? ELSE ? END,
490
+ attempts = CASE WHEN rerun_requested = 1 AND ? = 0 THEN 0 WHEN ? THEN 0 ELSE attempts END,
491
+ payload_json = CASE WHEN rerun_requested = 1 THEN payload_json ELSE COALESCE(?, payload_json) END,
492
+ attempted = COALESCE(?, attempted), succeeded = COALESCE(?, succeeded),
493
+ failed = COALESCE(?, failed), remaining = COALESCE(?, remaining),
494
+ progress_recorded = CASE WHEN ? THEN 1 ELSE progress_recorded END,
434
495
  last_error = CASE
435
496
  WHEN ? THEN NULL
436
497
  WHEN ? THEN ?
437
498
  ELSE last_error
438
499
  END,
439
- lease_owner = NULL, lease_expires_at = NULL, updated_at = ?
500
+ rerun_requested = 0, lease_owner = NULL, lease_expires_at = NULL, updated_at = ?
440
501
  WHERE id = ? AND status = 'running' AND lease_owner = ?
441
502
  `).run(
442
503
  status,
504
+ status === 'retry' ? 1 : 0,
505
+ now,
443
506
  now + delayMs,
507
+ status === 'retry' ? 1 : 0,
444
508
  options.resetAttempts ? 1 : 0,
445
509
  payloadJson,
510
+ progress?.attempted ?? null,
511
+ progress?.succeeded ?? null,
512
+ progress?.failed ?? null,
513
+ progress?.remaining ?? null,
514
+ progress ? 1 : 0,
446
515
  options.clearLastError ? 1 : 0,
447
516
  hasLastError ? 1 : 0,
448
517
  lastError,
@@ -462,6 +531,21 @@ export class MaintenanceJobStore {
462
531
  return Number(result.changes ?? 0);
463
532
  }
464
533
 
534
+ /** A successful foreground projection can acknowledge its pending outbox row. */
535
+ acknowledgePending(
536
+ projectId: string,
537
+ kind: MaintenanceJobKind,
538
+ dedupeKey: string,
539
+ now = Date.now(),
540
+ ): number {
541
+ const result = this.db.prepare(`
542
+ UPDATE maintenance_jobs
543
+ SET status = 'completed', completed_at = ?, updated_at = ?
544
+ WHERE project_id = ? AND kind = ? AND dedupe_key = ? AND status = 'pending'
545
+ `).run(now, now, projectId, kind, dedupeKey);
546
+ return Number(result.changes ?? 0);
547
+ }
548
+
465
549
  fail(id: string, workerId: string, error: unknown, now = Date.now()): MaintenanceJob | undefined {
466
550
  this.begin();
467
551
  try {
@@ -475,15 +559,18 @@ export class MaintenanceJobStore {
475
559
  }
476
560
 
477
561
  const attempts = Number(current.attempts);
478
- const exhausted = attempts >= Number(current.max_attempts);
562
+ const rerunRequested = Number(current.rerun_requested) === 1;
563
+ const exhausted = attempts >= Number(current.max_attempts) && !rerunRequested;
479
564
  const status: MaintenanceJobStatus = exhausted ? 'failed' : 'retry';
480
565
  const runAfter = exhausted ? Number(current.run_after) : now + getMaintenanceRetryDelayMs(attempts);
566
+ const nextAttempts = rerunRequested && attempts >= Number(current.max_attempts) ? 0 : attempts;
481
567
  this.db.prepare(`
482
568
  UPDATE maintenance_jobs
483
- SET status = ?, run_after = ?, lease_owner = NULL, lease_expires_at = NULL,
569
+ SET status = ?, run_after = ?, attempts = ?, rerun_requested = 0,
570
+ lease_owner = NULL, lease_expires_at = NULL,
484
571
  last_error = ?, updated_at = ?
485
572
  WHERE id = ?
486
- `).run(status, runAfter, errorText(error), now, id);
573
+ `).run(status, runAfter, nextAttempts, errorText(error), now, id);
487
574
  const updated = this.getRow(id)!;
488
575
  this.commit();
489
576
  return rowToJob(updated);
@@ -575,12 +662,16 @@ export class MaintenanceJobWorker {
575
662
  status: result.status,
576
663
  lastError: result.lastError,
577
664
  clearLastError: result.clearLastError,
665
+ progress: result.progress,
578
666
  now,
579
667
  });
580
668
  return { state: 'rescheduled', job: updated };
581
669
  }
582
- const updated = this.store.complete(job.id, this.workerId, now);
583
- return { state: 'completed', job: updated };
670
+ if (result?.progress && result.progress.remaining > 0) {
671
+ throw new Error('maintenance job reported completion with remaining work');
672
+ }
673
+ const updated = this.store.complete(job.id, this.workerId, now, result?.progress);
674
+ return { state: updated?.status === 'pending' ? 'rescheduled' : 'completed', job: updated };
584
675
  } catch (error) {
585
676
  const updated = this.store.fail(job.id, this.workerId, error, now);
586
677
  return { state: 'failed', job: updated };