@iworkforces/tracelattice 2.3.6 → 2.4.0
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/README.md +18 -5
- package/dist/ServerConfig.d.ts +16 -0
- package/dist/ServerConfig.d.ts.map +1 -1
- package/dist/ServerConfig.js +11 -0
- package/dist/ServerConfig.js.map +1 -1
- package/dist/cli.js +234 -18
- package/dist/cli.js.map +1 -1
- package/dist/config/ConfigLoader.d.ts +2 -0
- package/dist/config/ConfigLoader.d.ts.map +1 -1
- package/dist/config/ConfigLoader.js +2 -0
- package/dist/config/ConfigLoader.js.map +1 -1
- package/dist/contracts/PersistenceBackend.d.ts +26 -0
- package/dist/contracts/PersistenceBackend.d.ts.map +1 -1
- package/dist/contracts/persistence-backlog.d.ts +21 -0
- package/dist/contracts/persistence-backlog.d.ts.map +1 -0
- package/dist/contracts/persistence-backlog.js +1 -0
- package/dist/core/HistoryManager.d.ts +15 -1
- package/dist/core/HistoryManager.d.ts.map +1 -1
- package/dist/core/HistoryManager.js +12 -2
- package/dist/core/HistoryManager.js.map +1 -1
- package/dist/core/IHistoryManager.d.ts +2 -0
- package/dist/core/IHistoryManager.d.ts.map +1 -1
- package/dist/core/PersistenceBuffer.d.ts +25 -0
- package/dist/core/PersistenceBuffer.d.ts.map +1 -1
- package/dist/core/PersistenceBuffer.js +27 -5
- package/dist/core/PersistenceBuffer.js.map +1 -1
- package/dist/core/PersistenceBufferErrors.d.ts +10 -0
- package/dist/core/PersistenceBufferErrors.d.ts.map +1 -1
- package/dist/core/PersistenceBufferErrors.js +13 -1
- package/dist/core/PersistenceBufferErrors.js.map +1 -1
- package/dist/core/PersistenceRestore.d.ts.map +1 -1
- package/dist/core/PersistenceRestore.js +25 -30
- package/dist/core/PersistenceRestore.js.map +1 -1
- package/dist/core/PersistenceWorkQueue.d.ts +9 -0
- package/dist/core/PersistenceWorkQueue.d.ts.map +1 -1
- package/dist/core/PersistenceWorkQueue.js +18 -0
- package/dist/core/PersistenceWorkQueue.js.map +1 -1
- package/dist/core/ThoughtEvaluator.d.ts +6 -0
- package/dist/core/ThoughtEvaluator.d.ts.map +1 -1
- package/dist/core/ThoughtEvaluator.js +15 -1
- package/dist/core/ThoughtEvaluator.js.map +1 -1
- package/dist/core/ThoughtProcessor.d.ts.map +1 -1
- package/dist/core/ThoughtProcessor.js +3 -10
- package/dist/core/ThoughtProcessor.js.map +1 -1
- package/dist/core/evaluator/VerificationLinks.d.ts +5 -0
- package/dist/core/evaluator/VerificationLinks.d.ts.map +1 -1
- package/dist/core/evaluator/VerificationLinks.js +47 -53
- package/dist/core/evaluator/VerificationLinks.js.map +1 -1
- package/dist/core/reasoning/ActiveEvidenceProjection.d.ts.map +1 -1
- package/dist/core/reasoning/ActiveEvidenceProjection.js +4 -3
- package/dist/core/reasoning/ActiveEvidenceProjection.js.map +1 -1
- package/dist/errors.d.ts +1 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +2 -1
- package/dist/errors.js.map +1 -1
- package/dist/health/HealthChecker.d.ts +42 -1
- package/dist/health/HealthChecker.d.ts.map +1 -1
- package/dist/health/HealthChecker.js +60 -8
- package/dist/health/HealthChecker.js.map +1 -1
- package/dist/lib.d.ts +2 -2
- package/dist/lib.d.ts.map +1 -1
- package/dist/lib.js +1 -0
- package/dist/lib.js.map +1 -1
- package/dist/metrics/metrics.impl.js.map +1 -1
- package/dist/persistence/FilePersistence.d.ts +2 -1
- package/dist/persistence/FilePersistence.d.ts.map +1 -1
- package/dist/persistence/FilePersistence.js +6 -1
- package/dist/persistence/FilePersistence.js.map +1 -1
- package/dist/persistence/FileSnapshotV2.d.ts +2 -0
- package/dist/persistence/FileSnapshotV2.d.ts.map +1 -1
- package/dist/persistence/FileSnapshotV2.js +39 -1
- package/dist/persistence/FileSnapshotV2.js.map +1 -1
- package/dist/persistence/MemoryPersistence.d.ts +4 -1
- package/dist/persistence/MemoryPersistence.d.ts.map +1 -1
- package/dist/persistence/MemoryPersistence.js +30 -0
- package/dist/persistence/MemoryPersistence.js.map +1 -1
- package/dist/persistence/SqlitePersistence.d.ts +6 -1
- package/dist/persistence/SqlitePersistence.d.ts.map +1 -1
- package/dist/persistence/SqlitePersistence.js +31 -4
- package/dist/persistence/SqlitePersistence.js.map +1 -1
- package/dist/transport/StreamableHttpTransport.d.ts +12 -0
- package/dist/transport/StreamableHttpTransport.d.ts.map +1 -1
- package/dist/transport/StreamableHttpTransport.js +19 -5
- package/dist/transport/StreamableHttpTransport.js.map +1 -1
- package/package.json +11 -11
|
@@ -4,18 +4,19 @@ function resolvedVerificationTarget(thought, references) {
|
|
|
4
4
|
function resolveVerificationLinks(history, branches, admissionTargets = new Map()) {
|
|
5
5
|
const thoughts = collectActiveThoughts(history, branches);
|
|
6
6
|
const hypotheses = thoughts.filter((thought)=>'hypothesis' === thought.thought_type && Boolean(thought.id));
|
|
7
|
-
const
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
7
|
+
const hypothesesById = new Map();
|
|
8
|
+
for (const hypothesis of hypotheses){
|
|
9
|
+
const id = hypothesis.id;
|
|
10
|
+
if (id && !hypothesesById.has(id)) hypothesesById.set(id, hypothesis);
|
|
11
|
+
}
|
|
12
|
+
const hypothesisIds = new Set(hypothesesById.keys());
|
|
13
13
|
const targetsByVerifier = new Map();
|
|
14
14
|
const targetsByVerifierId = new Map();
|
|
15
15
|
const legacyTargets = uniqueLegacyTargets(hypotheses);
|
|
16
16
|
for (const verifier of thoughts){
|
|
17
17
|
if ('verification' !== verifier.thought_type) continue;
|
|
18
|
-
const
|
|
18
|
+
const targetId = verifier.id ? admissionTargets.get(verifier.id) : void 0;
|
|
19
|
+
const target = void 0 !== verifier.verification_target ? void 0 === targetId ? void 0 : hypothesesById.get(targetId) : verifier.id && void 0 !== verifier.hypothesis_id ? legacyTargets.get(verifier.hypothesis_id) : void 0;
|
|
19
20
|
if (void 0 !== target) {
|
|
20
21
|
targetsByVerifier.set(verifier, target);
|
|
21
22
|
if (verifier.id && target.id) targetsByVerifierId.set(verifier.id, target.id);
|
|
@@ -39,48 +40,50 @@ function resolveVerificationLinks(history, branches, admissionTargets = new Map(
|
|
|
39
40
|
});
|
|
40
41
|
}
|
|
41
42
|
function collectActiveMainThoughts(history, branches) {
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
43
|
+
const { thoughts, mainCount } = collectActiveEvidence(history, branches);
|
|
44
|
+
return thoughts.slice(0, mainCount);
|
|
45
|
+
}
|
|
46
|
+
function collectActiveThoughts(history, branches) {
|
|
47
|
+
return collectActiveEvidence(history, branches).thoughts;
|
|
48
|
+
}
|
|
49
|
+
function collectActiveEvidence(history, branches) {
|
|
50
|
+
const retained = new Map();
|
|
51
|
+
const retractedIds = new Set();
|
|
52
|
+
const lists = [
|
|
53
|
+
history,
|
|
54
|
+
...Object.values(branches)
|
|
46
55
|
];
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
active.push(thought);
|
|
56
|
+
for (const [index, list] of lists.entries())for (const thought of list){
|
|
57
|
+
const id = thought.id;
|
|
58
|
+
if (true === thought.retracted) {
|
|
59
|
+
if (id) {
|
|
60
|
+
retractedIds.add(id);
|
|
61
|
+
retained.delete(id);
|
|
62
|
+
}
|
|
55
63
|
continue;
|
|
56
64
|
}
|
|
57
|
-
if (!
|
|
58
|
-
|
|
59
|
-
|
|
65
|
+
if (!id) {
|
|
66
|
+
if (0 === index) retained.set(Symbol(), {
|
|
67
|
+
thought,
|
|
68
|
+
main: true
|
|
69
|
+
});
|
|
70
|
+
continue;
|
|
60
71
|
}
|
|
72
|
+
if (!(retractedIds.has(id) || retained.has(id))) retained.set(id, {
|
|
73
|
+
thought,
|
|
74
|
+
main: 0 === index
|
|
75
|
+
});
|
|
61
76
|
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
...history,
|
|
68
|
-
...branchThoughts
|
|
69
|
-
];
|
|
70
|
-
const retractedIds = new Set(allThoughts.flatMap((thought)=>true === thought.retracted && thought.id ? [
|
|
71
|
-
thought.id
|
|
72
|
-
] : []));
|
|
73
|
-
const active = collectActiveMainThoughts(history, branches);
|
|
74
|
-
const includedIds = new Set(active.flatMap((thought)=>thought.id ? [
|
|
75
|
-
thought.id
|
|
76
|
-
] : []));
|
|
77
|
-
for (const thought of branchThoughts)if (thought.id && true !== thought.retracted) {
|
|
78
|
-
if (!(retractedIds.has(thought.id) || includedIds.has(thought.id))) {
|
|
79
|
-
includedIds.add(thought.id);
|
|
80
|
-
active.push(thought);
|
|
81
|
-
}
|
|
77
|
+
const thoughts = [];
|
|
78
|
+
let mainCount = 0;
|
|
79
|
+
for (const entry of retained.values()){
|
|
80
|
+
thoughts.push(entry.thought);
|
|
81
|
+
if (entry.main) mainCount++;
|
|
82
82
|
}
|
|
83
|
-
return
|
|
83
|
+
return {
|
|
84
|
+
thoughts,
|
|
85
|
+
mainCount
|
|
86
|
+
};
|
|
84
87
|
}
|
|
85
88
|
function uniqueLegacyTargets(hypotheses) {
|
|
86
89
|
const candidates = new Map();
|
|
@@ -99,15 +102,6 @@ function uniqueLegacyTargets(hypotheses) {
|
|
|
99
102
|
]
|
|
100
103
|
]));
|
|
101
104
|
}
|
|
102
|
-
|
|
103
|
-
if (void 0 !== verifier.verification_target) {
|
|
104
|
-
if (!verifier.id) return;
|
|
105
|
-
const targetId = admissionTargets.get(verifier.id);
|
|
106
|
-
if (void 0 === targetId || !activeThoughtIds.has(targetId)) return;
|
|
107
|
-
return hypotheses.find((hypothesis)=>hypothesis.id === targetId);
|
|
108
|
-
}
|
|
109
|
-
return verifier.id && void 0 !== verifier.hypothesis_id ? legacyTargets.get(verifier.hypothesis_id) : void 0;
|
|
110
|
-
}
|
|
111
|
-
export { collectActiveMainThoughts, collectActiveThoughts, resolveVerificationLinks, resolvedVerificationTarget };
|
|
105
|
+
export { collectActiveEvidence, collectActiveMainThoughts, collectActiveThoughts, resolveVerificationLinks, resolvedVerificationTarget };
|
|
112
106
|
|
|
113
107
|
//# sourceMappingURL=VerificationLinks.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core/evaluator/VerificationLinks.js","sources":["../../../src/core/evaluator/VerificationLinks.ts"],"sourcesContent":["import type { ThoughtId } from '../../contracts/ids.js';\nimport type { ResolvedThoughtReferences } from '../IHistoryManager.js';\nimport type { ThoughtData } from '../thought.js';\n\nexport type ActiveThoughtBranches = Readonly<Record<string, readonly ThoughtData[]>>;\n\nexport interface VerificationLinks {\n\treadonly thoughts: readonly ThoughtData[];\n\treadonly hypotheses: readonly ThoughtData[];\n\treadonly hypothesisIds: ReadonlySet<ThoughtId>;\n\treadonly verifiedHypothesisIds: ReadonlySet<ThoughtId>;\n\treadonly verifiedHypothesisCount: number;\n\ttargetFor(verifierId: ThoughtId): ThoughtId | undefined;\n\tisVerified(hypothesis: ThoughtData): boolean;\n\tverifies(verifier: ThoughtData, hypothesis: ThoughtData): boolean;\n}\n\nexport function resolvedVerificationTarget(\n\tthought: ThoughtData,\n\treferences: ResolvedThoughtReferences\n): ThoughtId | undefined {\n\treturn thought.thought_type === 'verification'\n\t\t? references.verificationTargetThoughtId\n\t\t: undefined;\n}\n\nexport function resolveVerificationLinks(\n\thistory: readonly ThoughtData[],\n\tbranches: ActiveThoughtBranches,\n\tadmissionTargets: ReadonlyMap<ThoughtId, ThoughtId> = new Map()\n): VerificationLinks {\n\tconst thoughts = collectActiveThoughts(history, branches);\n\tconst hypotheses = thoughts.filter(\n\t\t(thought) => thought.thought_type === 'hypothesis' && Boolean(thought.id)\n\t);\n\tconst hypothesisIds = new Set(hypotheses.flatMap((thought) => (thought.id ? [thought.id] : [])));\n\tconst activeThoughtIds = new Set(thoughts.flatMap((thought) => (thought.id ? [thought.id] : [])));\n\tconst targetsByVerifier = new Map<ThoughtData, ThoughtData>();\n\tconst targetsByVerifierId = new Map<ThoughtId, ThoughtId>();\n\tconst legacyTargets = uniqueLegacyTargets(hypotheses);\n\n\tfor (const verifier of thoughts) {\n\t\tif (verifier.thought_type !== 'verification') continue;\n\t\tconst target = resolveTarget(\n\t\t\tverifier,\n\t\t\thypotheses,\n\t\t\tadmissionTargets,\n\t\t\tactiveThoughtIds,\n\t\t\tlegacyTargets\n\t\t);\n\t\tif (target === undefined) continue;\n\t\ttargetsByVerifier.set(verifier, target);\n\t\tif (verifier.id && target.id) {\n\t\t\ttargetsByVerifierId.set(verifier.id, target.id);\n\t\t}\n\t}\n\n\tconst verifiedHypotheses = new Set(targetsByVerifier.values());\n\tconst verifiedHypothesisIds = new Set(\n\t\t[...verifiedHypotheses].flatMap((thought) => (thought.id ? [thought.id] : []))\n\t);\n\treturn Object.freeze({\n\t\tthoughts: Object.freeze(thoughts),\n\t\thypotheses: Object.freeze(hypotheses),\n\t\thypothesisIds: new Set(hypothesisIds),\n\t\tverifiedHypothesisIds: new Set(verifiedHypothesisIds),\n\t\tverifiedHypothesisCount: verifiedHypotheses.size,\n\t\ttargetFor: (verifierId: ThoughtId) => targetsByVerifierId.get(verifierId),\n\t\tisVerified: (hypothesis: ThoughtData) => verifiedHypotheses.has(hypothesis),\n\t\tverifies: (verifier: ThoughtData, hypothesis: ThoughtData) =>\n\t\t\ttargetsByVerifier.get(verifier) === hypothesis,\n\t});\n}\n\nexport function collectActiveMainThoughts(\n\thistory: readonly ThoughtData[],\n\tbranches: ActiveThoughtBranches\n): ThoughtData[] {\n\tconst branchThoughts = Object.values(branches).flat();\n\tconst allThoughts = [...history, ...branchThoughts];\n\tconst retractedIds = new Set(\n\t\tallThoughts.flatMap((thought) => (thought.retracted === true && thought.id ? [thought.id] : []))\n\t);\n\tconst includedIds = new Set<ThoughtId>();\n\tconst active: ThoughtData[] = [];\n\tfor (const thought of history) {\n\t\tif (thought.retracted === true) continue;\n\t\tif (!thought.id) {\n\t\t\tactive.push(thought);\n\t\t\tcontinue;\n\t\t}\n\t\tif (retractedIds.has(thought.id) || includedIds.has(thought.id)) continue;\n\t\tincludedIds.add(thought.id);\n\t\tactive.push(thought);\n\t}\n\treturn active;\n}\n\nexport function collectActiveThoughts(\n\thistory: readonly ThoughtData[],\n\tbranches: ActiveThoughtBranches\n): ThoughtData[] {\n\tconst branchThoughts = Object.values(branches).flat();\n\tconst allThoughts = [...history, ...branchThoughts];\n\tconst retractedIds = new Set(\n\t\tallThoughts.flatMap((thought) => (thought.retracted === true && thought.id ? [thought.id] : []))\n\t);\n\tconst active = collectActiveMainThoughts(history, branches);\n\tconst includedIds = new Set(active.flatMap((thought) => (thought.id ? [thought.id] : [])));\n\tfor (const thought of branchThoughts) {\n\t\tif (!thought.id || thought.retracted === true) continue;\n\t\tif (retractedIds.has(thought.id) || includedIds.has(thought.id)) continue;\n\t\tincludedIds.add(thought.id);\n\t\tactive.push(thought);\n\t}\n\treturn active;\n}\n\nfunction uniqueLegacyTargets(hypotheses: readonly ThoughtData[]): ReadonlyMap<string, ThoughtData> {\n\tconst candidates = new Map<string, ThoughtData | undefined>();\n\tfor (const hypothesis of hypotheses) {\n\t\tconst label = hypothesis.hypothesis_id;\n\t\tif (label === undefined) continue;\n\t\tconst existing = candidates.get(label);\n\t\tcandidates.set(\n\t\t\tlabel,\n\t\t\texisting === undefined && !candidates.has(label) ? hypothesis : undefined\n\t\t);\n\t}\n\treturn new Map(\n\t\t[...candidates].flatMap(([label, target]) =>\n\t\t\ttarget === undefined ? [] : ([[label, target]] as const)\n\t\t)\n\t);\n}\n\nfunction resolveTarget(\n\tverifier: ThoughtData,\n\thypotheses: readonly ThoughtData[],\n\tadmissionTargets: ReadonlyMap<ThoughtId, ThoughtId>,\n\tactiveThoughtIds: ReadonlySet<ThoughtId>,\n\tlegacyTargets: ReadonlyMap<string, ThoughtData>\n): ThoughtData | undefined {\n\tif (verifier.verification_target !== undefined) {\n\t\tif (!verifier.id) return undefined;\n\t\tconst targetId = admissionTargets.get(verifier.id);\n\t\tif (targetId === undefined || !activeThoughtIds.has(targetId)) return undefined;\n\t\treturn hypotheses.find((hypothesis) => hypothesis.id === targetId);\n\t}\n\treturn !verifier.id || verifier.hypothesis_id === undefined\n\t\t? undefined\n\t\t: legacyTargets.get(verifier.hypothesis_id);\n}\n"],"names":["resolvedVerificationTarget","thought","references","undefined","resolveVerificationLinks","history","branches","admissionTargets","Map","thoughts","collectActiveThoughts","hypotheses","Boolean","hypothesisIds","Set","activeThoughtIds","targetsByVerifier","targetsByVerifierId","legacyTargets","uniqueLegacyTargets","verifier","target","resolveTarget","verifiedHypotheses","verifiedHypothesisIds","Object","verifierId","hypothesis","collectActiveMainThoughts","branchThoughts","allThoughts","retractedIds","includedIds","active","candidates","label","existing","targetId"],"mappings":"AAiBO,SAASA,2BACfC,OAAoB,EACpBC,UAAqC;IAErC,OAAOD,AAAyB,mBAAzBA,QAAQ,YAAY,GACxBC,WAAW,2BAA2B,GACtCC;AACJ;AAEO,SAASC,yBACfC,OAA+B,EAC/BC,QAA+B,EAC/BC,mBAAsD,IAAIC,KAAK;IAE/D,MAAMC,WAAWC,sBAAsBL,SAASC;IAChD,MAAMK,aAAaF,SAAS,MAAM,CACjC,CAACR,UAAYA,AAAyB,iBAAzBA,QAAQ,YAAY,IAAqBW,QAAQX,QAAQ,EAAE;IAEzE,MAAMY,gBAAgB,IAAIC,IAAIH,WAAW,OAAO,CAAC,CAACV,UAAaA,QAAQ,EAAE,GAAG;YAACA,QAAQ,EAAE;SAAC,GAAG,EAAE;IAC7F,MAAMc,mBAAmB,IAAID,IAAIL,SAAS,OAAO,CAAC,CAACR,UAAaA,QAAQ,EAAE,GAAG;YAACA,QAAQ,EAAE;SAAC,GAAG,EAAE;IAC9F,MAAMe,oBAAoB,IAAIR;IAC9B,MAAMS,sBAAsB,IAAIT;IAChC,MAAMU,gBAAgBC,oBAAoBR;IAE1C,KAAK,MAAMS,YAAYX,SAAU;QAChC,IAAIW,AAA0B,mBAA1BA,SAA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;QAChCD,WAAW,GAAG,CACbC,OACAC,AAAajC,WAAbiC,YAA2BF,WAAW,GAAG,CAACC,SAAsBhC,SAAbwB;IAErD;IACA,OAAO,IAAInB,IACV;WAAI0B;KAAW,CAAC,OAAO,CAAC,CAAC,CAACC,OAAOd,OAAO,GACvCA,AAAWlB,WAAXkB,SAAuB,EAAE,GAAI;YAAC;gBAACc;gBAAOd;aAAO;SAAC;AAGjD;AAEA,SAASC,cACRF,QAAqB,EACrBT,UAAkC,EAClCJ,gBAAmD,EACnDQ,gBAAwC,EACxCG,aAA+C;IAE/C,IAAIE,AAAiCjB,WAAjCiB,SAAS,mBAAmB,EAAgB;QAC/C,IAAI,CAACA,SAAS,EAAE,EAAE;QAClB,MAAMiB,WAAW9B,iBAAiB,GAAG,CAACa,SAAS,EAAE;QACjD,IAAIiB,AAAalC,WAAbkC,YAA0B,CAACtB,iBAAiB,GAAG,CAACsB,WAAW;QAC/D,OAAO1B,WAAW,IAAI,CAAC,CAACgB,aAAeA,WAAW,EAAE,KAAKU;IAC1D;IACA,OAAO,AAACjB,SAAS,EAAE,IAAIA,AAA2BjB,WAA3BiB,SAAS,aAAa,GAE1CF,cAAc,GAAG,CAACE,SAAS,aAAa,IADxCjB;AAEJ"}
|
|
1
|
+
{"version":3,"file":"core/evaluator/VerificationLinks.js","sources":["../../../src/core/evaluator/VerificationLinks.ts"],"sourcesContent":["import type { ThoughtId } from '../../contracts/ids.js';\nimport type { ResolvedThoughtReferences } from '../IHistoryManager.js';\nimport type { ThoughtData } from '../thought.js';\n\nexport type ActiveThoughtBranches = Readonly<Record<string, readonly ThoughtData[]>>;\n\nexport interface VerificationLinks {\n\treadonly thoughts: readonly ThoughtData[];\n\treadonly hypotheses: readonly ThoughtData[];\n\treadonly hypothesisIds: ReadonlySet<ThoughtId>;\n\treadonly verifiedHypothesisIds: ReadonlySet<ThoughtId>;\n\treadonly verifiedHypothesisCount: number;\n\ttargetFor(verifierId: ThoughtId): ThoughtId | undefined;\n\tisVerified(hypothesis: ThoughtData): boolean;\n\tverifies(verifier: ThoughtData, hypothesis: ThoughtData): boolean;\n}\n\nexport function resolvedVerificationTarget(\n\tthought: ThoughtData,\n\treferences: ResolvedThoughtReferences\n): ThoughtId | undefined {\n\treturn thought.thought_type === 'verification'\n\t\t? references.verificationTargetThoughtId\n\t\t: undefined;\n}\n\nexport function resolveVerificationLinks(\n\thistory: readonly ThoughtData[],\n\tbranches: ActiveThoughtBranches,\n\tadmissionTargets: ReadonlyMap<ThoughtId, ThoughtId> = new Map()\n): VerificationLinks {\n\tconst thoughts = collectActiveThoughts(history, branches);\n\tconst hypotheses = thoughts.filter(\n\t\t(thought) => thought.thought_type === 'hypothesis' && Boolean(thought.id)\n\t);\n\tconst hypothesesById = new Map<ThoughtId, ThoughtData>();\n\tfor (const hypothesis of hypotheses) {\n\t\tconst id = hypothesis.id;\n\t\tif (id && !hypothesesById.has(id)) hypothesesById.set(id, hypothesis);\n\t}\n\tconst hypothesisIds = new Set(hypothesesById.keys());\n\tconst targetsByVerifier = new Map<ThoughtData, ThoughtData>();\n\tconst targetsByVerifierId = new Map<ThoughtId, ThoughtId>();\n\tconst legacyTargets = uniqueLegacyTargets(hypotheses);\n\n\tfor (const verifier of thoughts) {\n\t\tif (verifier.thought_type !== 'verification') continue;\n\t\tconst targetId = verifier.id ? admissionTargets.get(verifier.id) : undefined;\n\t\tconst target =\n\t\t\tverifier.verification_target !== undefined\n\t\t\t\t? targetId === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: hypothesesById.get(targetId)\n\t\t\t\t: !verifier.id || verifier.hypothesis_id === undefined\n\t\t\t\t\t? undefined\n\t\t\t\t\t: legacyTargets.get(verifier.hypothesis_id);\n\t\tif (target === undefined) continue;\n\t\ttargetsByVerifier.set(verifier, target);\n\t\tif (verifier.id && target.id) {\n\t\t\ttargetsByVerifierId.set(verifier.id, target.id);\n\t\t}\n\t}\n\n\tconst verifiedHypotheses = new Set(targetsByVerifier.values());\n\tconst verifiedHypothesisIds = new Set(\n\t\t[...verifiedHypotheses].flatMap((thought) => (thought.id ? [thought.id] : []))\n\t);\n\treturn Object.freeze({\n\t\tthoughts: Object.freeze(thoughts),\n\t\thypotheses: Object.freeze(hypotheses),\n\t\thypothesisIds: new Set(hypothesisIds),\n\t\tverifiedHypothesisIds: new Set(verifiedHypothesisIds),\n\t\tverifiedHypothesisCount: verifiedHypotheses.size,\n\t\ttargetFor: (verifierId: ThoughtId) => targetsByVerifierId.get(verifierId),\n\t\tisVerified: (hypothesis: ThoughtData) => verifiedHypotheses.has(hypothesis),\n\t\tverifies: (verifier: ThoughtData, hypothesis: ThoughtData) =>\n\t\t\ttargetsByVerifier.get(verifier) === hypothesis,\n\t});\n}\n\nexport function collectActiveMainThoughts(\n\thistory: readonly ThoughtData[],\n\tbranches: ActiveThoughtBranches\n): ThoughtData[] {\n\tconst { thoughts, mainCount } = collectActiveEvidence(history, branches);\n\treturn thoughts.slice(0, mainCount);\n}\n\nexport function collectActiveThoughts(\n\thistory: readonly ThoughtData[],\n\tbranches: ActiveThoughtBranches\n): ThoughtData[] {\n\treturn collectActiveEvidence(history, branches).thoughts;\n}\n\n/** Visit each retained record once; later retractions delete earlier copies without reordering. */\nexport function collectActiveEvidence(\n\thistory: readonly ThoughtData[],\n\tbranches: ActiveThoughtBranches\n): { readonly thoughts: ThoughtData[]; readonly mainCount: number } {\n\tconst retained = new Map<ThoughtId | symbol, { thought: ThoughtData; main: boolean }>();\n\tconst retractedIds = new Set<ThoughtId>();\n\tconst lists = [history, ...Object.values(branches)];\n\tfor (const [index, list] of lists.entries()) {\n\t\tfor (const thought of list) {\n\t\t\tconst id = thought.id;\n\t\t\tif (thought.retracted === true) {\n\t\t\t\tif (id) {\n\t\t\t\t\tretractedIds.add(id);\n\t\t\t\t\tretained.delete(id);\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!id) {\n\t\t\t\tif (index === 0) retained.set(Symbol(), { thought, main: true });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (retractedIds.has(id) || retained.has(id)) continue;\n\t\t\tretained.set(id, { thought, main: index === 0 });\n\t\t}\n\t}\n\tconst thoughts: ThoughtData[] = [];\n\tlet mainCount = 0;\n\tfor (const entry of retained.values()) {\n\t\tthoughts.push(entry.thought);\n\t\tif (entry.main) mainCount++;\n\t}\n\treturn { thoughts, mainCount };\n}\n\nfunction uniqueLegacyTargets(hypotheses: readonly ThoughtData[]): ReadonlyMap<string, ThoughtData> {\n\tconst candidates = new Map<string, ThoughtData | undefined>();\n\tfor (const hypothesis of hypotheses) {\n\t\tconst label = hypothesis.hypothesis_id;\n\t\tif (label === undefined) continue;\n\t\tconst existing = candidates.get(label);\n\t\tcandidates.set(\n\t\t\tlabel,\n\t\t\texisting === undefined && !candidates.has(label) ? hypothesis : undefined\n\t\t);\n\t}\n\treturn new Map(\n\t\t[...candidates].flatMap(([label, target]) =>\n\t\t\ttarget === undefined ? [] : ([[label, target]] as const)\n\t\t)\n\t);\n}\n"],"names":["resolvedVerificationTarget","thought","references","undefined","resolveVerificationLinks","history","branches","admissionTargets","Map","thoughts","collectActiveThoughts","hypotheses","Boolean","hypothesesById","hypothesis","id","hypothesisIds","Set","targetsByVerifier","targetsByVerifierId","legacyTargets","uniqueLegacyTargets","verifier","targetId","target","verifiedHypotheses","verifiedHypothesisIds","Object","verifierId","collectActiveMainThoughts","mainCount","collectActiveEvidence","retained","retractedIds","lists","index","list","Symbol","entry","candidates","label","existing"],"mappings":"AAiBO,SAASA,2BACfC,OAAoB,EACpBC,UAAqC;IAErC,OAAOD,AAAyB,mBAAzBA,QAAQ,YAAY,GACxBC,WAAW,2BAA2B,GACtCC;AACJ;AAEO,SAASC,yBACfC,OAA+B,EAC/BC,QAA+B,EAC/BC,mBAAsD,IAAIC,KAAK;IAE/D,MAAMC,WAAWC,sBAAsBL,SAASC;IAChD,MAAMK,aAAaF,SAAS,MAAM,CACjC,CAACR,UAAYA,AAAyB,iBAAzBA,QAAQ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IAAIqB,YAAY;IAChB,KAAK,MAAMQ,SAASN,SAAS,MAAM,GAAI;QACtCvB,SAAS,IAAI,CAAC6B,MAAM,OAAO;QAC3B,IAAIA,MAAM,IAAI,EAAER;IACjB;IACA,OAAO;QAAErB;QAAUqB;IAAU;AAC9B;AAEA,SAAST,oBAAoBV,UAAkC;IAC9D,MAAM4B,aAAa,IAAI/B;IACvB,KAAK,MAAMM,cAAcH,WAAY;QACpC,MAAM6B,QAAQ1B,WAAW,aAAa;QACtC,IAAI0B,AAAUrC,WAAVqC,OAAqB;QACzB,MAAMC,WAAWF,WAAW,GAAG,CAACC;QAChCD,WAAW,GAAG,CACbC,OACAC,AAAatC,WAAbsC,YAA2BF,WAAW,GAAG,CAACC,SAAsBrC,SAAbW;IAErD;IACA,OAAO,IAAIN,IACV;WAAI+B;KAAW,CAAC,OAAO,CAAC,CAAC,CAACC,OAAOhB,OAAO,GACvCA,AAAWrB,WAAXqB,SAAuB,EAAE,GAAI;YAAC;gBAACgB;gBAAOhB;aAAO;SAAC;AAGjD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ActiveEvidenceProjection.d.ts","sourceRoot":"","sources":["../../../src/core/reasoning/ActiveEvidenceProjection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAmB,MAAM,+BAA+B,CAAC;AACjF,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,KAAK,EAAE,SAAS,EAAa,MAAM,wBAAwB,CAAC;AACnE,OAAO,
|
|
1
|
+
{"version":3,"file":"ActiveEvidenceProjection.d.ts","sourceRoot":"","sources":["../../../src/core/reasoning/ActiveEvidenceProjection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAmB,MAAM,+BAA+B,CAAC;AACjF,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,6BAA6B,CAAC;AAC5E,OAAO,KAAK,EAAE,SAAS,EAAa,MAAM,wBAAwB,CAAC;AACnE,OAAO,EAEN,KAAK,qBAAqB,EAC1B,MAAM,mCAAmC,CAAC;AAG3C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AAEjD,MAAM,WAAW,6BAA6B;IAC7C,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,OAAO,EAAE,SAAS,WAAW,EAAE,CAAC;IACzC,QAAQ,CAAC,QAAQ,EAAE,qBAAqB,CAAC;IACzC,QAAQ,CAAC,SAAS,EAAE,UAAU,GAAG,SAAS,CAAC;CAC3C;AAkCD;;;;;;GAMG;AACH,wBAAgB,6BAA6B,CAC5C,KAAK,EAAE,6BAA6B,GAClC,wBAAwB,CAQ1B"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { collectActiveEvidence } from "../evaluator/VerificationLinks.js";
|
|
2
2
|
import { GraphView } from "../graph/GraphView.js";
|
|
3
3
|
class ProjectedGraphStore {
|
|
4
4
|
_edges;
|
|
@@ -29,8 +29,9 @@ class ProjectedGraphStore {
|
|
|
29
29
|
}
|
|
30
30
|
}
|
|
31
31
|
function buildActiveEvidenceProjection(input) {
|
|
32
|
-
const
|
|
33
|
-
const activeThoughts = freezeThoughts(
|
|
32
|
+
const { thoughts, mainCount } = collectActiveEvidence(input.history, input.branches);
|
|
33
|
+
const activeThoughts = freezeThoughts(thoughts);
|
|
34
|
+
const mainHistory = Object.freeze(activeThoughts.slice(0, mainCount));
|
|
34
35
|
const graph = input.edgeStore ? projectGraph(input.sessionId, activeThoughts, input.edgeStore) : void 0;
|
|
35
36
|
return Object.freeze({
|
|
36
37
|
mainHistory,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core/reasoning/ActiveEvidenceProjection.js","sources":["../../../src/core/reasoning/ActiveEvidenceProjection.ts"],"sourcesContent":["import type { IEdgeStore, IGraphViewStore } from '../../contracts/interfaces.js';\nimport type { ActiveEvidenceProjection } from '../../contracts/strategy.js';\nimport type { SessionId, ThoughtId } from '../../contracts/ids.js';\nimport {\n\
|
|
1
|
+
{"version":3,"file":"core/reasoning/ActiveEvidenceProjection.js","sources":["../../../src/core/reasoning/ActiveEvidenceProjection.ts"],"sourcesContent":["import type { IEdgeStore, IGraphViewStore } from '../../contracts/interfaces.js';\nimport type { ActiveEvidenceProjection } from '../../contracts/strategy.js';\nimport type { SessionId, ThoughtId } from '../../contracts/ids.js';\nimport {\n\tcollectActiveEvidence,\n\ttype ActiveThoughtBranches,\n} from '../evaluator/VerificationLinks.js';\nimport { GraphView } from '../graph/GraphView.js';\nimport type { Edge } from '../graph/Edge.js';\nimport type { ThoughtData } from '../thought.js';\n\nexport interface ActiveEvidenceProjectionInput {\n\treadonly sessionId: SessionId;\n\treadonly history: readonly ThoughtData[];\n\treadonly branches: ActiveThoughtBranches;\n\treadonly edgeStore: IEdgeStore | undefined;\n}\n\nclass ProjectedGraphStore implements IGraphViewStore {\n\tprivate readonly _edges: readonly Edge[];\n\tprivate readonly _nodes: readonly ThoughtId[];\n\tprivate readonly _outgoing: ReadonlyMap<ThoughtId, readonly Edge[]>;\n\tprivate readonly _incoming: ReadonlyMap<ThoughtId, readonly Edge[]>;\n\tprivate readonly _sessionId: SessionId;\n\n\tconstructor(sessionId: SessionId, edges: readonly Edge[], nodes: readonly ThoughtId[]) {\n\t\tthis._sessionId = sessionId;\n\t\tthis._edges = Object.freeze(edges.map(copyEdge));\n\t\tthis._nodes = Object.freeze([...nodes]);\n\t\tthis._outgoing = buildAdjacency(this._edges, 'from');\n\t\tthis._incoming = buildAdjacency(this._edges, 'to');\n\t}\n\n\toutgoing(sessionId: SessionId, from: ThoughtId): readonly Edge[] {\n\t\treturn sessionId === this._sessionId ? (this._outgoing.get(from) ?? []) : [];\n\t}\n\n\tincoming(sessionId: SessionId, to: ThoughtId): readonly Edge[] {\n\t\treturn sessionId === this._sessionId ? (this._incoming.get(to) ?? []) : [];\n\t}\n\n\tedgesForSession(sessionId: SessionId): readonly Edge[] {\n\t\treturn sessionId === this._sessionId ? this._edges : [];\n\t}\n\n\tnodesForSession(sessionId: SessionId): readonly ThoughtId[] {\n\t\treturn sessionId === this._sessionId ? this._nodes : [];\n\t}\n}\n\n/**\n * Build immutable, deep-copied active evidence for strategy reads.\n *\n * Main history keeps retained main order. Active thoughts include branch-only retained entries.\n * The graph is induced by active endpoints only, without path contraction, and never mutates the\n * audit edge store.\n */\nexport function buildActiveEvidenceProjection(\n\tinput: ActiveEvidenceProjectionInput\n): ActiveEvidenceProjection {\n\tconst { thoughts, mainCount } = collectActiveEvidence(input.history, input.branches);\n\tconst activeThoughts = freezeThoughts(thoughts);\n\tconst mainHistory = Object.freeze(activeThoughts.slice(0, mainCount));\n\tconst graph = input.edgeStore\n\t\t? projectGraph(input.sessionId, activeThoughts, input.edgeStore)\n\t\t: undefined;\n\treturn Object.freeze({ mainHistory, activeThoughts, graph });\n}\n\nfunction projectGraph(\n\tsessionId: SessionId,\n\tactiveThoughts: readonly ThoughtData[],\n\tedgeStore: IEdgeStore\n): GraphView {\n\tconst activeIds = new Set(activeThoughts.flatMap((thought) => (thought.id ? [thought.id] : [])));\n\tconst auditEdges = edgeStore.edgesForSession(sessionId);\n\tconst visibleNodes = new Set<ThoughtId>();\n\tfor (const edge of auditEdges) {\n\t\tif (activeIds.has(edge.from)) visibleNodes.add(edge.from);\n\t\tif (activeIds.has(edge.to)) visibleNodes.add(edge.to);\n\t}\n\tconst edges = auditEdges.filter((edge) => activeIds.has(edge.from) && activeIds.has(edge.to));\n\treturn new GraphView(new ProjectedGraphStore(sessionId, edges, [...visibleNodes]));\n}\n\nfunction freezeThoughts(thoughts: readonly ThoughtData[]): readonly ThoughtData[] {\n\treturn Object.freeze(thoughts.map((thought) => Object.freeze(structuredClone(thought))));\n}\n\nfunction copyEdge(edge: Edge): Edge {\n\treturn Object.freeze({\n\t\t...edge,\n\t\t...(edge.metadata === undefined ? {} : { metadata: copyMetadata(edge.metadata) }),\n\t});\n}\n\nfunction copyMetadata(metadata: Record<string, unknown>): Record<string, unknown> {\n\treturn Object.freeze(\n\t\tObject.fromEntries(\n\t\t\tObject.entries(metadata).map(([key, value]) => [key, copyMetadataValue(value)])\n\t\t)\n\t);\n}\n\nfunction copyMetadataValue(value: unknown): unknown {\n\tif (Array.isArray(value)) return Object.freeze(value.map(copyMetadataValue));\n\tif (isMetadataRecord(value)) return copyMetadata(value);\n\treturn value;\n}\n\nfunction isMetadataRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === 'object' && value !== null;\n}\n\nfunction buildAdjacency(\n\tedges: readonly Edge[],\n\tendpoint: 'from' | 'to'\n): ReadonlyMap<ThoughtId, readonly Edge[]> {\n\tconst mutable = new Map<ThoughtId, Edge[]>();\n\tfor (const edge of edges) {\n\t\tconst key = edge[endpoint];\n\t\tconst bucket = mutable.get(key);\n\t\tif (bucket === undefined) mutable.set(key, [edge]);\n\t\telse bucket.push(edge);\n\t}\n\treturn new Map([...mutable].map(([key, bucket]) => [key, Object.freeze(bucket)]));\n}\n"],"names":["ProjectedGraphStore","sessionId","edges","nodes","Object","copyEdge","buildAdjacency","from","to","buildActiveEvidenceProjection","input","thoughts","mainCount","collectActiveEvidence","activeThoughts","freezeThoughts","mainHistory","graph","projectGraph","undefined","edgeStore","activeIds","Set","thought","auditEdges","visibleNodes","edge","GraphView","structuredClone","copyMetadata","metadata","key","value","copyMetadataValue","Array","isMetadataRecord","endpoint","mutable","Map","bucket"],"mappings":";;AAkBA,MAAMA;IACY,OAAwB;IACxB,OAA6B;IAC7B,UAAmD;IACnD,UAAmD;IACnD,WAAsB;IAEvC,YAAYC,SAAoB,EAAEC,KAAsB,EAAEC,KAA2B,CAAE;QACtF,IAAI,CAAC,UAAU,GAAGF;QAClB,IAAI,CAAC,MAAM,GAAGG,OAAO,MAAM,CAACF,MAAM,GAAG,CAACG;QACtC,IAAI,CAAC,MAAM,GAAGD,OAAO,MAAM,CAAC;eAAID;SAAM;QACtC,IA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AAS1B,eACRJ,KAAsB,EACtBkC,QAAuB;IAEvB,MAAMC,UAAU,IAAIC;IACpB,KAAK,MAAMZ,QAAQxB,MAAO;QACzB,MAAM6B,MAAML,IAAI,CAACU,SAAS;QAC1B,MAAMG,SAASF,QAAQ,GAAG,CAACN;QAC3B,IAAIQ,AAAWpB,WAAXoB,QAAsBF,QAAQ,GAAG,CAACN,KAAK;YAACL;SAAK;aAC5Ca,OAAO,IAAI,CAACb;IAClB;IACA,OAAO,IAAIY,IAAI;WAAID;KAAQ,CAAC,GAAG,CAAC,CAAC,CAACN,KAAKQ,OAAO,GAAK;YAACR;YAAK3B,OAAO,MAAM,CAACmC;SAAQ;AAChF"}
|
package/dist/errors.d.ts
CHANGED
|
@@ -67,6 +67,7 @@ export declare const ERROR_CODES: {
|
|
|
67
67
|
readonly PERSISTENCE_SCOPE_MISMATCH: "PERSISTENCE_SCOPE_MISMATCH";
|
|
68
68
|
readonly PERSISTENCE_UNAVAILABLE: "PERSISTENCE_UNAVAILABLE";
|
|
69
69
|
readonly PERSISTENCE_COMPATIBILITY: "PERSISTENCE_COMPATIBILITY";
|
|
70
|
+
readonly PERSISTENCE_BACKLOG_FULL: "PERSISTENCE_BACKLOG_FULL";
|
|
70
71
|
};
|
|
71
72
|
export type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];
|
|
72
73
|
/**
|
package/dist/errors.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH;;GAEG;AACH,eAAO,MAAM,WAAW
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH;;GAEG;AACH,eAAO,MAAM,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;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IACnD,SAAyB,KAAK,EAAE,OAAO,CAAC;gBAE5B,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,2BAA2B,EAAE,KAAK,EAAE,OAAO;CAU5E;AAED,qBAAa,sBAAuB,SAAQ,uBAAuB;IAClE,SAAgB,OAAO,EAAE,MAAM,CAAC;gBAEpB,OAAO,EAAE,MAAM;CAK3B;AAED,8EAA8E;AAC9E,qBAAa,6BAA8B,SAAQ,uBAAuB;IACzE,SAAgB,UAAU,EAAE,MAAM,CAAC;IACnC,SAAgB,MAAM,EAAE,MAAM,CAAC;IAC/B,SAAyB,KAAK,EAAE,OAAO,CAAC;gBAE5B,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,OAAO;CAU/D;AAED;;GAEG;AACH,wBAAgB,WAAW,CAAC,CAAC,SAAS,SAAS,EAC9C,GAAG,EAAE,OAAO,EACZ,IAAI,EAAE,CAAC,GACL,GAAG,IAAI,uBAAuB,GAAG;IAAE,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAA;CAAE,CAEvD;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,CAEtD"}
|
package/dist/errors.js
CHANGED
|
@@ -36,7 +36,8 @@ const ERROR_CODES = {
|
|
|
36
36
|
PERSISTENCE_SESSION_BARRIER_REENTRANCY: 'PERSISTENCE_SESSION_BARRIER_REENTRANCY',
|
|
37
37
|
PERSISTENCE_SCOPE_MISMATCH: 'PERSISTENCE_SCOPE_MISMATCH',
|
|
38
38
|
PERSISTENCE_UNAVAILABLE: 'PERSISTENCE_UNAVAILABLE',
|
|
39
|
-
PERSISTENCE_COMPATIBILITY: 'PERSISTENCE_COMPATIBILITY'
|
|
39
|
+
PERSISTENCE_COMPATIBILITY: 'PERSISTENCE_COMPATIBILITY',
|
|
40
|
+
PERSISTENCE_BACKLOG_FULL: 'PERSISTENCE_BACKLOG_FULL'
|
|
40
41
|
};
|
|
41
42
|
const WARNING_CODES = {
|
|
42
43
|
TOTAL_THOUGHTS_ADJUSTED: 'TOTAL_THOUGHTS_ADJUSTED'
|
package/dist/errors.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"errors.js","sources":["../src/errors.ts"],"sourcesContent":["/**\n * Custom error types for the TraceLattice server.\n *\n * This module defines a hierarchy of error classes for handling various\n * error conditions that can occur in the sequential thinking server.\n * All errors extend the base `SequentialThinkingError` class with\n * specific error codes for programmatic handling.\n *\n * @example\n * ```typescript\n * import { ToolNotFoundError, SkillDiscoveryError } from './errors.js';\n *\n * // Throw a tool not found error\n * throw new ToolNotFoundError('my-tool');\n *\n * // Catch and handle specific errors\n * try {\n * await discoverSkills(dir);\n * } catch (error) {\n * if (error instanceof SkillDiscoveryError) {\n * console.error(`Failed to discover skills: ${error.message}`);\n * console.error(`Error code: ${error.code}`);\n * }\n * }\n * ```\n * @module errors\n */\n\n/**\n * All known error codes as a const object for exhaustive switching.\n */\nexport const ERROR_CODES = {\n\tCONFIGURATION_ERROR: 'CONFIGURATION_ERROR',\n\tTOOL_NOT_FOUND: 'TOOL_NOT_FOUND',\n\tSKILL_NOT_FOUND: 'SKILL_NOT_FOUND',\n\tINVALID_THOUGHT: 'INVALID_THOUGHT',\n\tSKILL_DISCOVERY_FAILED: 'SKILL_DISCOVERY_FAILED',\n\tHISTORY_LIMIT_EXCEEDED: 'HISTORY_LIMIT_EXCEEDED',\n\tDUPLICATE_SKILL: 'DUPLICATE_SKILL',\n\tINVALID_SKILL: 'INVALID_SKILL',\n\tDUPLICATE_TOOL: 'DUPLICATE_TOOL',\n\tINVALID_TOOL: 'INVALID_TOOL',\n\tSESSION_NOT_ACTIVE: 'SESSION_NOT_ACTIVE',\n\tSESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n\tMAX_SESSIONS_REACHED: 'MAX_SESSIONS_REACHED',\n\tPOOL_TERMINATED: 'POOL_TERMINATED',\n\tVALIDATION_ERROR: 'VALIDATION_ERROR',\n\tINVALID_EDGE: 'INVALID_EDGE',\n\tCYCLE_DETECTED: 'CYCLE_DETECTED',\n\tSUSPENSION_NOT_FOUND: 'SUSPENSION_NOT_FOUND',\n\tSUSPENSION_EXPIRED: 'SUSPENSION_EXPIRED',\n\tINVALID_TOOL_CALL: 'INVALID_TOOL_CALL',\n\tINVALID_BACKTRACK: 'INVALID_BACKTRACK',\n\tDUPLICATE_SUMMARY: 'DUPLICATE_SUMMARY',\n\tUNKNOWN_TOOL: 'UNKNOWN_TOOL',\n\tLOCK_TIMEOUT: 'LOCK_TIMEOUT',\n\tCLI_SHUTDOWN_TIMEOUT: 'CLI_SHUTDOWN_TIMEOUT',\n\tSESSION_ACCESS_DENIED: 'SESSION_ACCESS_DENIED',\n\tSESSION_EXPIRED: 'SESSION_EXPIRED',\n\tSESSION_LIFECYCLE_CLOSED: 'SESSION_LIFECYCLE_CLOSED',\n\tPERSISTENCE_OWNERSHIP: 'PERSISTENCE_OWNERSHIP',\n\tPERSISTENCE_CORRUPTION: 'PERSISTENCE_CORRUPTION',\n\tPERSISTENCE_PUBLICATION: 'PERSISTENCE_PUBLICATION',\n\tPERSISTENCE_CLOSED: 'PERSISTENCE_CLOSED',\n\tPERSISTENCE_DRAIN: 'PERSISTENCE_DRAIN',\n\tPERSISTENCE_SESSION_ADMISSION_CLOSED: 'PERSISTENCE_SESSION_ADMISSION_CLOSED',\n\tPERSISTENCE_SESSION_BARRIER_REENTRANCY: 'PERSISTENCE_SESSION_BARRIER_REENTRANCY',\n\tPERSISTENCE_SCOPE_MISMATCH: 'PERSISTENCE_SCOPE_MISMATCH',\n\tPERSISTENCE_UNAVAILABLE: 'PERSISTENCE_UNAVAILABLE',\n\tPERSISTENCE_COMPATIBILITY: 'PERSISTENCE_COMPATIBILITY',\n} as const;\n\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\n/**\n * All known warning codes as a const object.\n * Warnings are non-fatal advisory signals returned alongside successful results.\n */\nexport const WARNING_CODES = {\n\tTOTAL_THOUGHTS_ADJUSTED: 'TOTAL_THOUGHTS_ADJUSTED',\n} as const;\n\nexport type WarningCode = (typeof WARNING_CODES)[keyof typeof WARNING_CODES];\n\n/**\n * Base error class for all Sequential Thinking server errors.\n *\n * This error extends the native `Error` class and adds a `code` property\n * for programmatic error identification and handling. All specific error\n * types in the system extend this base class.\n *\n * @remarks\n * **Error Codes:**\n * - `TOOL_NOT_FOUND` - A requested tool was not found\n * - `SKILL_NOT_FOUND` - A requested skill was not found\n * - `INVALID_THOUGHT` - Thought validation failed\n * - `SKILL_DISCOVERY_FAILED` - Skill discovery operation failed\n * - `HISTORY_LIMIT_EXCEEDED` - History size limit was exceeded\n * - `INVALID_EDGE` - An invalid edge operation was attempted\n *\n * @example\n * ```typescript\n * // Throw a custom sequential thinking error\n * throw new SequentialThinkingError('Custom error message', 'CUSTOM_CODE');\n *\n * // Check if an error is a SequentialThinkingError\n * if (error instanceof SequentialThinkingError) {\n * console.error(`Error [${error.code}]: ${error.message}`);\n * }\n * ```\n */\nexport class SequentialThinkingError extends Error {\n\t/** The error code for programmatic identification. */\n\tpublic readonly code: ErrorCode;\n\n\t/**\n\t * Creates a new SequentialThinkingError.\n\t *\n\t * @param message - Human-readable error message\n\t * @param code - Error code for programmatic handling\n\t *\n\t * @example\n\t * ```typescript\n\t * const error = new SequentialThinkingError(\n\t * 'Something went wrong',\n\t * 'CUSTOM_ERROR'\n\t * );\n\t * console.log(error.code); // 'CUSTOM_ERROR'\n\t * ```\n\t */\n\tconstructor(message: string, code: ErrorCode) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.name = 'SequentialThinkingError';\n\t\tError.captureStackTrace(this, this.constructor);\n\t}\n}\n\nexport class ConfigurationError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.CONFIGURATION_ERROR);\n\t\tthis.name = 'ConfigurationError';\n\t}\n}\n\n/**\n * Error thrown when a requested tool is not found in the registry.\n *\n * This error is thrown when attempting to retrieve, update, or delete\n * a tool that doesn't exist in the tool registry.\n *\n * @example\n * ```typescript\n * const tool = registry.get('non-existent-tool');\n * if (!tool) {\n * throw new ToolNotFoundError('non-existent-tool');\n * }\n * ```\n */\nexport class ToolNotFoundError extends SequentialThinkingError {\n\t/**\n\t * Creates a new ToolNotFoundError.\n\t *\n\t * @param toolName - The name of the tool that was not found\n\t * @param action - Optional action being performed (e.g., 'remove', 'update')\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new ToolNotFoundError('my-custom-tool');\n\t * // Error: tool 'my-custom-tool' not found\n\t *\n\t * throw new ToolNotFoundError('my-custom-tool', 'remove');\n\t * // Error: tool 'my-custom-tool' not found, cannot remove\n\t * // Code: TOOL_NOT_FOUND\n\t * ```\n\t */\n\tconstructor(toolName: string, action?: string) {\n\t\tconst message = action\n\t\t\t? `Tool '${toolName}' not found, cannot ${action}`\n\t\t\t: `Tool '${toolName}' not found`;\n\t\tsuper(message, ERROR_CODES.TOOL_NOT_FOUND);\n\t\tthis.name = 'ToolNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when a requested skill is not found in the registry.\n *\n * This error is thrown when attempting to retrieve, update, or delete\n * a skill that doesn't exist in the skill registry.\n *\n * @example\n * ```typescript\n * const skill = registry.get('non-existent-skill');\n * if (!skill) {\n * throw new SkillNotFoundError('non-existent-skill');\n * }\n * ```\n */\nexport class SkillNotFoundError extends SequentialThinkingError {\n\t/**\n\t * Creates a new SkillNotFoundError.\n\t *\n\t * @param skillName - The name of the skill that was not found\n\t * @param action - Optional action being performed (e.g., 'remove', 'update')\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new SkillNotFoundError('my-custom-skill');\n\t * // Error: skill 'my-custom-skill' not found\n\t *\n\t * throw new SkillNotFoundError('my-custom-skill', 'remove');\n\t * // Error: skill 'my-custom-skill' not found, cannot remove\n\t * // Code: SKILL_NOT_FOUND\n\t * ```\n\t */\n\tconstructor(skillName: string, action?: string) {\n\t\tconst message = action\n\t\t\t? `Skill '${skillName}' not found, cannot ${action}`\n\t\t\t: `Skill '${skillName}' not found`;\n\t\tsuper(message, ERROR_CODES.SKILL_NOT_FOUND);\n\t\tthis.name = 'SkillNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when thought validation fails.\n *\n * This error is thrown when a thought fails validation, typically due to\n * invalid values, missing required fields, or constraint violations.\n *\n * @example\n * ```typescript\n * // Validate thought number\n * if (thought.thought_number < 1) {\n * throw new InvalidThoughtError(thought.thought_number, 'thought_number must be >= 1');\n * }\n * ```\n */\nexport class InvalidThoughtError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidThoughtError.\n\t *\n\t * @param thoughtNumber - The thought number that failed validation\n\t * @param reason - Human-readable explanation of why validation failed\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidThoughtError(5, 'thought_number exceeds total_thoughts');\n\t * // Error: Invalid thought 5: thought_number exceeds total_thoughts\n\t * // Code: INVALID_THOUGHT\n\t * ```\n\t */\n\tconstructor(thoughtNumber: number, reason: string) {\n\t\tsuper(`Invalid thought ${thoughtNumber}: ${reason}`, ERROR_CODES.INVALID_THOUGHT);\n\t\tthis.name = 'InvalidThoughtError';\n\t}\n}\n\n/**\n * Error thrown when skill discovery fails.\n *\n * This error is thrown when the skill discovery process encounters an issue,\n * such as filesystem errors, invalid skill files, or parsing failures.\n *\n * @remarks\n * The original error that caused the discovery failure is preserved in the\n * `cause` property for debugging purposes.\n *\n * @example\n * ```typescript\n * try {\n * await discoverSkills('./skills');\n * } catch (error) {\n * throw new SkillDiscoveryError('./skills', error as Error);\n * }\n * ```\n */\nexport class SkillDiscoveryError extends SequentialThinkingError {\n\t/** The underlying error that caused the discovery failure. */\n\tpublic override readonly cause: Error;\n\n\t/**\n\t * Creates a new SkillDiscoveryError.\n\t *\n\t * @param directory - The directory where discovery failed\n\t * @param cause - The underlying error that caused the failure\n\t *\n\t * @example\n\t * ```typescript\n\t * try {\n\t * const skills = await loadSkills('./invalid-directory');\n\t * } catch (error) {\n\t * throw new SkillDiscoveryError('./invalid-directory', error as Error);\n\t * }\n\t * ```\n\t */\n\tconstructor(directory: string, cause: Error) {\n\t\tsuper(\n\t\t\t`Failed to discover skills in ${directory}: ${cause.message}`,\n\t\t\tERROR_CODES.SKILL_DISCOVERY_FAILED\n\t\t);\n\t\tthis.name = 'SkillDiscoveryError';\n\t\tthis.cause = cause;\n\t}\n}\n\n/**\n * Error thrown when history size exceeds the configured limit.\n *\n * This error is thrown when an operation would cause the history size\n * to exceed the maximum configured size limit.\n *\n * @example\n * ```typescript\n * if (history.length >= maxSize) {\n * throw new HistoryLimitExceededError(history.length, maxSize);\n * }\n * ```\n */\nexport class HistoryLimitExceededError extends SequentialThinkingError {\n\t/**\n\t * Creates a new HistoryLimitExceededError.\n\t *\n\t * @param currentSize - The current history size\n\t * @param maxSize - The maximum allowed size\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new HistoryLimitExceededError(1500, 1000);\n\t * // Error: History size 1500 exceeds limit 1000\n\t * // Code: HISTORY_LIMIT_EXCEEDED\n\t * ```\n\t */\n\tconstructor(currentSize: number, maxSize: number) {\n\t\tsuper(\n\t\t\t`History size ${currentSize} exceeds limit ${maxSize}`,\n\t\t\tERROR_CODES.HISTORY_LIMIT_EXCEEDED\n\t\t);\n\t\tthis.name = 'HistoryLimitExceededError';\n\t}\n}\n\n/**\n * Error thrown when attempting to add a skill that already exists.\n *\n * This error is thrown when trying to register a skill with a name that\n * is already present in the skill registry.\n *\n * @example\n * ```typescript\n * if (registry.has(skill.name)) {\n * throw new DuplicateSkillError(skill.name);\n * }\n * ```\n */\nexport class DuplicateSkillError extends SequentialThinkingError {\n\t/**\n\t * Creates a new DuplicateSkillError.\n\t *\n\t * @param skillName - The name of the duplicate skill\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new DuplicateSkillError('my-skill');\n\t * // Error: skill 'my-skill' already exists\n\t * // Code: DUPLICATE_SKILL\n\t * ```\n\t */\n\tconstructor(skillName: string) {\n\t\tsuper(`skill '${skillName}' already exists`, ERROR_CODES.DUPLICATE_SKILL);\n\t\tthis.name = 'DuplicateSkillError';\n\t}\n}\n\n/**\n * Error thrown when a skill has invalid data.\n *\n * This error is thrown when a skill fails validation, typically due to\n * missing required fields or invalid values.\n *\n * @example\n * ```typescript\n * if (!skill.name) {\n * throw new InvalidSkillError('Skill must have a valid name');\n * }\n * ```\n */\nexport class InvalidSkillError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidSkillError.\n\t *\n\t * @param reason - The reason for the validation failure\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidSkillError('Skill must have a valid name');\n\t * // Error: Invalid skill: Skill must have a valid name\n\t * // Code: INVALID_SKILL\n\t * ```\n\t */\n\tconstructor(reason: string) {\n\t\tsuper(`Invalid skill: ${reason}`, ERROR_CODES.INVALID_SKILL);\n\t\tthis.name = 'InvalidSkillError';\n\t}\n}\n\n/**\n * Error thrown when attempting to add a tool that already exists.\n *\n * This error is thrown when trying to register a tool with a name that\n * is already present in the tool registry.\n *\n * @example\n * ```typescript\n * if (registry.has(tool.name)) {\n * throw new DuplicateToolError(tool.name);\n * }\n * ```\n */\nexport class DuplicateToolError extends SequentialThinkingError {\n\t/**\n\t * Creates a new DuplicateToolError.\n\t *\n\t * @param toolName - The name of the duplicate tool\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new DuplicateToolError('my-tool');\n\t * // Error: tool 'my-tool' already exists\n\t * // Code: DUPLICATE_TOOL\n\t * ```\n\t */\n\tconstructor(toolName: string) {\n\t\tsuper(`tool '${toolName}' already exists`, ERROR_CODES.DUPLICATE_TOOL);\n\t\tthis.name = 'DuplicateToolError';\n\t}\n}\n\n/**\n * Error thrown when a tool has invalid data.\n *\n * This error is thrown when a tool fails validation, typically due to\n * missing required fields or invalid values.\n *\n * @example\n * ```typescript\n * if (!tool.name) {\n * throw new InvalidToolError('Tool must have a valid name');\n * }\n * ```\n */\nexport class InvalidToolError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidToolError.\n\t *\n\t * @param reason - The reason for the validation failure\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidToolError('Tool must have a valid name');\n\t * // Error: Invalid tool: Tool must have a valid name\n\t * // Code: INVALID_TOOL\n\t * ```\n\t */\n\tconstructor(reason: string) {\n\t\tsuper(`Invalid tool: ${reason}`, ERROR_CODES.INVALID_TOOL);\n\t\tthis.name = 'InvalidToolError';\n\t}\n}\n\n/**\n * Error thrown when the maximum number of sessions has been reached.\n *\n * This error is thrown when trying to create a new session when the\n * pool has reached its configured maximum session limit.\n *\n * @example\n * ```typescript\n * if (pool.sessionCount >= pool.maxSessions) {\n * throw new MaxSessionsReachedError(pool.maxSessions);\n * }\n * ```\n */\nexport class MaxSessionsReachedError extends SequentialThinkingError {\n\t/**\n\t * Creates a new MaxSessionsReachedError.\n\t *\n\t * @param maxSessions - The maximum number of sessions allowed\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new MaxSessionsReachedError(100);\n\t * // Error: Max sessions (100) reached. Wait for a session to close or increase maxSessions.\n\t * // Code: MAX_SESSIONS_REACHED\n\t * ```\n\t */\n\tconstructor(maxSessions: number) {\n\t\tsuper(\n\t\t\t`Max sessions (${maxSessions}) reached. Wait for a session to close or increase maxSessions.`,\n\t\t\tERROR_CODES.MAX_SESSIONS_REACHED\n\t\t);\n\t\tthis.name = 'MaxSessionsReachedError';\n\t}\n}\n\n/**\n * Error thrown when attempting to use a terminated connection pool.\n *\n * This error is thrown when trying to create sessions or process requests\n * after the connection pool has been terminated.\n *\n * @example\n * ```typescript\n * if (pool.isTerminated) {\n * throw new PoolTerminatedError();\n * }\n * ```\n */\nexport class PoolTerminatedError extends SequentialThinkingError {\n\t/**\n\t * Creates a new PoolTerminatedError.\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new PoolTerminatedError();\n\t * // Error: ConnectionPool has been terminated\n\t * // Code: POOL_TERMINATED\n\t * ```\n\t */\n\tconstructor() {\n\t\tsuper('ConnectionPool has been terminated', ERROR_CODES.POOL_TERMINATED);\n\t\tthis.name = 'PoolTerminatedError';\n\t}\n}\n\n/**\n * Error thrown when input validation fails due to invalid or malicious data.\n *\n * This error is thrown when user input fails security or format validation,\n * such as path traversal attempts or invalid identifier formats.\n *\n * @example\n * ```typescript\n * if (!BRANCH_ID_PATTERN.test(branchId)) {\n * throw new ValidationError('branchId', 'Invalid format');\n * }\n * ```\n */\nexport class ValidationError extends SequentialThinkingError {\n\t/** The field that failed validation. */\n\tpublic readonly field: string;\n\n\tconstructor(field: string, reason: string) {\n\t\tsuper(`Validation failed for '${field}': ${reason}`, ERROR_CODES.VALIDATION_ERROR);\n\t\tthis.name = 'ValidationError';\n\t\tthis.field = field;\n\t}\n}\n\n/**\n * Error thrown when an invalid edge operation is attempted.\n *\n * This error is thrown when attempting to add an edge that violates\n * structural invariants of the thought DAG, such as a self-edge\n * (where `from` and `to` reference the same thought).\n *\n * @example\n * ```typescript\n * if (edge.from === edge.to) {\n * throw new InvalidEdgeError(\n * `Self-edge not allowed: from and to are the same (${edge.from})`\n * );\n * }\n * ```\n */\nexport class InvalidEdgeError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidEdgeError.\n\t *\n\t * @param message - Human-readable explanation of the invalid edge\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidEdgeError('Self-edge not allowed: from and to are the same (t1)');\n\t * // Code: INVALID_EDGE\n\t * ```\n\t */\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.INVALID_EDGE);\n\t\tthis.name = 'InvalidEdgeError';\n\t}\n}\n\n/**\n * Error thrown when a cycle is detected during graph traversal.\n *\n * This error is thrown by graph algorithms (such as topological sort)\n * when the thought DAG contains a cycle, violating the acyclic invariant.\n *\n * @example\n * ```typescript\n * try {\n * const order = graphView.topological(sessionId);\n * } catch (error) {\n * if (error instanceof CycleDetectedError) {\n * console.error('Cycle in thought graph:', error.message);\n * }\n * }\n * ```\n */\nexport class CycleDetectedError extends SequentialThinkingError {\n\t/**\n\t * Creates a new CycleDetectedError.\n\t *\n\t * @param message - Human-readable explanation of the cycle\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new CycleDetectedError('Cycle detected in session s1');\n\t * // Code: CYCLE_DETECTED\n\t * ```\n\t */\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.CYCLE_DETECTED);\n\t\tthis.name = 'CycleDetectedError';\n\t}\n}\n\n/**\n * Error thrown when a suspension record is not found.\n *\n * This error is thrown when attempting to resume a tool interleave\n * suspension that does not exist in the suspension store.\n */\nexport class SuspensionNotFoundError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.SUSPENSION_NOT_FOUND);\n\t\tthis.name = 'SuspensionNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when a suspension record has expired.\n *\n * This error is thrown when attempting to resume a tool interleave\n * suspension whose TTL has elapsed.\n */\nexport class SuspensionExpiredError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.SUSPENSION_EXPIRED);\n\t\tthis.name = 'SuspensionExpiredError';\n\t}\n}\n\n/**\n * Error thrown when a tool call payload is invalid.\n *\n * This error is thrown when a tool interleave invocation has malformed\n * arguments, missing identifiers, or otherwise fails validation.\n */\nexport class InvalidToolCallError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.INVALID_TOOL_CALL);\n\t\tthis.name = 'InvalidToolCallError';\n\t}\n}\n\n/**\n * Error thrown when a backtrack operation is invalid.\n *\n * This error is thrown when an attempt to backtrack the reasoning\n * chain references an unreachable thought or violates DAG invariants.\n */\nexport class InvalidBacktrackError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.INVALID_BACKTRACK);\n\t\tthis.name = 'InvalidBacktrackError';\n\t}\n}\n\n/**\n * Error thrown when a tool_call references a tool not registered with the server.\n *\n * Acts as an allowlist gate: only tools registered in the ToolRegistry may be\n * invoked through tool interleave. Prevents arbitrary tool name injection.\n */\nexport class UnknownToolError extends SequentialThinkingError {\n\tpublic readonly toolName: string;\n\n\tconstructor(toolName: string, message?: string) {\n\t\tsuper(\n\t\t\tmessage ?? `Unknown tool '${toolName}': not registered with the server`,\n\t\t\tERROR_CODES.UNKNOWN_TOOL\n\t\t);\n\t\tthis.name = 'UnknownToolError';\n\t\tthis.toolName = toolName;\n\t}\n}\n\n/** Error thrown when the CLI's complete shutdown exceeds its outer deadline. */\nexport class CliShutdownTimeoutError extends SequentialThinkingError {\n\tpublic readonly timeoutMs: number;\n\n\tconstructor(timeoutMs: number) {\n\t\tsuper(`CLI shutdown timed out after ${timeoutMs}ms`, ERROR_CODES.CLI_SHUTDOWN_TIMEOUT);\n\t\tthis.name = 'CliShutdownTimeoutError';\n\t\tthis.timeoutMs = timeoutMs;\n\t}\n}\n\nexport class PersistenceOwnershipError extends SequentialThinkingError {\n\tpublic readonly canonicalDataDir: string;\n\tpublic readonly lockPath: string;\n\tpublic override readonly cause: unknown;\n\n\tconstructor(canonicalDataDir: string, lockPath: string, cause: unknown) {\n\t\tsuper(\n\t\t\t`Persistence directory '${canonicalDataDir}' already has an active writer`,\n\t\t\tERROR_CODES.PERSISTENCE_OWNERSHIP\n\t\t);\n\t\tthis.name = 'PersistenceOwnershipError';\n\t\tthis.canonicalDataDir = canonicalDataDir;\n\t\tthis.lockPath = lockPath;\n\t\tthis.cause = cause;\n\t}\n}\n\nexport class PersistenceCorruptionError extends SequentialThinkingError {\n\tpublic readonly path: string;\n\tpublic override readonly cause: unknown;\n\n\tconstructor(path: string, cause: unknown) {\n\t\tsuper(\n\t\t\t`Persisted data at '${path}' is corrupt or incompatible`,\n\t\t\tERROR_CODES.PERSISTENCE_CORRUPTION\n\t\t);\n\t\tthis.name = 'PersistenceCorruptionError';\n\t\tthis.path = path;\n\t\tthis.cause = cause;\n\t}\n}\n\n/** Error raised when startup cannot read from an unhealthy persistence backend. */\nexport class PersistenceUnavailableError extends SequentialThinkingError {\n\tconstructor() {\n\t\tsuper(\n\t\t\t'Persistence backend is unavailable during startup restore',\n\t\t\tERROR_CODES.PERSISTENCE_UNAVAILABLE\n\t\t);\n\t\tthis.name = 'PersistenceUnavailableError';\n\t}\n}\n\nexport type PersistencePublicationStage = 'temporary-write' | 'atomic-replacement' | 'cleanup';\n\nexport class PersistencePublicationError extends SequentialThinkingError {\n\tpublic readonly path: string;\n\tpublic readonly stage: PersistencePublicationStage;\n\tpublic override readonly cause: unknown;\n\n\tconstructor(path: string, stage: PersistencePublicationStage, cause: unknown) {\n\t\tsuper(\n\t\t\t`Failed persistence publication for '${path}' during ${stage}`,\n\t\t\tERROR_CODES.PERSISTENCE_PUBLICATION\n\t\t);\n\t\tthis.name = 'PersistencePublicationError';\n\t\tthis.path = path;\n\t\tthis.stage = stage;\n\t\tthis.cause = cause;\n\t}\n}\n\nexport class PersistenceClosedError extends SequentialThinkingError {\n\tpublic readonly dataDir: string;\n\n\tconstructor(dataDir: string) {\n\t\tsuper(`Persistence writer for '${dataDir}' is closed`, ERROR_CODES.PERSISTENCE_CLOSED);\n\t\tthis.name = 'PersistenceClosedError';\n\t\tthis.dataDir = dataDir;\n\t}\n}\n\n/** Error raised for well-formed but unsupported or drifted persisted data. */\nexport class PersistenceCompatibilityError extends SequentialThinkingError {\n\tpublic readonly sourcePath: string;\n\tpublic readonly detail: string;\n\tpublic override readonly cause: unknown;\n\n\tconstructor(sourcePath: string, detail: string, cause?: unknown) {\n\t\tsuper(\n\t\t\t`Persisted data at '${sourcePath}' is incompatible: ${detail}`,\n\t\t\tERROR_CODES.PERSISTENCE_COMPATIBILITY\n\t\t);\n\t\tthis.name = 'PersistenceCompatibilityError';\n\t\tthis.sourcePath = sourcePath;\n\t\tthis.detail = detail;\n\t\tthis.cause = cause;\n\t}\n}\n\n/**\n * Type guard to check if an error has a specific error code.\n */\nexport function isErrorCode<C extends ErrorCode>(\n\terr: unknown,\n\tcode: C\n): err is SequentialThinkingError & { readonly code: C } {\n\treturn err instanceof SequentialThinkingError && err.code === code;\n}\n\n/**\n * Extract a human-readable message from an unknown error value.\n *\n * Standardizes the common `error instanceof Error ? error.message : String(error)`\n * pattern used in catch blocks across the codebase.\n *\n * @param error - The unknown error value to extract a message from\n * @returns The error message string\n *\n * @example\n * ```typescript\n * try {\n * await doSomething();\n * } catch (error) {\n * logger.error('Failed', { error: getErrorMessage(error) });\n * }\n * ```\n */\nexport function getErrorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n"],"names":["ERROR_CODES","WARNING_CODES","SequentialThinkingError","Error","message","code","ConfigurationError","ToolNotFoundError","toolName","action","SkillNotFoundError","skillName","InvalidThoughtError","thoughtNumber","reason","SkillDiscoveryError","directory","cause","HistoryLimitExceededError","currentSize","maxSize","DuplicateSkillError","InvalidSkillError","DuplicateToolError","InvalidToolError","MaxSessionsReachedError","maxSessions","PoolTerminatedError","ValidationError","field","InvalidEdgeError","CycleDetectedError","SuspensionNotFoundError","SuspensionExpiredError","InvalidToolCallError","InvalidBacktrackError","UnknownToolError","CliShutdownTimeoutError","timeoutMs","PersistenceOwnershipError","canonicalDataDir","lockPath","PersistenceCorruptionError","path","PersistenceUnavailableError","PersistencePublicationError","stage","PersistenceClosedError","dataDir","PersistenceCompatibilityError","sourcePath","detail","isErrorCode","err","getErrorMessage","error","String"],"mappings":"AA+BO,MAAMA,cAAc;IAC1B,qBAAqB;IACrB,gBAAgB;IAChB,iBAAiB;IACjB,iBAAiB;IACjB,wBAAwB;IACxB,wBAAwB;IACxB,iBAAiB;IACjB,eAAe;IACf,gBAAgB;IAChB,cAAc;IACd,oBAAoB;IACpB,mBAAmB;IACnB,sBAAsB;IACtB,iBAAiB;IACjB,kBAAkB;IAClB,cAAc;IACd,gBAAgB;IAChB,sBAAsB;IACtB,oBAAoB;IACpB,mBAAmB;IACnB,mBAAmB;IACnB,mBAAmB;IACnB,cAAc;IACd,cAAc;IACd,sBAAsB;IACtB,uBA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ACD;AAIO,MAAM6C,oCAAoC3C;IAChC,KAAa;IACb,MAAmC;IAC1B,MAAe;IAExC,YAAYyC,IAAY,EAAEG,KAAkC,EAAE7B,KAAc,CAAE;QAC7E,KAAK,CACJ,CAAC,oCAAoC,EAAE0B,KAAK,SAAS,EAAEG,OAAO,EAC9D9C,YAAY,uBAAuB;QAEpC,IAAI,CAAC,IAAI,GAAG;QACZ,IAAI,CAAC,IAAI,GAAG2C;QACZ,IAAI,CAAC,KAAK,GAAGG;QACb,IAAI,CAAC,KAAK,GAAG7B;IACd;AACD;AAEO,MAAM8B,+BAA+B7C;IAC3B,QAAgB;IAEhC,YAAY8C,OAAe,CAAE;QAC5B,KAAK,CAAC,CAAC,wBAAwB,EAAEA,QAAQ,WAAW,CAAC,EAAEhD,YAAY,kBAAkB;QACrF,IAAI,CAAC,IAAI,GAAG;QACZ,IAAI,CAAC,OAAO,GAAGgD;IAChB;AACD;AAGO,MAAMC,sCAAsC/C;IAClC,WAAmB;IACnB,OAAe;IACN,MAAe;IAExC,YAAYgD,UAAkB,EAAEC,MAAc,EAAElC,KAAe,CAAE;QAChE,KAAK,CACJ,CAAC,mBAAmB,EAAEiC,WAAW,mBAAmB,EAAEC,QAAQ,EAC9DnD,YAAY,yBAAyB;QAEtC,IAAI,CAAC,IAAI,GAAG;QACZ,IAAI,CAAC,UAAU,GAAGkD;QAClB,IAAI,CAAC,MAAM,GAAGC;QACd,IAAI,CAAC,KAAK,GAAGlC;IACd;AACD;AAKO,SAASmC,YACfC,GAAY,EACZhD,IAAO;IAEP,OAAOgD,eAAenD,2BAA2BmD,IAAI,IAAI,KAAKhD;AAC/D;AAoBO,SAASiD,gBAAgBC,KAAc;IAC7C,OAAOA,iBAAiBpD,QAAQoD,MAAM,OAAO,GAAGC,OAAOD;AACxD"}
|
|
1
|
+
{"version":3,"file":"errors.js","sources":["../src/errors.ts"],"sourcesContent":["/**\n * Custom error types for the TraceLattice server.\n *\n * This module defines a hierarchy of error classes for handling various\n * error conditions that can occur in the sequential thinking server.\n * All errors extend the base `SequentialThinkingError` class with\n * specific error codes for programmatic handling.\n *\n * @example\n * ```typescript\n * import { ToolNotFoundError, SkillDiscoveryError } from './errors.js';\n *\n * // Throw a tool not found error\n * throw new ToolNotFoundError('my-tool');\n *\n * // Catch and handle specific errors\n * try {\n * await discoverSkills(dir);\n * } catch (error) {\n * if (error instanceof SkillDiscoveryError) {\n * console.error(`Failed to discover skills: ${error.message}`);\n * console.error(`Error code: ${error.code}`);\n * }\n * }\n * ```\n * @module errors\n */\n\n/**\n * All known error codes as a const object for exhaustive switching.\n */\nexport const ERROR_CODES = {\n\tCONFIGURATION_ERROR: 'CONFIGURATION_ERROR',\n\tTOOL_NOT_FOUND: 'TOOL_NOT_FOUND',\n\tSKILL_NOT_FOUND: 'SKILL_NOT_FOUND',\n\tINVALID_THOUGHT: 'INVALID_THOUGHT',\n\tSKILL_DISCOVERY_FAILED: 'SKILL_DISCOVERY_FAILED',\n\tHISTORY_LIMIT_EXCEEDED: 'HISTORY_LIMIT_EXCEEDED',\n\tDUPLICATE_SKILL: 'DUPLICATE_SKILL',\n\tINVALID_SKILL: 'INVALID_SKILL',\n\tDUPLICATE_TOOL: 'DUPLICATE_TOOL',\n\tINVALID_TOOL: 'INVALID_TOOL',\n\tSESSION_NOT_ACTIVE: 'SESSION_NOT_ACTIVE',\n\tSESSION_NOT_FOUND: 'SESSION_NOT_FOUND',\n\tMAX_SESSIONS_REACHED: 'MAX_SESSIONS_REACHED',\n\tPOOL_TERMINATED: 'POOL_TERMINATED',\n\tVALIDATION_ERROR: 'VALIDATION_ERROR',\n\tINVALID_EDGE: 'INVALID_EDGE',\n\tCYCLE_DETECTED: 'CYCLE_DETECTED',\n\tSUSPENSION_NOT_FOUND: 'SUSPENSION_NOT_FOUND',\n\tSUSPENSION_EXPIRED: 'SUSPENSION_EXPIRED',\n\tINVALID_TOOL_CALL: 'INVALID_TOOL_CALL',\n\tINVALID_BACKTRACK: 'INVALID_BACKTRACK',\n\tDUPLICATE_SUMMARY: 'DUPLICATE_SUMMARY',\n\tUNKNOWN_TOOL: 'UNKNOWN_TOOL',\n\tLOCK_TIMEOUT: 'LOCK_TIMEOUT',\n\tCLI_SHUTDOWN_TIMEOUT: 'CLI_SHUTDOWN_TIMEOUT',\n\tSESSION_ACCESS_DENIED: 'SESSION_ACCESS_DENIED',\n\tSESSION_EXPIRED: 'SESSION_EXPIRED',\n\tSESSION_LIFECYCLE_CLOSED: 'SESSION_LIFECYCLE_CLOSED',\n\tPERSISTENCE_OWNERSHIP: 'PERSISTENCE_OWNERSHIP',\n\tPERSISTENCE_CORRUPTION: 'PERSISTENCE_CORRUPTION',\n\tPERSISTENCE_PUBLICATION: 'PERSISTENCE_PUBLICATION',\n\tPERSISTENCE_CLOSED: 'PERSISTENCE_CLOSED',\n\tPERSISTENCE_DRAIN: 'PERSISTENCE_DRAIN',\n\tPERSISTENCE_SESSION_ADMISSION_CLOSED: 'PERSISTENCE_SESSION_ADMISSION_CLOSED',\n\tPERSISTENCE_SESSION_BARRIER_REENTRANCY: 'PERSISTENCE_SESSION_BARRIER_REENTRANCY',\n\tPERSISTENCE_SCOPE_MISMATCH: 'PERSISTENCE_SCOPE_MISMATCH',\n\tPERSISTENCE_UNAVAILABLE: 'PERSISTENCE_UNAVAILABLE',\n\tPERSISTENCE_COMPATIBILITY: 'PERSISTENCE_COMPATIBILITY',\n\tPERSISTENCE_BACKLOG_FULL: 'PERSISTENCE_BACKLOG_FULL',\n} as const;\n\nexport type ErrorCode = (typeof ERROR_CODES)[keyof typeof ERROR_CODES];\n\n/**\n * All known warning codes as a const object.\n * Warnings are non-fatal advisory signals returned alongside successful results.\n */\nexport const WARNING_CODES = {\n\tTOTAL_THOUGHTS_ADJUSTED: 'TOTAL_THOUGHTS_ADJUSTED',\n} as const;\n\nexport type WarningCode = (typeof WARNING_CODES)[keyof typeof WARNING_CODES];\n\n/**\n * Base error class for all Sequential Thinking server errors.\n *\n * This error extends the native `Error` class and adds a `code` property\n * for programmatic error identification and handling. All specific error\n * types in the system extend this base class.\n *\n * @remarks\n * **Error Codes:**\n * - `TOOL_NOT_FOUND` - A requested tool was not found\n * - `SKILL_NOT_FOUND` - A requested skill was not found\n * - `INVALID_THOUGHT` - Thought validation failed\n * - `SKILL_DISCOVERY_FAILED` - Skill discovery operation failed\n * - `HISTORY_LIMIT_EXCEEDED` - History size limit was exceeded\n * - `INVALID_EDGE` - An invalid edge operation was attempted\n *\n * @example\n * ```typescript\n * // Throw a custom sequential thinking error\n * throw new SequentialThinkingError('Custom error message', 'CUSTOM_CODE');\n *\n * // Check if an error is a SequentialThinkingError\n * if (error instanceof SequentialThinkingError) {\n * console.error(`Error [${error.code}]: ${error.message}`);\n * }\n * ```\n */\nexport class SequentialThinkingError extends Error {\n\t/** The error code for programmatic identification. */\n\tpublic readonly code: ErrorCode;\n\n\t/**\n\t * Creates a new SequentialThinkingError.\n\t *\n\t * @param message - Human-readable error message\n\t * @param code - Error code for programmatic handling\n\t *\n\t * @example\n\t * ```typescript\n\t * const error = new SequentialThinkingError(\n\t * 'Something went wrong',\n\t * 'CUSTOM_ERROR'\n\t * );\n\t * console.log(error.code); // 'CUSTOM_ERROR'\n\t * ```\n\t */\n\tconstructor(message: string, code: ErrorCode) {\n\t\tsuper(message);\n\t\tthis.code = code;\n\t\tthis.name = 'SequentialThinkingError';\n\t\tError.captureStackTrace(this, this.constructor);\n\t}\n}\n\nexport class ConfigurationError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.CONFIGURATION_ERROR);\n\t\tthis.name = 'ConfigurationError';\n\t}\n}\n\n/**\n * Error thrown when a requested tool is not found in the registry.\n *\n * This error is thrown when attempting to retrieve, update, or delete\n * a tool that doesn't exist in the tool registry.\n *\n * @example\n * ```typescript\n * const tool = registry.get('non-existent-tool');\n * if (!tool) {\n * throw new ToolNotFoundError('non-existent-tool');\n * }\n * ```\n */\nexport class ToolNotFoundError extends SequentialThinkingError {\n\t/**\n\t * Creates a new ToolNotFoundError.\n\t *\n\t * @param toolName - The name of the tool that was not found\n\t * @param action - Optional action being performed (e.g., 'remove', 'update')\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new ToolNotFoundError('my-custom-tool');\n\t * // Error: tool 'my-custom-tool' not found\n\t *\n\t * throw new ToolNotFoundError('my-custom-tool', 'remove');\n\t * // Error: tool 'my-custom-tool' not found, cannot remove\n\t * // Code: TOOL_NOT_FOUND\n\t * ```\n\t */\n\tconstructor(toolName: string, action?: string) {\n\t\tconst message = action\n\t\t\t? `Tool '${toolName}' not found, cannot ${action}`\n\t\t\t: `Tool '${toolName}' not found`;\n\t\tsuper(message, ERROR_CODES.TOOL_NOT_FOUND);\n\t\tthis.name = 'ToolNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when a requested skill is not found in the registry.\n *\n * This error is thrown when attempting to retrieve, update, or delete\n * a skill that doesn't exist in the skill registry.\n *\n * @example\n * ```typescript\n * const skill = registry.get('non-existent-skill');\n * if (!skill) {\n * throw new SkillNotFoundError('non-existent-skill');\n * }\n * ```\n */\nexport class SkillNotFoundError extends SequentialThinkingError {\n\t/**\n\t * Creates a new SkillNotFoundError.\n\t *\n\t * @param skillName - The name of the skill that was not found\n\t * @param action - Optional action being performed (e.g., 'remove', 'update')\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new SkillNotFoundError('my-custom-skill');\n\t * // Error: skill 'my-custom-skill' not found\n\t *\n\t * throw new SkillNotFoundError('my-custom-skill', 'remove');\n\t * // Error: skill 'my-custom-skill' not found, cannot remove\n\t * // Code: SKILL_NOT_FOUND\n\t * ```\n\t */\n\tconstructor(skillName: string, action?: string) {\n\t\tconst message = action\n\t\t\t? `Skill '${skillName}' not found, cannot ${action}`\n\t\t\t: `Skill '${skillName}' not found`;\n\t\tsuper(message, ERROR_CODES.SKILL_NOT_FOUND);\n\t\tthis.name = 'SkillNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when thought validation fails.\n *\n * This error is thrown when a thought fails validation, typically due to\n * invalid values, missing required fields, or constraint violations.\n *\n * @example\n * ```typescript\n * // Validate thought number\n * if (thought.thought_number < 1) {\n * throw new InvalidThoughtError(thought.thought_number, 'thought_number must be >= 1');\n * }\n * ```\n */\nexport class InvalidThoughtError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidThoughtError.\n\t *\n\t * @param thoughtNumber - The thought number that failed validation\n\t * @param reason - Human-readable explanation of why validation failed\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidThoughtError(5, 'thought_number exceeds total_thoughts');\n\t * // Error: Invalid thought 5: thought_number exceeds total_thoughts\n\t * // Code: INVALID_THOUGHT\n\t * ```\n\t */\n\tconstructor(thoughtNumber: number, reason: string) {\n\t\tsuper(`Invalid thought ${thoughtNumber}: ${reason}`, ERROR_CODES.INVALID_THOUGHT);\n\t\tthis.name = 'InvalidThoughtError';\n\t}\n}\n\n/**\n * Error thrown when skill discovery fails.\n *\n * This error is thrown when the skill discovery process encounters an issue,\n * such as filesystem errors, invalid skill files, or parsing failures.\n *\n * @remarks\n * The original error that caused the discovery failure is preserved in the\n * `cause` property for debugging purposes.\n *\n * @example\n * ```typescript\n * try {\n * await discoverSkills('./skills');\n * } catch (error) {\n * throw new SkillDiscoveryError('./skills', error as Error);\n * }\n * ```\n */\nexport class SkillDiscoveryError extends SequentialThinkingError {\n\t/** The underlying error that caused the discovery failure. */\n\tpublic override readonly cause: Error;\n\n\t/**\n\t * Creates a new SkillDiscoveryError.\n\t *\n\t * @param directory - The directory where discovery failed\n\t * @param cause - The underlying error that caused the failure\n\t *\n\t * @example\n\t * ```typescript\n\t * try {\n\t * const skills = await loadSkills('./invalid-directory');\n\t * } catch (error) {\n\t * throw new SkillDiscoveryError('./invalid-directory', error as Error);\n\t * }\n\t * ```\n\t */\n\tconstructor(directory: string, cause: Error) {\n\t\tsuper(\n\t\t\t`Failed to discover skills in ${directory}: ${cause.message}`,\n\t\t\tERROR_CODES.SKILL_DISCOVERY_FAILED\n\t\t);\n\t\tthis.name = 'SkillDiscoveryError';\n\t\tthis.cause = cause;\n\t}\n}\n\n/**\n * Error thrown when history size exceeds the configured limit.\n *\n * This error is thrown when an operation would cause the history size\n * to exceed the maximum configured size limit.\n *\n * @example\n * ```typescript\n * if (history.length >= maxSize) {\n * throw new HistoryLimitExceededError(history.length, maxSize);\n * }\n * ```\n */\nexport class HistoryLimitExceededError extends SequentialThinkingError {\n\t/**\n\t * Creates a new HistoryLimitExceededError.\n\t *\n\t * @param currentSize - The current history size\n\t * @param maxSize - The maximum allowed size\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new HistoryLimitExceededError(1500, 1000);\n\t * // Error: History size 1500 exceeds limit 1000\n\t * // Code: HISTORY_LIMIT_EXCEEDED\n\t * ```\n\t */\n\tconstructor(currentSize: number, maxSize: number) {\n\t\tsuper(\n\t\t\t`History size ${currentSize} exceeds limit ${maxSize}`,\n\t\t\tERROR_CODES.HISTORY_LIMIT_EXCEEDED\n\t\t);\n\t\tthis.name = 'HistoryLimitExceededError';\n\t}\n}\n\n/**\n * Error thrown when attempting to add a skill that already exists.\n *\n * This error is thrown when trying to register a skill with a name that\n * is already present in the skill registry.\n *\n * @example\n * ```typescript\n * if (registry.has(skill.name)) {\n * throw new DuplicateSkillError(skill.name);\n * }\n * ```\n */\nexport class DuplicateSkillError extends SequentialThinkingError {\n\t/**\n\t * Creates a new DuplicateSkillError.\n\t *\n\t * @param skillName - The name of the duplicate skill\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new DuplicateSkillError('my-skill');\n\t * // Error: skill 'my-skill' already exists\n\t * // Code: DUPLICATE_SKILL\n\t * ```\n\t */\n\tconstructor(skillName: string) {\n\t\tsuper(`skill '${skillName}' already exists`, ERROR_CODES.DUPLICATE_SKILL);\n\t\tthis.name = 'DuplicateSkillError';\n\t}\n}\n\n/**\n * Error thrown when a skill has invalid data.\n *\n * This error is thrown when a skill fails validation, typically due to\n * missing required fields or invalid values.\n *\n * @example\n * ```typescript\n * if (!skill.name) {\n * throw new InvalidSkillError('Skill must have a valid name');\n * }\n * ```\n */\nexport class InvalidSkillError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidSkillError.\n\t *\n\t * @param reason - The reason for the validation failure\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidSkillError('Skill must have a valid name');\n\t * // Error: Invalid skill: Skill must have a valid name\n\t * // Code: INVALID_SKILL\n\t * ```\n\t */\n\tconstructor(reason: string) {\n\t\tsuper(`Invalid skill: ${reason}`, ERROR_CODES.INVALID_SKILL);\n\t\tthis.name = 'InvalidSkillError';\n\t}\n}\n\n/**\n * Error thrown when attempting to add a tool that already exists.\n *\n * This error is thrown when trying to register a tool with a name that\n * is already present in the tool registry.\n *\n * @example\n * ```typescript\n * if (registry.has(tool.name)) {\n * throw new DuplicateToolError(tool.name);\n * }\n * ```\n */\nexport class DuplicateToolError extends SequentialThinkingError {\n\t/**\n\t * Creates a new DuplicateToolError.\n\t *\n\t * @param toolName - The name of the duplicate tool\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new DuplicateToolError('my-tool');\n\t * // Error: tool 'my-tool' already exists\n\t * // Code: DUPLICATE_TOOL\n\t * ```\n\t */\n\tconstructor(toolName: string) {\n\t\tsuper(`tool '${toolName}' already exists`, ERROR_CODES.DUPLICATE_TOOL);\n\t\tthis.name = 'DuplicateToolError';\n\t}\n}\n\n/**\n * Error thrown when a tool has invalid data.\n *\n * This error is thrown when a tool fails validation, typically due to\n * missing required fields or invalid values.\n *\n * @example\n * ```typescript\n * if (!tool.name) {\n * throw new InvalidToolError('Tool must have a valid name');\n * }\n * ```\n */\nexport class InvalidToolError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidToolError.\n\t *\n\t * @param reason - The reason for the validation failure\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidToolError('Tool must have a valid name');\n\t * // Error: Invalid tool: Tool must have a valid name\n\t * // Code: INVALID_TOOL\n\t * ```\n\t */\n\tconstructor(reason: string) {\n\t\tsuper(`Invalid tool: ${reason}`, ERROR_CODES.INVALID_TOOL);\n\t\tthis.name = 'InvalidToolError';\n\t}\n}\n\n/**\n * Error thrown when the maximum number of sessions has been reached.\n *\n * This error is thrown when trying to create a new session when the\n * pool has reached its configured maximum session limit.\n *\n * @example\n * ```typescript\n * if (pool.sessionCount >= pool.maxSessions) {\n * throw new MaxSessionsReachedError(pool.maxSessions);\n * }\n * ```\n */\nexport class MaxSessionsReachedError extends SequentialThinkingError {\n\t/**\n\t * Creates a new MaxSessionsReachedError.\n\t *\n\t * @param maxSessions - The maximum number of sessions allowed\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new MaxSessionsReachedError(100);\n\t * // Error: Max sessions (100) reached. Wait for a session to close or increase maxSessions.\n\t * // Code: MAX_SESSIONS_REACHED\n\t * ```\n\t */\n\tconstructor(maxSessions: number) {\n\t\tsuper(\n\t\t\t`Max sessions (${maxSessions}) reached. Wait for a session to close or increase maxSessions.`,\n\t\t\tERROR_CODES.MAX_SESSIONS_REACHED\n\t\t);\n\t\tthis.name = 'MaxSessionsReachedError';\n\t}\n}\n\n/**\n * Error thrown when attempting to use a terminated connection pool.\n *\n * This error is thrown when trying to create sessions or process requests\n * after the connection pool has been terminated.\n *\n * @example\n * ```typescript\n * if (pool.isTerminated) {\n * throw new PoolTerminatedError();\n * }\n * ```\n */\nexport class PoolTerminatedError extends SequentialThinkingError {\n\t/**\n\t * Creates a new PoolTerminatedError.\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new PoolTerminatedError();\n\t * // Error: ConnectionPool has been terminated\n\t * // Code: POOL_TERMINATED\n\t * ```\n\t */\n\tconstructor() {\n\t\tsuper('ConnectionPool has been terminated', ERROR_CODES.POOL_TERMINATED);\n\t\tthis.name = 'PoolTerminatedError';\n\t}\n}\n\n/**\n * Error thrown when input validation fails due to invalid or malicious data.\n *\n * This error is thrown when user input fails security or format validation,\n * such as path traversal attempts or invalid identifier formats.\n *\n * @example\n * ```typescript\n * if (!BRANCH_ID_PATTERN.test(branchId)) {\n * throw new ValidationError('branchId', 'Invalid format');\n * }\n * ```\n */\nexport class ValidationError extends SequentialThinkingError {\n\t/** The field that failed validation. */\n\tpublic readonly field: string;\n\n\tconstructor(field: string, reason: string) {\n\t\tsuper(`Validation failed for '${field}': ${reason}`, ERROR_CODES.VALIDATION_ERROR);\n\t\tthis.name = 'ValidationError';\n\t\tthis.field = field;\n\t}\n}\n\n/**\n * Error thrown when an invalid edge operation is attempted.\n *\n * This error is thrown when attempting to add an edge that violates\n * structural invariants of the thought DAG, such as a self-edge\n * (where `from` and `to` reference the same thought).\n *\n * @example\n * ```typescript\n * if (edge.from === edge.to) {\n * throw new InvalidEdgeError(\n * `Self-edge not allowed: from and to are the same (${edge.from})`\n * );\n * }\n * ```\n */\nexport class InvalidEdgeError extends SequentialThinkingError {\n\t/**\n\t * Creates a new InvalidEdgeError.\n\t *\n\t * @param message - Human-readable explanation of the invalid edge\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new InvalidEdgeError('Self-edge not allowed: from and to are the same (t1)');\n\t * // Code: INVALID_EDGE\n\t * ```\n\t */\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.INVALID_EDGE);\n\t\tthis.name = 'InvalidEdgeError';\n\t}\n}\n\n/**\n * Error thrown when a cycle is detected during graph traversal.\n *\n * This error is thrown by graph algorithms (such as topological sort)\n * when the thought DAG contains a cycle, violating the acyclic invariant.\n *\n * @example\n * ```typescript\n * try {\n * const order = graphView.topological(sessionId);\n * } catch (error) {\n * if (error instanceof CycleDetectedError) {\n * console.error('Cycle in thought graph:', error.message);\n * }\n * }\n * ```\n */\nexport class CycleDetectedError extends SequentialThinkingError {\n\t/**\n\t * Creates a new CycleDetectedError.\n\t *\n\t * @param message - Human-readable explanation of the cycle\n\t *\n\t * @example\n\t * ```typescript\n\t * throw new CycleDetectedError('Cycle detected in session s1');\n\t * // Code: CYCLE_DETECTED\n\t * ```\n\t */\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.CYCLE_DETECTED);\n\t\tthis.name = 'CycleDetectedError';\n\t}\n}\n\n/**\n * Error thrown when a suspension record is not found.\n *\n * This error is thrown when attempting to resume a tool interleave\n * suspension that does not exist in the suspension store.\n */\nexport class SuspensionNotFoundError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.SUSPENSION_NOT_FOUND);\n\t\tthis.name = 'SuspensionNotFoundError';\n\t}\n}\n\n/**\n * Error thrown when a suspension record has expired.\n *\n * This error is thrown when attempting to resume a tool interleave\n * suspension whose TTL has elapsed.\n */\nexport class SuspensionExpiredError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.SUSPENSION_EXPIRED);\n\t\tthis.name = 'SuspensionExpiredError';\n\t}\n}\n\n/**\n * Error thrown when a tool call payload is invalid.\n *\n * This error is thrown when a tool interleave invocation has malformed\n * arguments, missing identifiers, or otherwise fails validation.\n */\nexport class InvalidToolCallError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.INVALID_TOOL_CALL);\n\t\tthis.name = 'InvalidToolCallError';\n\t}\n}\n\n/**\n * Error thrown when a backtrack operation is invalid.\n *\n * This error is thrown when an attempt to backtrack the reasoning\n * chain references an unreachable thought or violates DAG invariants.\n */\nexport class InvalidBacktrackError extends SequentialThinkingError {\n\tconstructor(message: string) {\n\t\tsuper(message, ERROR_CODES.INVALID_BACKTRACK);\n\t\tthis.name = 'InvalidBacktrackError';\n\t}\n}\n\n/**\n * Error thrown when a tool_call references a tool not registered with the server.\n *\n * Acts as an allowlist gate: only tools registered in the ToolRegistry may be\n * invoked through tool interleave. Prevents arbitrary tool name injection.\n */\nexport class UnknownToolError extends SequentialThinkingError {\n\tpublic readonly toolName: string;\n\n\tconstructor(toolName: string, message?: string) {\n\t\tsuper(\n\t\t\tmessage ?? `Unknown tool '${toolName}': not registered with the server`,\n\t\t\tERROR_CODES.UNKNOWN_TOOL\n\t\t);\n\t\tthis.name = 'UnknownToolError';\n\t\tthis.toolName = toolName;\n\t}\n}\n\n/** Error thrown when the CLI's complete shutdown exceeds its outer deadline. */\nexport class CliShutdownTimeoutError extends SequentialThinkingError {\n\tpublic readonly timeoutMs: number;\n\n\tconstructor(timeoutMs: number) {\n\t\tsuper(`CLI shutdown timed out after ${timeoutMs}ms`, ERROR_CODES.CLI_SHUTDOWN_TIMEOUT);\n\t\tthis.name = 'CliShutdownTimeoutError';\n\t\tthis.timeoutMs = timeoutMs;\n\t}\n}\n\nexport class PersistenceOwnershipError extends SequentialThinkingError {\n\tpublic readonly canonicalDataDir: string;\n\tpublic readonly lockPath: string;\n\tpublic override readonly cause: unknown;\n\n\tconstructor(canonicalDataDir: string, lockPath: string, cause: unknown) {\n\t\tsuper(\n\t\t\t`Persistence directory '${canonicalDataDir}' already has an active writer`,\n\t\t\tERROR_CODES.PERSISTENCE_OWNERSHIP\n\t\t);\n\t\tthis.name = 'PersistenceOwnershipError';\n\t\tthis.canonicalDataDir = canonicalDataDir;\n\t\tthis.lockPath = lockPath;\n\t\tthis.cause = cause;\n\t}\n}\n\nexport class PersistenceCorruptionError extends SequentialThinkingError {\n\tpublic readonly path: string;\n\tpublic override readonly cause: unknown;\n\n\tconstructor(path: string, cause: unknown) {\n\t\tsuper(\n\t\t\t`Persisted data at '${path}' is corrupt or incompatible`,\n\t\t\tERROR_CODES.PERSISTENCE_CORRUPTION\n\t\t);\n\t\tthis.name = 'PersistenceCorruptionError';\n\t\tthis.path = path;\n\t\tthis.cause = cause;\n\t}\n}\n\n/** Error raised when startup cannot read from an unhealthy persistence backend. */\nexport class PersistenceUnavailableError extends SequentialThinkingError {\n\tconstructor() {\n\t\tsuper(\n\t\t\t'Persistence backend is unavailable during startup restore',\n\t\t\tERROR_CODES.PERSISTENCE_UNAVAILABLE\n\t\t);\n\t\tthis.name = 'PersistenceUnavailableError';\n\t}\n}\n\nexport type PersistencePublicationStage = 'temporary-write' | 'atomic-replacement' | 'cleanup';\n\nexport class PersistencePublicationError extends SequentialThinkingError {\n\tpublic readonly path: string;\n\tpublic readonly stage: PersistencePublicationStage;\n\tpublic override readonly cause: unknown;\n\n\tconstructor(path: string, stage: PersistencePublicationStage, cause: unknown) {\n\t\tsuper(\n\t\t\t`Failed persistence publication for '${path}' during ${stage}`,\n\t\t\tERROR_CODES.PERSISTENCE_PUBLICATION\n\t\t);\n\t\tthis.name = 'PersistencePublicationError';\n\t\tthis.path = path;\n\t\tthis.stage = stage;\n\t\tthis.cause = cause;\n\t}\n}\n\nexport class PersistenceClosedError extends SequentialThinkingError {\n\tpublic readonly dataDir: string;\n\n\tconstructor(dataDir: string) {\n\t\tsuper(`Persistence writer for '${dataDir}' is closed`, ERROR_CODES.PERSISTENCE_CLOSED);\n\t\tthis.name = 'PersistenceClosedError';\n\t\tthis.dataDir = dataDir;\n\t}\n}\n\n/** Error raised for well-formed but unsupported or drifted persisted data. */\nexport class PersistenceCompatibilityError extends SequentialThinkingError {\n\tpublic readonly sourcePath: string;\n\tpublic readonly detail: string;\n\tpublic override readonly cause: unknown;\n\n\tconstructor(sourcePath: string, detail: string, cause?: unknown) {\n\t\tsuper(\n\t\t\t`Persisted data at '${sourcePath}' is incompatible: ${detail}`,\n\t\t\tERROR_CODES.PERSISTENCE_COMPATIBILITY\n\t\t);\n\t\tthis.name = 'PersistenceCompatibilityError';\n\t\tthis.sourcePath = sourcePath;\n\t\tthis.detail = detail;\n\t\tthis.cause = cause;\n\t}\n}\n\n/**\n * Type guard to check if an error has a specific error code.\n */\nexport function isErrorCode<C extends ErrorCode>(\n\terr: unknown,\n\tcode: C\n): err is SequentialThinkingError & { readonly code: C } {\n\treturn err instanceof SequentialThinkingError && err.code === code;\n}\n\n/**\n * Extract a human-readable message from an unknown error value.\n *\n * Standardizes the common `error instanceof Error ? error.message : String(error)`\n * pattern used in catch blocks across the codebase.\n *\n * @param error - The unknown error value to extract a message from\n * @returns The error message string\n *\n * @example\n * ```typescript\n * try {\n * await doSomething();\n * } catch (error) {\n * logger.error('Failed', { error: getErrorMessage(error) });\n * }\n * ```\n */\nexport function getErrorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n"],"names":["ERROR_CODES","WARNING_CODES","SequentialThinkingError","Error","message","code","ConfigurationError","ToolNotFoundError","toolName","action","SkillNotFoundError","skillName","InvalidThoughtError","thoughtNumber","reason","SkillDiscoveryError","directory","cause","HistoryLimitExceededError","currentSize","maxSize","DuplicateSkillError","InvalidSkillError","DuplicateToolError","InvalidToolError","MaxSessionsReachedError","maxSessions","PoolTerminatedError","ValidationError","field","InvalidEdgeError","CycleDetectedError","SuspensionNotFoundError","SuspensionExpiredError","InvalidToolCallError","InvalidBacktrackError","UnknownToolError","CliShutdownTimeoutError","timeoutMs","PersistenceOwnershipError","canonicalDataDir","lockPath","PersistenceCorruptionError","path","PersistenceUnavailableError","PersistencePublicationError","stage","PersistenceClosedError","dataDir","PersistenceCompatibilityError","sourcePath","detail","isErrorCode","err","getErrorMessage","error","String"],"mappings":"AA+BO,MAAMA,cAAc;IAC1B,qBAAqB;IACrB,gBAAgB;IAChB,iBAAiB;IACjB,iBAAiB;IACjB,wBAAwB;IACxB,wBAAwB;IACxB,iBAAiB;IACjB,eAAe;IACf,gBAAgB;IAChB,cAAc;IACd,oBAAoB;IACpB,mBAAmB;IACnB,sBAAsB;IACtB,iBAAiB;IACjB,kBAAkB;IAClB,cAAc;IACd,gBAAgB;IAChB,sBAAsB;IACtB,oBAAoB;IACpB,mBAAmB;IACnB,mBAAmB;IACnB,mBAAmB;IACnB,cAAc;IACd,cAAc;IACd,sBAAsB;IACtB,uBAAuB;IACvB,iBAAiB;IACjB,0BAA0B;IAC1B,uBAAuB;IACvB,wBAAwB;IACxB,yBAAyB;IACzB,oBAAoB;IACpB,mBAAmB;IACnB,sCAAsC;IACtC,wCAAwC;IACxC,4BAA4B;IAC5B,yBAAyB;IACzB,2BAA2B;IAC3B,0BAA0B;AAC3B;AAQO,MAA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,YAAY,uBAAuB;QAEpC,IAAI,CAAC,IAAI,GAAG;QACZ,IAAI,CAAC,IAAI,GAAG2C;QACZ,IAAI,CAAC,KAAK,GAAGG;QACb,IAAI,CAAC,KAAK,GAAG7B;IACd;AACD;AAEO,MAAM8B,+BAA+B7C;IAC3B,QAAgB;IAEhC,YAAY8C,OAAe,CAAE;QAC5B,KAAK,CAAC,CAAC,wBAAwB,EAAEA,QAAQ,WAAW,CAAC,EAAEhD,YAAY,kBAAkB;QACrF,IAAI,CAAC,IAAI,GAAG;QACZ,IAAI,CAAC,OAAO,GAAGgD;IAChB;AACD;AAGO,MAAMC,sCAAsC/C;IAClC,WAAmB;IACnB,OAAe;IACN,MAAe;IAExC,YAAYgD,UAAkB,EAAEC,MAAc,EAAElC,KAAe,CAAE;QAChE,KAAK,CACJ,CAAC,mBAAmB,EAAEiC,WAAW,mBAAmB,EAAEC,QAAQ,EAC9DnD,YAAY,yBAAyB;QAEtC,IAAI,CAAC,IAAI,GAAG;QACZ,IAAI,CAAC,UAAU,GAAGkD;QAClB,IAAI,CAAC,MAAM,GAAGC;QACd,IAAI,CAAC,KAAK,GAAGlC;IACd;AACD;AAKO,SAASmC,YACfC,GAAY,EACZhD,IAAO;IAEP,OAAOgD,eAAenD,2BAA2BmD,IAAI,IAAI,KAAKhD;AAC/D;AAoBO,SAASiD,gBAAgBC,KAAc;IAC7C,OAAOA,iBAAiBpD,QAAQoD,MAAM,OAAO,GAAGC,OAAOD;AACxD"}
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import type { Logger } from '../logger/StructuredLogger.js';
|
|
10
10
|
import type { PersistenceBackend } from '../contracts/PersistenceBackend.js';
|
|
11
|
+
import type { PersistenceBacklogSource } from '../contracts/persistence-backlog.js';
|
|
11
12
|
/**
|
|
12
13
|
* Health status of an individual component.
|
|
13
14
|
*/
|
|
@@ -30,7 +31,24 @@ export interface HealthCheckResult {
|
|
|
30
31
|
*/
|
|
31
32
|
export interface HealthCheckerOptions {
|
|
32
33
|
persistence?: PersistenceBackend | null;
|
|
34
|
+
/**
|
|
35
|
+
* Reports quarantine and unflushed-work counts. Its component is omitted while the source
|
|
36
|
+
* returns `null` (persistence disabled).
|
|
37
|
+
*/
|
|
38
|
+
persistenceBacklog?: PersistenceBacklogSource | null;
|
|
33
39
|
logger?: Logger;
|
|
40
|
+
/**
|
|
41
|
+
* Deadline for `persistence.healthy()`, in milliseconds. A probe that outlives it reports the
|
|
42
|
+
* persistence component unhealthy but keeps running; later checks join it instead of starting
|
|
43
|
+
* another.
|
|
44
|
+
* @default 1000
|
|
45
|
+
*/
|
|
46
|
+
probeTimeoutMs?: number;
|
|
47
|
+
/**
|
|
48
|
+
* How long a settled probe result is reused, in milliseconds. `0` probes on every call.
|
|
49
|
+
* @default 0
|
|
50
|
+
*/
|
|
51
|
+
probeFreshnessMs?: number;
|
|
34
52
|
}
|
|
35
53
|
/**
|
|
36
54
|
* Aggregates component health into liveness and readiness checks.
|
|
@@ -47,7 +65,13 @@ export interface HealthCheckerOptions {
|
|
|
47
65
|
*/
|
|
48
66
|
export declare class HealthChecker {
|
|
49
67
|
private _persistence;
|
|
68
|
+
private _backlog;
|
|
50
69
|
private _logger;
|
|
70
|
+
private readonly _probeTimeoutMs;
|
|
71
|
+
private readonly _probeFreshnessMs;
|
|
72
|
+
/** Verdict of the backend probe that has not settled yet, shared by every caller. */
|
|
73
|
+
private _inFlight;
|
|
74
|
+
private _settled;
|
|
51
75
|
constructor(options?: HealthCheckerOptions);
|
|
52
76
|
/**
|
|
53
77
|
* Liveness check — returns 'ok' if the process is alive.
|
|
@@ -63,11 +87,28 @@ export declare class HealthChecker {
|
|
|
63
87
|
* - 'ok' if all components are healthy (or no components registered)
|
|
64
88
|
* - 'degraded' if some components are unhealthy
|
|
65
89
|
* - 'unhealthy' if all components are unhealthy
|
|
90
|
+
*
|
|
91
|
+
* The persistence probe is bounded by `probeTimeoutMs`, shared between concurrent calls, and
|
|
92
|
+
* reused for `probeFreshnessMs` after it settles. The backlog component is read on every call.
|
|
66
93
|
*/
|
|
67
94
|
checkReadiness(): Promise<HealthCheckResult>;
|
|
68
95
|
/**
|
|
69
|
-
*
|
|
96
|
+
* Persistence component from the freshest source available: a settled result still inside
|
|
97
|
+
* the freshness window, else the probe already running (even past its deadline), else a new
|
|
98
|
+
* probe.
|
|
70
99
|
*/
|
|
71
100
|
private _checkPersistence;
|
|
101
|
+
/**
|
|
102
|
+
* Start one backend probe. The backend call is never abandoned: it stays tracked until it
|
|
103
|
+
* settles, while the returned verdict resolves at that point or at the deadline, whichever
|
|
104
|
+
* comes first.
|
|
105
|
+
*/
|
|
106
|
+
private _startProbe;
|
|
107
|
+
private _checkBacklog;
|
|
108
|
+
/**
|
|
109
|
+
* Probe the persistence backend with latency measurement. Never rejects: every failure,
|
|
110
|
+
* including a rejection that arrives after the deadline, becomes an unhealthy component.
|
|
111
|
+
*/
|
|
112
|
+
private _probeBackend;
|
|
72
113
|
}
|
|
73
114
|
//# sourceMappingURL=HealthChecker.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"HealthChecker.d.ts","sourceRoot":"","sources":["../../src/health/HealthChecker.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,+BAA+B,CAAC;AAC5D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,oCAAoC,CAAC;
|
|
1
|
+
{"version":3,"file":"HealthChecker.d.ts","sourceRoot":"","sources":["../../src/health/HealthChecker.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,+BAA+B,CAAC;AAC5D,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,oCAAoC,CAAC;AAC7E,OAAO,KAAK,EACX,wBAAwB,EAExB,MAAM,qCAAqC,CAAC;AAK7C;;GAEG;AACH,MAAM,WAAW,eAAe;IAC/B,IAAI,EAA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