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.
- package/CHANGELOG.md +62 -1
- package/dist/cli/index.js +1886 -1273
- package/dist/index.js +1724 -1088
- package/dist/{maintenance-jobs-DVRF-46r.d.ts → maintenance-jobs-DweoCoTT.d.ts} +25 -15
- package/dist/maintenance-runner.d.ts +1 -1
- package/dist/maintenance-runner.js +694 -172
- package/dist/media-audio-runner.js +685 -164
- package/dist/media-video-runner.js +693 -172
- package/dist/memcode-runtime/CHANGELOG.md +44 -1
- package/dist/sdk.js +13952 -13345
- package/dist/vector-backfill-runner.d.ts +1 -1
- package/dist/vector-backfill-runner.js +693 -172
- package/docs/ARCHITECTURE.md +219 -0
- package/docs/CONFIGURATION.md +15 -0
- package/docs/DESIGN_DECISIONS.md +37 -0
- package/docs/DEVELOPMENT.md +1 -1
- package/docs/MODULES.md +7 -1
- package/docs/PERFORMANCE.md +14 -0
- package/docs/README.md +1 -1
- package/docs/ROADMAP-1.9.12-2.0.md +18 -2
- package/package.json +1 -1
- package/plugins/antigravity/memorix/plugin.json +1 -1
- package/plugins/claude/memorix/.claude-plugin/plugin.json +1 -1
- package/plugins/codebuddy/memorix/.codebuddy-plugin/plugin.json +1 -1
- package/plugins/codex/memorix/.codex-plugin/plugin.json +1 -1
- package/plugins/copilot/memorix/plugin.json +1 -1
- package/plugins/gemini/memorix/gemini-extension.json +1 -1
- package/plugins/hermes/memorix/plugin.yaml +1 -1
- package/plugins/omp/memorix/package.json +1 -1
- package/plugins/openclaw/memorix/.codex-plugin/plugin.json +1 -1
- package/plugins/pi/memorix/package.json +1 -1
- package/server.json +2 -2
- package/src/cli/tui/chat-service.ts +6 -9
- package/src/cli/tui/data.ts +2 -2
- package/src/codegraph/auto-context.ts +9 -2
- package/src/codegraph/derived-view.ts +63 -0
- package/src/compact/engine.ts +10 -33
- package/src/config/resolved-config.ts +11 -0
- package/src/config/retrieval-strategy.ts +22 -0
- package/src/config/toml-loader.ts +5 -0
- package/src/config/yaml-loader.ts +7 -0
- package/src/core/derived-view.ts +15 -0
- package/src/core/maintenance-result.ts +33 -0
- package/src/core/retrieval-contracts.ts +57 -0
- package/src/core/retrieval-facade.ts +18 -0
- package/src/core/retrieval-policy.ts +44 -0
- package/src/core/runtime-context.ts +42 -0
- package/src/embedding/api-provider.ts +18 -8
- package/src/knowledge/workset.ts +0 -2
- package/src/memory/consolidation.ts +3 -2
- package/src/memory/feedback-model.ts +1 -4
- package/src/memory/observations.ts +165 -87
- package/src/runtime/control-plane-maintenance.ts +1 -0
- package/src/runtime/isolated-maintenance.ts +1 -0
- package/src/runtime/maintenance-jobs.ts +123 -32
- package/src/runtime/project-maintenance.ts +69 -1
- package/src/sdk.ts +3 -2
- package/src/search/fts-view.ts +53 -0
- package/src/search/orama-view.ts +40 -0
- package/src/search/retrieval-facade.ts +38 -0
- package/src/search/semantic-index.ts +13 -0
- package/src/search/semantic-view.ts +34 -0
- package/src/server.ts +19 -7
- package/src/store/obs-store.ts +15 -0
- package/src/store/orama-store.ts +116 -42
- package/src/store/sqlite-db.ts +22 -0
- package/src/store/sqlite-store.ts +27 -0
|
@@ -36,10 +36,10 @@ import {
|
|
|
36
36
|
isEmbeddingEnabled,
|
|
37
37
|
makeOramaObservationId,
|
|
38
38
|
getLastSearchMode,
|
|
39
|
-
|
|
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<
|
|
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<
|
|
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
|
-
|
|
834
|
-
if (
|
|
835
|
-
|
|
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
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
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(
|
|
920
|
-
observationId:
|
|
921
|
-
entityName:
|
|
922
|
-
type:
|
|
923
|
-
title:
|
|
924
|
-
narrative:
|
|
925
|
-
facts:
|
|
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(
|
|
1011
|
+
attachments: formatAttachmentProvenance(updated.attachments),
|
|
929
1012
|
tokens,
|
|
930
|
-
createdAt:
|
|
931
|
-
projectId:
|
|
1013
|
+
createdAt: updated.createdAt,
|
|
1014
|
+
projectId: updated.projectId,
|
|
932
1015
|
accessCount: 0,
|
|
933
1016
|
lastAccessedAt: '',
|
|
934
1017
|
status: 'active',
|
|
935
|
-
source:
|
|
936
|
-
sourceDetail:
|
|
937
|
-
valueCategory:
|
|
938
|
-
admissionState:
|
|
939
|
-
admissionReason:
|
|
940
|
-
visibility:
|
|
941
|
-
createdByAgentId:
|
|
942
|
-
sharedWithAgentIds: JSON.stringify(
|
|
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
|
-
|
|
946
|
-
|
|
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
|
-
|
|
957
|
-
await removeObs(oramaId);
|
|
1031
|
+
try { await removeObservation(oramaId); } catch { /* index row may be absent */ }
|
|
958
1032
|
await insertObservation(doc);
|
|
959
|
-
} catch {
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
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(
|
|
969
|
-
await persistEvidenceCard(
|
|
970
|
-
|
|
971
|
-
if (
|
|
972
|
-
|
|
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:
|
|
977
|
-
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
|
|
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
|
|
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
|
|
1587
|
+
return result.diagnostics.mode;
|
|
1510
1588
|
}
|
|
1511
1589
|
|
|
1512
1590
|
/**
|
|
@@ -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
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
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 = ?,
|
|
433
|
-
|
|
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
|
|
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 = ?,
|
|
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
|
-
|
|
583
|
-
|
|
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 };
|