@iworkforces/tracelattice 2.2.1 → 2.3.1
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 +6 -2
- package/dist/cli.js +10 -7
- package/dist/contracts/reasoning-types.d.ts +3 -3
- package/dist/contracts/reasoning-types.d.ts.map +1 -1
- package/dist/core/HistoryManager.d.ts +6 -1
- package/dist/core/HistoryManager.d.ts.map +1 -1
- package/dist/core/HistoryManager.js +38 -6
- 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/SessionErrors.d.ts +4 -0
- package/dist/core/SessionErrors.d.ts.map +1 -1
- package/dist/core/SessionErrors.js +9 -1
- package/dist/core/SessionErrors.js.map +1 -1
- package/dist/core/SessionResetCoordinator.d.ts +4 -0
- package/dist/core/SessionResetCoordinator.d.ts.map +1 -1
- package/dist/core/SessionResetCoordinator.js +6 -0
- package/dist/core/SessionResetCoordinator.js.map +1 -1
- package/dist/core/ThoughtEvaluator.d.ts +9 -2
- package/dist/core/ThoughtEvaluator.d.ts.map +1 -1
- package/dist/core/ThoughtEvaluator.js +9 -2
- package/dist/core/ThoughtEvaluator.js.map +1 -1
- package/dist/core/ThoughtProcessor.d.ts +1 -0
- package/dist/core/ThoughtProcessor.d.ts.map +1 -1
- package/dist/core/ThoughtProcessor.js +47 -20
- package/dist/core/ThoughtProcessor.js.map +1 -1
- package/dist/core/evaluator/GraphPatterns.d.ts +8 -0
- package/dist/core/evaluator/GraphPatterns.d.ts.map +1 -0
- package/dist/core/evaluator/GraphPatterns.js +88 -0
- package/dist/core/evaluator/GraphPatterns.js.map +1 -0
- package/dist/core/evaluator/GraphSignalComputer.d.ts +12 -0
- package/dist/core/evaluator/GraphSignalComputer.d.ts.map +1 -0
- package/dist/core/evaluator/GraphSignalComputer.js +17 -0
- package/dist/core/evaluator/GraphSignalComputer.js.map +1 -0
- package/dist/core/evaluator/PatternDetector.d.ts +4 -1
- package/dist/core/evaluator/PatternDetector.d.ts.map +1 -1
- package/dist/core/evaluator/PatternDetector.js +8 -2
- package/dist/core/evaluator/PatternDetector.js.map +1 -1
- package/dist/core/graph/EdgeEmitter.js +1 -1
- package/dist/core/graph/EdgeEmitter.js.map +1 -1
- package/dist/core/graph/GraphView.d.ts +60 -2
- package/dist/core/graph/GraphView.d.ts.map +1 -1
- package/dist/core/graph/GraphView.js +127 -11
- package/dist/core/graph/GraphView.js.map +1 -1
- package/dist/core/reasoning/GraphContext.d.ts +25 -0
- package/dist/core/reasoning/GraphContext.d.ts.map +1 -0
- package/dist/core/reasoning/GraphContext.js +32 -0
- package/dist/core/reasoning/GraphContext.js.map +1 -0
- package/dist/core/reasoning.d.ts +10 -0
- package/dist/core/reasoning.d.ts.map +1 -1
- package/dist/errors.d.ts +1 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +1 -0
- package/dist/errors.js.map +1 -1
- package/dist/persistence/FileSnapshotV2.d.ts +6 -6
- package/dist/schema.d.ts +3 -3
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +9 -7
- package/dist/schema.js.map +1 -1
- package/package.json +12 -12
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core/ThoughtEvaluator.js","sources":["../../src/core/ThoughtEvaluator.ts"],"sourcesContent":["/**\n * Quality signal computation for sequential thinking.\n *\n * Thin facade that composes the extracted evaluator submodules\n * ({@link SignalComputer}, {@link Aggregator}, {@link PatternDetector})\n * to preserve the original {@link ThoughtEvaluator} public API.\n *\n * @module core/ThoughtEvaluator\n */\n\nimport type { ICalibrator } from '../contracts/calibrator.js';\nimport type { SessionId, ThoughtId } from '../contracts/ids.js';\nimport type { ConfidenceSignals, PatternSignal, ReasoningStats } from './reasoning.js';\nimport type { ThoughtData } from './thought.js';\nimport { Aggregator } from './evaluator/Aggregator.js';\nimport { PatternDetector } from './evaluator/PatternDetector.js';\nimport { SignalComputer } from './evaluator/SignalComputer.js';\nimport { resolveVerificationLinks } from './evaluator/VerificationLinks.js';\n\nexport interface VerificationLinkContext {\n\treadonly verificationTargets?: ReadonlyMap<ThoughtId, ThoughtId>;\n}\n\n/** Explicit thought and canonical session used for response calibration. */\nexport interface ConfidenceSignalContext extends VerificationLinkContext {\n\treadonly currentThought: ThoughtData;\n\treadonly sessionId: SessionId;\n}\n\n/**\n * Stateless service that computes quality signals and reasoning analytics\n * from thought history and branch data.\n *\n * @remarks\n * All methods are pure computations — no side effects, no I/O, no internal state.\n * Designed to be registered as transient in the DI container.\n *\n * @example\n * ```typescript\n * const evaluator = new ThoughtEvaluator(calibrator);\n * const signals = evaluator.computeConfidenceSignals(history, branches, context);\n * const stats = evaluator.computeReasoningStats(history, branches);\n * const patterns = evaluator.computePatternSignals(history, branches);\n * ```\n */\nexport class ThoughtEvaluator {\n\tprivate readonly _signalComputer: SignalComputer;\n\tprivate readonly _aggregator: Aggregator;\n\tprivate readonly _patternDetector: PatternDetector;\n\tprivate readonly _calibrator: ICalibrator;\n\n\tconstructor(calibrator: ICalibrator) {\n\t\tthis._signalComputer = new SignalComputer();\n\t\tthis._aggregator = new Aggregator();\n\t\tthis._patternDetector = new PatternDetector();\n\t\tthis._calibrator = calibrator;\n\t}\n\n\t/** Compute confidence signals from history context. Pure computation. */\n\tpublic computeConfidenceSignals(\n\t\thistory: ThoughtData[],\n\t\tbranches: Record<string, ThoughtData[]>,\n\t\tcontext: ConfidenceSignalContext\n\t): ConfidenceSignals {\n\t\tconst links = resolveVerificationLinks(history, branches, context.verificationTargets);\n\t\tconst { branches: b } = filterRetracted(history, branches);\n\t\tconst
|
|
1
|
+
{"version":3,"file":"core/ThoughtEvaluator.js","sources":["../../src/core/ThoughtEvaluator.ts"],"sourcesContent":["/**\n * Quality signal computation for sequential thinking.\n *\n * Thin facade that composes the extracted evaluator submodules\n * ({@link SignalComputer}, {@link Aggregator}, {@link PatternDetector})\n * to preserve the original {@link ThoughtEvaluator} public API.\n *\n * @module core/ThoughtEvaluator\n */\n\nimport type { ICalibrator } from '../contracts/calibrator.js';\nimport type { SessionId, ThoughtId } from '../contracts/ids.js';\nimport type { ConfidenceSignals, PatternSignal, ReasoningStats } from './reasoning.js';\nimport type { ThoughtData } from './thought.js';\nimport { Aggregator } from './evaluator/Aggregator.js';\nimport { PatternDetector } from './evaluator/PatternDetector.js';\nimport { SignalComputer } from './evaluator/SignalComputer.js';\nimport { resolveVerificationLinks } from './evaluator/VerificationLinks.js';\nimport { GraphSignalComputer } from './evaluator/GraphSignalComputer.js';\nimport type { ActiveGraphContext } from './evaluator/GraphSignalComputer.js';\n\nexport interface VerificationLinkContext {\n\treadonly verificationTargets?: ReadonlyMap<ThoughtId, ThoughtId>;\n}\n\n/** Explicit thought and canonical session used for response calibration. */\nexport interface GraphAwareContext {\n\treadonly activeGraph?: ActiveGraphContext;\n}\n\nexport interface PatternSignalContext extends VerificationLinkContext, GraphAwareContext {}\n\nexport interface ConfidenceSignalContext extends VerificationLinkContext, GraphAwareContext {\n\treadonly currentThought: ThoughtData;\n\treadonly sessionId: SessionId;\n}\n\n/**\n * Stateless service that computes quality signals and reasoning analytics\n * from thought history and branch data.\n *\n * @remarks\n * All methods are pure computations — no side effects, no I/O, no internal state.\n * Designed to be registered as transient in the DI container.\n *\n * @example\n * ```typescript\n * const evaluator = new ThoughtEvaluator(calibrator);\n * const signals = evaluator.computeConfidenceSignals(history, branches, context);\n * const stats = evaluator.computeReasoningStats(history, branches);\n * const patterns = evaluator.computePatternSignals(history, branches);\n * ```\n */\nexport class ThoughtEvaluator {\n\tprivate readonly _signalComputer: SignalComputer;\n\tprivate readonly _aggregator: Aggregator;\n\tprivate readonly _patternDetector: PatternDetector;\n\tprivate readonly _calibrator: ICalibrator;\n\tprivate readonly _graphSignalComputer = new GraphSignalComputer();\n\n\tconstructor(calibrator: ICalibrator) {\n\t\tthis._signalComputer = new SignalComputer();\n\t\tthis._aggregator = new Aggregator();\n\t\tthis._patternDetector = new PatternDetector();\n\t\tthis._calibrator = calibrator;\n\t}\n\n\t/** Compute confidence signals from history context. Pure computation. */\n\tpublic computeConfidenceSignals(\n\t\thistory: ThoughtData[],\n\t\tbranches: Record<string, ThoughtData[]>,\n\t\tcontext: ConfidenceSignalContext\n\t): ConfidenceSignals {\n\t\tconst links = resolveVerificationLinks(history, branches, context.verificationTargets);\n\t\tconst { branches: b } = filterRetracted(history, branches);\n\t\tconst baseSignals = this._signalComputer.computeConfidenceSignals(\n\t\t\t[...links.thoughts],\n\t\t\tb,\n\t\t\tlinks\n\t\t);\n\t\tconst graphSignals =\n\t\t\tcontext.activeGraph === undefined\n\t\t\t\t? undefined\n\t\t\t\t: this._graphSignalComputer.compute(context.activeGraph);\n\t\tconst signals =\n\t\t\tgraphSignals === undefined ? baseSignals : { ...baseSignals, graph_signals: graphSignals };\n\t\tif (!this._calibrator.enabled) return signals;\n\n\t\tconst thought = context.currentThought;\n\t\tif (thought.confidence === undefined) return signals;\n\t\tconst sessionId = context.sessionId;\n\n\t\tconst result = this._calibrator.calibrate(\n\t\t\tthought.confidence,\n\t\t\tthought.thought_type ?? 'regular',\n\t\t\tsessionId\n\t\t);\n\t\treturn {\n\t\t\t...signals,\n\t\t\tcalibrated_confidence: result.calibrated,\n\t\t\tcalibration_metrics: this._calibrator.metrics(sessionId),\n\t\t};\n\t}\n\n\t/** Compute aggregated reasoning analytics. Pure computation. */\n\tpublic computeReasoningStats(\n\t\thistory: ThoughtData[],\n\t\tbranches: Record<string, ThoughtData[]>,\n\t\tcontext: VerificationLinkContext = {}\n\t): ReasoningStats {\n\t\tconst links = resolveVerificationLinks(history, branches, context.verificationTargets);\n\t\tconst { branches: b } = filterRetracted(history, branches);\n\t\treturn this._aggregator.computeReasoningStats([...links.thoughts], b, links);\n\t}\n\n\t/** Detect reasoning patterns (anti-patterns and positive signals). Pure computation. */\n\tpublic computePatternSignals(\n\t\thistory: ThoughtData[],\n\t\tbranches: Record<string, ThoughtData[]>,\n\t\tcontext: PatternSignalContext = {}\n\t): PatternSignal[] {\n\t\tconst { history: h, branches: b } = filterRetracted(history, branches);\n\t\tconst links = resolveVerificationLinks(history, branches, context.verificationTargets);\n\t\treturn this._patternDetector.computePatternSignals(h, b, links, context.activeGraph);\n\t}\n}\n\n/**\n * Filters out logically retracted thoughts from history and branches.\n * Retracted thoughts remain in storage (event-sourcing) but are excluded\n * from quality signal calculations.\n */\nfunction filterRetracted(\n\thistory: ThoughtData[],\n\tbranches: Record<string, ThoughtData[]>\n): { history: ThoughtData[]; branches: Record<string, ThoughtData[]> } {\n\tconst h = history.filter((t) => !t.retracted);\n\tconst b: Record<string, ThoughtData[]> = {};\n\tfor (const [id, list] of Object.entries(branches)) {\n\t\tb[id] = list.filter((t) => !t.retracted);\n\t}\n\treturn { history: h, branches: b };\n}\n"],"names":["ThoughtEvaluator","GraphSignalComputer","calibrator","SignalComputer","Aggregator","PatternDetector","history","branches","context","links","resolveVerificationLinks","b","filterRetracted","baseSignals","graphSignals","undefined","signals","thought","sessionId","result","h","t","id","list","Object"],"mappings":";;;;;AAqDO,MAAMA;IACK,gBAAgC;IAChC,YAAwB;IACxB,iBAAkC;IAClC,YAAyB;IACzB,uBAAuB,IAAIC,sBAAsB;IAElE,YAAYC,UAAuB,CAAE;QACpC,IAAI,CAAC,eAAe,GAAG,IAAIC;QAC3B,IAAI,CAAC,WAAW,GAAG,IAAIC;QACvB,IAAI,CAAC,gBAAgB,GAAG,IAAIC;QAC5B,IAAI,CAAC,WAAW,GAAGH;IACpB;IAGO,yBACNI,OAAsB,EACtBC,QAAuC,EACvCC,OAAgC,EACZ;QACpB,MAAMC,QAAQC,yBAAyBJ,SAASC,UAAUC,QAAQ,mBAAmB;QACrF,MAAM,EAAE,UAAUG,CAAC,EAAE,GAAGC,gBAAgBN,SAASC;QACjD,MAAMM,cAAc,IAAI,CAAC,eAAe,CAAC,wBAAwB,CAChE;eAAIJ,MAAM,QAAQ;SAAC,EACnBE,GACAF;QAED,MAAMK,eACLN,AA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MAAMa,IAAId,QAAQ,MAAM,CAAC,CAACe,IAAM,CAACA,EAAE,SAAS;IAC5C,MAAMV,IAAmC,CAAC;IAC1C,KAAK,MAAM,CAACW,IAAIC,KAAK,IAAIC,OAAO,OAAO,CAACjB,UACvCI,CAAC,CAACW,GAAG,GAAGC,KAAK,MAAM,CAAC,CAACF,IAAM,CAACA,EAAE,SAAS;IAExC,OAAO;QAAE,SAASD;QAAG,UAAUT;IAAE;AAClC"}
|
|
@@ -192,6 +192,7 @@ export declare class ThoughtProcessor {
|
|
|
192
192
|
private _processInner;
|
|
193
193
|
private _recordVerificationOutcome;
|
|
194
194
|
private _collectReasoningSignals;
|
|
195
|
+
private _buildActiveEvidence;
|
|
195
196
|
private _buildSuccessResponse;
|
|
196
197
|
/**
|
|
197
198
|
* Run the configured reasoning strategy and return its decision.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ThoughtProcessor.d.ts","sourceRoot":"","sources":["../../src/core/ThoughtProcessor.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAKH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,+BAA+B,CAAC;AAC5D,OAAO,EAIN,KAAK,SAAS,EAEd,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAc,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAC/E,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,KAAK,EAAE,gBAAgB,EAAoB,MAAM,4BAA4B,CAAC;AACrF,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"ThoughtProcessor.d.ts","sourceRoot":"","sources":["../../src/core/ThoughtProcessor.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAKH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,+BAA+B,CAAC;AAC5D,OAAO,EAIN,KAAK,SAAS,EAEd,MAAM,qBAAqB,CAAC;AAC7B,OAAO,KAAK,EAAc,gBAAgB,EA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;IAC/D,YAAY,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAiB3D,qFAAqF;IACxE,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;IAOtC,OAAO,CAAC,aAAa;IA+BrB,OAAO,CAAC,mBAAmB;IAqB3B,OAAO,CAAC,MAAM,CAAC,qBAAqB;IAWpC,gEAAgE;IACzD,0BAA0B,CAAC,SAAS,EAAE,SAAS,GAAG,IAAI;IAO7D,kFAAkF;IAC3E,sBAAsB,IAAI,IAAI;IAOrC,OAAO,CAAC,2BAA2B;YAWrB,aAAa;IAiG3B,OAAO,CAAC,0BAA0B;IAWlC,OAAO,CAAC,wBAAwB;IA+BhC,OAAO,CAAC,oBAAoB;IAqB5B,OAAO,CAAC,qBAAqB;IA0C7B;;;;OAIG;IACH,OAAO,CAAC,YAAY;IAyCpB;;;;;OAKG;IACH,OAAO,CAAC,eAAe;IAavB,yDAAyD;IACzD,OAAO,CAAC,aAAa;IAIrB;;;;;;;;;;;;;;;;;;OAkBG;IACH,OAAO,CAAC,aAAa;IAoBrB;;;OAGG;IACH,OAAO,CAAC,0BAA0B;IAoDlC,OAAO,CAAC,iBAAiB;IAIzB;;;;;;;;;OASG;IACH,OAAO,CAAC,iBAAiB;IAYzB;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,kBAAkB;IAajC;;;;OAIG;IACH,OAAO,CAAC,eAAe;IA0CvB;;;OAGG;YACW,sBAAsB;CAkBpC"}
|
|
@@ -6,6 +6,7 @@ import { JsonShapeError, enforceJsonShape } from "../sanitize.js";
|
|
|
6
6
|
import { SequentialThinkingSchema } from "../schema.js";
|
|
7
7
|
import { GraphView } from "./graph/GraphView.js";
|
|
8
8
|
import { buildActiveEvidenceProjection } from "./reasoning/ActiveEvidenceProjection.js";
|
|
9
|
+
import { buildGraphContext } from "./reasoning/GraphContext.js";
|
|
9
10
|
import { assertNever } from "../utils.js";
|
|
10
11
|
import { normalizeInput } from "./InputNormalizer.js";
|
|
11
12
|
import { SequentialStrategy } from "./reasoning/strategies/SequentialStrategy.js";
|
|
@@ -47,10 +48,12 @@ class ThoughtProcessor {
|
|
|
47
48
|
this._logger.info(message, meta);
|
|
48
49
|
}
|
|
49
50
|
static _HINT_PRIORITY = {
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
51
|
+
refuted_hypothesis_dependency: 1,
|
|
52
|
+
confidence_drift: 2,
|
|
53
|
+
unverified_hypothesis: 3,
|
|
54
|
+
unaddressed_critique: 4,
|
|
55
|
+
no_alternatives_explored: 5,
|
|
56
|
+
consecutive_without_verification: 6
|
|
54
57
|
};
|
|
55
58
|
_generateHints(patterns, currentThoughtNumber, sessionId) {
|
|
56
59
|
const warnings = patterns.filter((p)=>'warning' === p.severity);
|
|
@@ -85,9 +88,10 @@ class ThoughtProcessor {
|
|
|
85
88
|
return await this._processInner(prepared);
|
|
86
89
|
};
|
|
87
90
|
if (prepared.resetState) {
|
|
88
|
-
this.historyManager.
|
|
91
|
+
this.historyManager.assertSessionResetAuthorized(sessionId);
|
|
89
92
|
return await this._lifecycle.withSessionReset(sessionId, operation);
|
|
90
93
|
}
|
|
94
|
+
this.historyManager.inspectSession(sessionId);
|
|
91
95
|
return await this._lifecycle.runOperation(sessionId, operation);
|
|
92
96
|
} catch (error) {
|
|
93
97
|
return this._buildErrorResponse(error);
|
|
@@ -95,7 +99,7 @@ class ThoughtProcessor {
|
|
|
95
99
|
}
|
|
96
100
|
async resetSession(sessionId) {
|
|
97
101
|
const canonicalSessionId = asSessionId(sessionId);
|
|
98
|
-
this.historyManager.
|
|
102
|
+
this.historyManager.assertSessionResetAuthorized(canonicalSessionId);
|
|
99
103
|
const operation = async ()=>{
|
|
100
104
|
await this.historyManager.resetSessionWithinExclusive(canonicalSessionId, ()=>this.clearSessionAuxiliaryState(canonicalSessionId));
|
|
101
105
|
};
|
|
@@ -182,8 +186,8 @@ class ThoughtProcessor {
|
|
|
182
186
|
async _processInner(prepared) {
|
|
183
187
|
const { thought, resetState, registerBranchId } = prepared;
|
|
184
188
|
const sessionId = thought.session_id;
|
|
185
|
-
|
|
186
|
-
const validationSnapshot = resetState ? ThoughtProcessor._emptySessionSnapshot() :
|
|
189
|
+
if (resetState) this.historyManager.assertSessionResetAuthorized(sessionId);
|
|
190
|
+
const validationSnapshot = resetState ? ThoughtProcessor._emptySessionSnapshot() : this.historyManager.inspectSession(sessionId);
|
|
187
191
|
if (!resetState) {
|
|
188
192
|
if (!thought.available_mcp_tools && validationSnapshot.availableMcpTools) thought.available_mcp_tools = [
|
|
189
193
|
...validationSnapshot.availableMcpTools
|
|
@@ -234,12 +238,13 @@ class ThoughtProcessor {
|
|
|
234
238
|
sessionId
|
|
235
239
|
});
|
|
236
240
|
const signals = this._collectReasoningSignals(checkedInput);
|
|
237
|
-
const decision = this._runStrategy(checkedInput, signals.
|
|
241
|
+
const decision = this._runStrategy(checkedInput, signals.evidence, signals.reasoningStats);
|
|
238
242
|
return this._buildSuccessResponse({
|
|
239
243
|
thought: checkedInput,
|
|
240
244
|
reasoning: {
|
|
241
245
|
confidenceSignals: signals.confidenceSignals,
|
|
242
246
|
reasoningStats: signals.reasoningStats,
|
|
247
|
+
graphContext: void 0 === signals.evidence ? void 0 : buildGraphContext(sessionId, checkedInput, signals.evidence),
|
|
243
248
|
reasoningHints: signals.reasoningHints
|
|
244
249
|
},
|
|
245
250
|
decision,
|
|
@@ -255,26 +260,51 @@ class ThoughtProcessor {
|
|
|
255
260
|
const sessionId = input.session_id;
|
|
256
261
|
const history = this.historyManager.getHistory(sessionId);
|
|
257
262
|
const branches = this.historyManager.getBranches(sessionId);
|
|
263
|
+
const evidence = this._buildActiveEvidence(sessionId, history, branches);
|
|
264
|
+
const graphScope = evidence?.graph === void 0 ? {} : {
|
|
265
|
+
activeGraph: {
|
|
266
|
+
sessionId,
|
|
267
|
+
view: evidence.graph
|
|
268
|
+
}
|
|
269
|
+
};
|
|
258
270
|
const verificationTargets = this.historyManager.inspectSession(sessionId).verificationTargets;
|
|
259
271
|
const confidenceSignals = this._thoughtEvaluator.computeConfidenceSignals(history, branches, {
|
|
260
272
|
currentThought: input,
|
|
261
273
|
sessionId,
|
|
262
|
-
verificationTargets
|
|
274
|
+
verificationTargets,
|
|
275
|
+
...graphScope
|
|
263
276
|
});
|
|
264
277
|
const reasoningStats = this._thoughtEvaluator.computeReasoningStats(history, branches, {
|
|
265
278
|
verificationTargets
|
|
266
279
|
});
|
|
267
280
|
const patternSignals = this._thoughtEvaluator.computePatternSignals(history, branches, {
|
|
268
|
-
verificationTargets
|
|
281
|
+
verificationTargets,
|
|
282
|
+
...graphScope
|
|
269
283
|
});
|
|
270
284
|
const reasoningHints = this._generateHints(patternSignals, input.thought_number, sessionId);
|
|
271
285
|
return {
|
|
272
|
-
|
|
286
|
+
evidence,
|
|
273
287
|
confidenceSignals,
|
|
274
288
|
reasoningStats,
|
|
275
289
|
reasoningHints
|
|
276
290
|
};
|
|
277
291
|
}
|
|
292
|
+
_buildActiveEvidence(sessionId, history, branches) {
|
|
293
|
+
try {
|
|
294
|
+
return buildActiveEvidenceProjection({
|
|
295
|
+
sessionId,
|
|
296
|
+
history,
|
|
297
|
+
branches,
|
|
298
|
+
edgeStore: this._getEdgeStore()
|
|
299
|
+
});
|
|
300
|
+
} catch (error) {
|
|
301
|
+
this._logger.warn('Active evidence projection failed — omitting graph and strategy hints', {
|
|
302
|
+
sessionId,
|
|
303
|
+
error: getErrorMessage(error)
|
|
304
|
+
});
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
}
|
|
278
308
|
_buildSuccessResponse(state) {
|
|
279
309
|
const sessionId = state.thought.session_id;
|
|
280
310
|
return {
|
|
@@ -298,6 +328,9 @@ class ThoughtProcessor {
|
|
|
298
328
|
hypothesis_id: state.thought.hypothesis_id,
|
|
299
329
|
confidence_signals: state.reasoning.confidenceSignals,
|
|
300
330
|
reasoning_stats: state.reasoning.reasoningStats,
|
|
331
|
+
...void 0 !== state.reasoning.graphContext && {
|
|
332
|
+
graph_context: state.reasoning.graphContext
|
|
333
|
+
},
|
|
301
334
|
...state.reasoning.reasoningHints.length > 0 && {
|
|
302
335
|
reasoning_hints: state.reasoning.reasoningHints
|
|
303
336
|
},
|
|
@@ -313,17 +346,11 @@ class ThoughtProcessor {
|
|
|
313
346
|
]
|
|
314
347
|
};
|
|
315
348
|
}
|
|
316
|
-
_runStrategy(currentThought,
|
|
349
|
+
_runStrategy(currentThought, evidence, stats) {
|
|
317
350
|
const sessionId = currentThought.session_id;
|
|
318
351
|
let decision;
|
|
319
352
|
try {
|
|
320
|
-
|
|
321
|
-
sessionId,
|
|
322
|
-
history,
|
|
323
|
-
branches: this.historyManager.getBranches(sessionId),
|
|
324
|
-
edgeStore: this._getEdgeStore()
|
|
325
|
-
});
|
|
326
|
-
decision = this.strategy.decide({
|
|
353
|
+
if (void 0 !== evidence) decision = this.strategy.decide({
|
|
327
354
|
sessionId,
|
|
328
355
|
evidence,
|
|
329
356
|
stats,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core/ThoughtProcessor.js","sources":["../../src/core/ThoughtProcessor.ts"],"sourcesContent":["/**\n * Core thought processing logic and validation.\n *\n * This module provides the `ThoughtProcessor` class which handles the main\n * sequential thinking request processing pipeline, including input validation,\n * history management, and response formatting.\n *\n * @module processor\n */\n\nimport * as v from 'valibot';\n\nimport { NullLogger } from '../logger/NullLogger.js';\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport {\n\tasBranchId,\n\tasSessionId,\n\ttype BranchId,\n\ttype SessionId,\n\ttype ThoughtId,\n} from '../contracts/ids.js';\nimport type { IEdgeStore, IOutcomeRecorder } from '../contracts/interfaces.js';\nimport type { ICalibrator } from '../contracts/calibrator.js';\nimport type { ISuspensionStore, SuspensionRecord } from '../contracts/suspension.js';\nimport type { IReasoningStrategy, StrategyDecision } from '../contracts/strategy.js';\nimport { DEFAULT_FLAGS, type FeatureFlags } from '../contracts/features.js';\nimport type { ISessionLock, IToolRegistry } from '../contracts/interfaces.js';\nimport {\n\tInvalidBacktrackError,\n\tInvalidToolCallError,\n\tSequentialThinkingError,\n\tUnknownToolError,\n\tValidationError,\n} from '../errors.js';\nimport { getErrorMessage, WARNING_CODES } from '../errors.js';\nimport { enforceJsonShape, JsonShapeError } from '../sanitize.js';\nimport { SequentialThinkingSchema } from '../schema.js';\nimport { GraphView } from './graph/GraphView.js';\nimport { buildActiveEvidenceProjection } from './reasoning/ActiveEvidenceProjection.js';\nimport { assertNever } from '../utils.js';\nimport type {\n\tHistorySessionSnapshot,\n\tIHistoryManager,\n\tThoughtAdmissionContext,\n} from './IHistoryManager.js';\nimport { normalizeInput } from './InputNormalizer.js';\nimport type {\n\tThoughtData,\n\tToolCallThought,\n\tToolObservationThought,\n\tValidatedThought,\n} from './thought.js';\nimport type { ThoughtEvaluator } from './ThoughtEvaluator.js';\nimport type { ThoughtFormatter } from './ThoughtFormatter.js';\nimport type { PatternName } from '../contracts/reasoning-types.js';\nimport type { PatternSignal } from './reasoning.js';\nimport { SequentialStrategy } from './reasoning/strategies/SequentialStrategy.js';\nimport type { CompressionService } from './compression/CompressionService.js';\nimport { validateThoughtCrossReferences } from './CrossReferenceValidator.js';\nimport { SessionLifecycleCoordinator } from './SessionLifecycleCoordinator.js';\nimport { prepareVerificationOutcome } from './VerificationOutcomeAdmission.js';\n\ntype ConfidenceSignalsResult = ReturnType<ThoughtEvaluator['computeConfidenceSignals']>;\ntype ReasoningStatsResult = ReturnType<ThoughtEvaluator['computeReasoningStats']>;\n\ntype ReasoningSignalBundle = {\n\treadonly history: ThoughtData[];\n\treadonly confidenceSignals: ConfidenceSignalsResult;\n\treadonly reasoningStats: ReasoningStatsResult;\n\treadonly reasoningHints: readonly string[];\n};\n\ntype ProcessedThoughtResponseState = {\n\treadonly thought: ThoughtData;\n\treadonly reasoning: {\n\t\treadonly confidenceSignals: ConfidenceSignalsResult;\n\t\treadonly reasoningStats: ReasoningStatsResult;\n\t\treadonly reasoningHints: readonly string[];\n\t};\n\treadonly decision: StrategyDecision | undefined;\n\treadonly warnings: readonly string[];\n};\n\ntype ThoughtProcessInput = ThoughtData & { readonly register_branch_id?: string };\n\ntype PreparedThought = {\n\treadonly thought: ThoughtData;\n\treadonly resetState: boolean;\n\treadonly registerBranchId: BranchId | undefined;\n\treadonly validationWarnings: readonly string[];\n};\n\n/**\n * The return type expected by MCP tool invocations.\n *\n * This structure matches the MCP protocol for tool results,\n * supporting both success and error responses.\n *\n * @example\n * ```typescript\n * const successResult: CallToolResult = {\n * content: [{ type: 'text', text: '{\"status\":\"success\"}' }]\n * };\n *\n * const errorResult: CallToolResult = {\n * content: [{ type: 'text', text: '{\"error\":\"Something went wrong\"}' }],\n * isError: true\n * };\n * ```\n */\nexport interface CallToolResult extends Record<string, unknown> {\n\t/** Array of content blocks (typically text) to return to the client. */\n\tcontent: Array<{\n\t\ttype: 'text';\n\t\ttext: string;\n\t}>;\n\n\t/** Whether this result represents an error condition. */\n\tisError?: boolean;\n}\n\n/**\n * Core processor for sequential thinking requests.\n *\n * Pipeline: validate → normalize → add to history → format → evaluate signals\n * → run reasoning strategy → return structured response.\n *\n * Auto-adjusts `total_thoughts` if `thought_number` exceeds it. All errors are\n * caught and returned as formatted error responses with `isError: true`.\n *\n * @example\n * ```typescript\n * const processor = new ThoughtProcessor(historyManager, formatter, new ThoughtEvaluator());\n * const result = await processor.process({\n * thought: '...',\n * thought_number: 1,\n * total_thoughts: 5,\n * next_thought_needed: true,\n * session_id: asSessionId('analysis')\n * });\n * ```\n */\nexport class ThoughtProcessor {\n\t/** Logger for debugging and monitoring. */\n\tprivate _logger: Logger;\n\n\t/** Evaluator for quality signal computation. */\n\tprivate readonly _thoughtEvaluator: ThoughtEvaluator;\n\n\t/**\n\t * Per-session cooldown tracker: session_id → pattern → last_fired_thought_number.\n\t * Prevents re-firing the same pattern hint within 3 thoughts.\n\t */\n\tprivate _hintCooldowns = new Map<SessionId, Map<PatternName, number>>();\n\n\t/**\n\t * Creates a new ThoughtProcessor instance.\n\t *\n\t * @param historyManager - History manager for storing thoughts\n\t * @param thoughtFormatter - Formatter for output formatting\n\t * @param thoughtEvaluator - Evaluator for quality signal computation\n\t * @param logger - Optional logger for diagnostics (defaults to NullLogger)\n\t * @param strategy - Reasoning strategy controlling next-action decisions (defaults to SequentialStrategy)\n\t * @param compressionService - Optional compression service for auto-compression on terminate\n\t * @param suspensionStore - Optional suspension store enabling tool interleave\n\t * @param toolRegistry - Optional tool registry for tool_name allowlist validation (required when toolInterleave is enabled)\n\t * @param features - Optional feature flags (defaults to DEFAULT_FLAGS — all opt-in flags off)\n\t * @param sessionLock - Optional per-session async lock; when provided, `process()` runs under it\n\t * @param outcomeRecorder - Optional per-session calibration outcome store\n\t */\n\tconstructor(\n\t\tprivate historyManager: IHistoryManager,\n\t\tprivate thoughtFormatter: ThoughtFormatter,\n\t\tthoughtEvaluator: ThoughtEvaluator,\n\t\tlogger?: Logger,\n\t\tprivate readonly strategy: IReasoningStrategy = new SequentialStrategy(),\n\t\tprivate readonly _compressionService?: CompressionService,\n\t\tprivate readonly _suspensionStore?: ISuspensionStore,\n\t\tprivate readonly _toolRegistry?: IToolRegistry,\n\t\tprivate readonly _features: FeatureFlags = DEFAULT_FLAGS,\n\t\tprivate readonly _sessionLock?: ISessionLock,\n\t\tprivate readonly _outcomeRecorder?: IOutcomeRecorder,\n\t\tprivate readonly _lifecycle: SessionLifecycleCoordinator = new SessionLifecycleCoordinator(),\n\t\tprivate readonly _calibrator?: ICalibrator\n\t) {\n\t\tthis._thoughtEvaluator = thoughtEvaluator;\n\t\tthis._logger = logger ?? new NullLogger();\n\t}\n\n\t/**\n\t * Internal logging method.\n\t * @param message - The message to log\n\t * @param meta - Optional metadata\n\t * @private\n\t */\n\tprivate log(message: string, meta?: Record<string, unknown>): void {\n\t\tthis._logger.info(message, meta);\n\t}\n\n\t/**\n\t * Priority ordering for warning patterns (lower = higher priority).\n\t * Ensures the most actionable patterns fill the hint cap first.\n\t */\n\tprivate static readonly _HINT_PRIORITY: Readonly<Partial<Record<PatternName, number>>> = {\n\t\tconfidence_drift: 1, // Most actionable — degrading confidence\n\t\tunverified_hypothesis: 2, // Important for quality\n\t\tno_alternatives_explored: 3, // Breadth gap\n\t\tconsecutive_without_verification: 4, // Routine pattern\n\t};\n\n\t/**\n\t * Generate actionable hints from pattern signals.\n\t * Rules: max 3 hints, warning-severity only, cooldown of 3 thoughts per pattern per session.\n\t *\n\t * Warning patterns are sorted by priority before selection (see _HINT_PRIORITY).\n\t * Higher-priority patterns (lower number) fill the hint cap first.\n\t *\n\t * @param patterns - Detected pattern signals\n\t * @param currentThoughtNumber - The current thought number being processed\n\t * @param sessionId - Session identifier for cooldown scoping\n\t * @returns Array of hint strings (max 3), empty if no warnings\n\t */\n\tprivate _generateHints(\n\t\tpatterns: PatternSignal[],\n\t\tcurrentThoughtNumber: number,\n\t\tsessionId: SessionId\n\t): string[] {\n\t\tconst warnings = patterns.filter((p) => p.severity === 'warning');\n\t\tif (warnings.length === 0) return [];\n\n\t\t// Sort by priority (lower number = higher priority)\n\t\twarnings.sort((a, b) => {\n\t\t\tconst pa = ThoughtProcessor._HINT_PRIORITY[a.pattern] ?? 99;\n\t\t\tconst pb = ThoughtProcessor._HINT_PRIORITY[b.pattern] ?? 99;\n\t\t\treturn pa - pb;\n\t\t});\n\n\t\tlet cooldowns = this._hintCooldowns.get(sessionId);\n\t\tif (cooldowns === undefined) {\n\t\t\tcooldowns = new Map();\n\t\t\tthis._hintCooldowns.set(sessionId, cooldowns);\n\t\t}\n\n\t\tconst hints: string[] = [];\n\t\tfor (const warning of warnings) {\n\t\t\tif (hints.length >= 3) break;\n\n\t\t\tconst lastFired = cooldowns.get(warning.pattern);\n\t\t\tif (lastFired !== undefined && currentThoughtNumber - lastFired < 3) {\n\t\t\t\tcontinue; // Still in cooldown\n\t\t\t}\n\n\t\t\thints.push(warning.message);\n\t\t\tcooldowns.set(warning.pattern, currentThoughtNumber);\n\t\t}\n\n\t\treturn hints;\n\t}\n\n\t/**\n\t * Processes a thought through the sequential thinking pipeline.\n\t *\n\t * This method validates the input, adds it to history, formats the output,\n\t * computes quality signals via the ThoughtEvaluator, and returns\n\t * a structured response with metadata about the current state.\n\t *\n\t * @param input - The thought data to process\n\t * @returns A Promise resolving to the formatted tool result containing:\n\t * - `thought_number` — Current thought index\n\t * - `total_thoughts` — Estimated total thoughts\n\t * - `next_thought_needed` — Whether to continue\n\t * - `branches` — Active branch IDs\n\t * - `thought_history_length` — Number of thoughts in history\n\t * - `available_mcp_tools` — MCP tools available for recommendation\n\t * - `available_skills` — Skills available for recommendation\n\t * - `current_step` — Current step recommendation\n\t * - `previous_steps` — Previously recommended steps\n\t * - `remaining_steps` — Upcoming step descriptions\n\t * - `thought_type` — Classification of thought purpose (optional)\n\t * - `quality_score` — Self-assessed quality score 0-1 (optional)\n\t * - `confidence` — Self-assessed confidence 0-1 (optional)\n\t * - `hypothesis_id` — Hypothesis link for verification chains (optional)\n\t * - `confidence_signals` — Computed reasoning quality signals (includes structural_quality and quality_components)\n\t * - `reasoning_stats` — Aggregated reasoning analytics\n\t * - `reasoning_hints` — (Conditional) Actionable hints from pattern analysis, max 3, warning-severity only (optional)\n\t *\n\t * @example\n\t * ```typescript\n\t * const result = await processor.process({\n\t * thought: 'I should read the README file',\n\t * thought_number: 1,\n\t * total_thoughts: 3,\n\t * next_thought_needed: true,\n\t * session_id: asSessionId('analysis')\n\t * });\n\t *\n\t * console.log(result.content[0].text);\n\t * // Output includes: thought_number, total_thoughts, next_thought_needed,\n\t * // branches, thought_history_length, and any recommendations\n\t * ```\n\t */\n\tpublic async process(input: ThoughtProcessInput): Promise<CallToolResult> {\n\t\ttry {\n\t\t\tconst prepared = this._prepareInput(input);\n\t\t\tconst sessionId = prepared.thought.session_id;\n\t\t\tconst operation = async (): Promise<CallToolResult> => {\n\t\t\t\tif (this._sessionLock !== undefined) {\n\t\t\t\t\treturn await this._sessionLock.withLock(sessionId, () => this._processInner(prepared));\n\t\t\t\t}\n\t\t\t\treturn await this._processInner(prepared);\n\t\t\t};\n\t\t\tif (prepared.resetState) {\n\t\t\t\tthis.historyManager.inspectSession(sessionId);\n\t\t\t\treturn await this._lifecycle.withSessionReset(sessionId, operation);\n\t\t\t}\n\t\t\treturn await this._lifecycle.runOperation(sessionId, operation);\n\t\t} catch (error) {\n\t\t\treturn this._buildErrorResponse(error);\n\t\t}\n\t}\n\n\t/** Resets one canonical session and its processor-owned auxiliary state. */\n\tpublic async resetSession(sessionId: string): Promise<void> {\n\t\tconst canonicalSessionId = asSessionId(sessionId);\n\t\tthis.historyManager.inspectSession(canonicalSessionId);\n\t\tconst operation = async (): Promise<void> => {\n\t\t\tawait this.historyManager.resetSessionWithinExclusive(canonicalSessionId, () =>\n\t\t\t\tthis.clearSessionAuxiliaryState(canonicalSessionId)\n\t\t\t);\n\t\t};\n\t\tawait this._lifecycle.withSessionReset(canonicalSessionId, async () => {\n\t\t\tif (this._sessionLock !== undefined) {\n\t\t\t\tawait this._sessionLock.withLock(canonicalSessionId, operation);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait operation();\n\t\t});\n\t}\n\n\t/** Resets all history and processor-owned auxiliary state from a trusted context. */\n\tpublic async resetAll(): Promise<void> {\n\t\tawait this._lifecycle.withGlobalReset(\n\t\t\tasync () =>\n\t\t\t\tawait this.historyManager.resetAllWithinExclusive(() => this.clearAllAuxiliaryState())\n\t\t);\n\t}\n\n\tprivate _prepareInput(input: ThoughtProcessInput): PreparedThought {\n\t\tconst normalized = normalizeInput(input);\n\t\tif (typeof normalized === 'object' && normalized !== null) {\n\t\t\tthis._validateToolArgumentsShape(normalized.tool_arguments);\n\t\t}\n\t\tconst parsed = v.safeParse(SequentialThinkingSchema, normalized);\n\t\tif (!parsed.success) {\n\t\t\tconst firstIssue = parsed.issues[0];\n\t\t\tconst field = firstIssue?.path?.map((item) => String(item.key)).join('.') || 'input';\n\t\t\tthrow new ValidationError(field, firstIssue?.message ?? 'Invalid input');\n\t\t}\n\n\t\tconst internal = normalizeInput(parsed.output) as ThoughtData & {\n\t\t\tregister_branch_id?: string;\n\t\t};\n\t\tconst registerBranchId =\n\t\t\tinternal.register_branch_id === undefined\n\t\t\t\t? undefined\n\t\t\t\t: asBranchId(internal.register_branch_id);\n\t\tconst thought = { ...internal };\n\t\tdelete thought.register_branch_id;\n\t\tconst { result, warnings } = this.validateInput(thought);\n\t\tthis._validateStatelessNewTypes(result);\n\t\treturn {\n\t\t\tthought: result,\n\t\t\tresetState: result.reset_state === true,\n\t\t\tregisterBranchId,\n\t\t\tvalidationWarnings: warnings,\n\t\t};\n\t}\n\n\tprivate _buildErrorResponse(error: unknown): CallToolResult {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text',\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...(error instanceof SequentialThinkingError && { code: error.code }),\n\t\t\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t\t\t\tmessage: getErrorMessage(error),\n\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t};\n\t}\n\n\tprivate static _emptySessionSnapshot(): HistorySessionSnapshot {\n\t\treturn {\n\t\t\thistory: [],\n\t\t\tbranches: {},\n\t\t\tverificationTargets: new Map(),\n\t\t\tbranchIds: [],\n\t\t\tavailableMcpTools: undefined,\n\t\t\tavailableSkills: undefined,\n\t\t};\n\t}\n\n\t/** Clears all processor-owned state for one removed session. */\n\tpublic clearSessionAuxiliaryState(sessionId: SessionId): void {\n\t\tthis._hintCooldowns.delete(sessionId);\n\t\tthis._suspensionStore?.clearSession(sessionId);\n\t\tthis._outcomeRecorder?.clearOutcomes(sessionId);\n\t\tthis._calibrator?.clearSession(sessionId);\n\t}\n\n\t/** Clears all processor-owned state after global reset or successful shutdown. */\n\tpublic clearAllAuxiliaryState(): void {\n\t\tthis._suspensionStore?.clearAll();\n\t\tthis._outcomeRecorder?.clearAllOutcomes();\n\t\tthis._calibrator?.clearAll();\n\t\tthis._hintCooldowns.clear();\n\t}\n\n\tprivate _validateToolArgumentsShape(toolArguments: unknown): void {\n\t\ttry {\n\t\t\tenforceJsonShape(toolArguments ?? {});\n\t\t} catch (error) {\n\t\t\tif (error instanceof JsonShapeError) {\n\t\t\t\tthrow new ValidationError('tool_arguments', error.reason);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate async _processInner(prepared: PreparedThought): Promise<CallToolResult> {\n\t\tconst { thought, resetState, registerBranchId } = prepared;\n\t\tconst sessionId = thought.session_id;\n\t\tconst existingSnapshot = this.historyManager.inspectSession(sessionId);\n\t\tconst validationSnapshot = resetState\n\t\t\t? ThoughtProcessor._emptySessionSnapshot()\n\t\t\t: existingSnapshot;\n\t\tif (!resetState) {\n\t\t\tif (!thought.available_mcp_tools && validationSnapshot.availableMcpTools) {\n\t\t\t\tthought.available_mcp_tools = [...validationSnapshot.availableMcpTools];\n\t\t\t}\n\t\t\tif (!thought.available_skills && validationSnapshot.availableSkills) {\n\t\t\t\tthought.available_skills = [...validationSnapshot.availableSkills];\n\t\t\t}\n\t\t}\n\t\tconst resolveThoughtReference = resetState\n\t\t\t? () => ({ kind: 'missing' as const })\n\t\t\t: (thoughtNumber: number) =>\n\t\t\t\t\tthis.historyManager.resolveThoughtReference(sessionId, thoughtNumber);\n\t\tconst {\n\t\t\tresult: checkedInput,\n\t\t\twarnings: refWarnings,\n\t\t\tresolvedReferences,\n\t\t} = validateThoughtCrossReferences(thought, {\n\t\t\tsnapshot: validationSnapshot,\n\t\t\tresolveThoughtReference,\n\t\t\tstrictBranchReferences: resetState || registerBranchId !== undefined,\n\t\t\tlogger: this._logger,\n\t\t});\n\t\tconst verificationOutcome = prepareVerificationOutcome({\n\t\t\tinput: checkedInput,\n\t\t\tsnapshot: validationSnapshot,\n\t\t\tresolvedReferences,\n\t\t\tsessionId,\n\t\t\trecorder: this._outcomeRecorder,\n\t\t});\n\t\tconst allWarnings = [...prepared.validationWarnings, ...refWarnings];\n\t\tconst validated = this._validateNewTypes(checkedInput);\n\t\tconst admissionContext: ThoughtAdmissionContext = { resolvedReferences };\n\t\tif (resetState && validated.thought_type === 'tool_observation') {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t'tool_observation cannot resume a suspension in reset replacement state'\n\t\t\t);\n\t\t}\n\n\t\tif (resetState) {\n\t\t\tawait this.historyManager.resetSessionWithinExclusive(sessionId, () =>\n\t\t\t\tthis.clearSessionAuxiliaryState(sessionId)\n\t\t\t);\n\t\t\tthis.log('State reset for session', { sessionId });\n\t\t}\n\t\tthis.historyManager.assertThoughtIdentityAvailable(checkedInput);\n\t\tif (registerBranchId !== undefined) {\n\t\t\tthis.historyManager.registerBranch(sessionId, registerBranchId);\n\t\t}\n\n\t\t// Tool-interleave suspend path: persist the tool_call thought, then return\n\t\t// a `suspended` envelope without running strategy/evaluator.\n\t\tif (validated.thought_type === 'tool_call' && this._suspensionStore) {\n\t\t\treturn this._handleToolCall(validated, admissionContext);\n\t\t}\n\n\t\t// Tool-interleave resume path: consume the suspension and continue the\n\t\t// normal pipeline (addThought → format → evaluate → strategy).\n\t\tif (validated.thought_type === 'tool_observation' && this._suspensionStore) {\n\t\t\tawait this._handleToolObservation(validated, admissionContext);\n\t\t} else {\n\t\t\tthis.historyManager.addThought(checkedInput, admissionContext);\n\t\t}\n\t\tthis._recordVerificationOutcome(verificationOutcome, sessionId);\n\n\t\tconst formattedThought = this.thoughtFormatter.formatThought(checkedInput);\n\t\tthis.log(formattedThought, { sessionId });\n\n\t\tconst signals = this._collectReasoningSignals(checkedInput);\n\n\t\t// Strategy decision — pluggable reasoning policy hook.\n\t\t// Built after history/stats so strategies see the latest state.\n\t\tconst decision = this._runStrategy(checkedInput, signals.history, signals.reasoningStats);\n\n\t\treturn this._buildSuccessResponse({\n\t\t\tthought: checkedInput,\n\t\t\treasoning: {\n\t\t\t\tconfidenceSignals: signals.confidenceSignals,\n\t\t\t\treasoningStats: signals.reasoningStats,\n\t\t\t\treasoningHints: signals.reasoningHints,\n\t\t\t},\n\t\t\tdecision,\n\t\t\twarnings: allWarnings,\n\t\t});\n\t}\n\n\tprivate _recordVerificationOutcome(\n\t\toutcome: ReturnType<typeof prepareVerificationOutcome>,\n\t\tsessionId: SessionId\n\t): void {\n\t\tif (outcome === undefined) return;\n\t\tif (this._outcomeRecorder?.enabled === true) {\n\t\t\tthis._outcomeRecorder.recordVerification(outcome);\n\t\t}\n\t\tif (this._calibrator?.enabled === true) this._calibrator.refit(sessionId);\n\t}\n\n\tprivate _collectReasoningSignals(input: ThoughtData): ReasoningSignalBundle {\n\t\tconst sessionId = input.session_id;\n\t\tconst history = this.historyManager.getHistory(sessionId);\n\t\tconst branches = this.historyManager.getBranches(sessionId);\n\t\tconst verificationTargets = this.historyManager.inspectSession(sessionId).verificationTargets;\n\t\tconst confidenceSignals = this._thoughtEvaluator.computeConfidenceSignals(history, branches, {\n\t\t\tcurrentThought: input,\n\t\t\tsessionId,\n\t\t\tverificationTargets,\n\t\t});\n\t\tconst reasoningStats = this._thoughtEvaluator.computeReasoningStats(history, branches, {\n\t\t\tverificationTargets,\n\t\t});\n\t\tconst patternSignals = this._thoughtEvaluator.computePatternSignals(history, branches, {\n\t\t\tverificationTargets,\n\t\t});\n\t\tconst reasoningHints = this._generateHints(patternSignals, input.thought_number, sessionId);\n\n\t\treturn {\n\t\t\thistory,\n\t\t\tconfidenceSignals,\n\t\t\treasoningStats,\n\t\t\treasoningHints,\n\t\t};\n\t}\n\n\tprivate _buildSuccessResponse(state: ProcessedThoughtResponseState): CallToolResult {\n\t\tconst sessionId = state.thought.session_id;\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text' as const,\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthought_number: state.thought.thought_number,\n\t\t\t\t\t\t\ttotal_thoughts: state.thought.total_thoughts,\n\t\t\t\t\t\t\tnext_thought_needed: state.thought.next_thought_needed ?? true,\n\t\t\t\t\t\t\tbranches: this.historyManager.getBranchIds(sessionId),\n\t\t\t\t\t\t\tthought_history_length: this.historyManager.getHistoryLength(sessionId),\n\t\t\t\t\t\t\tavailable_mcp_tools: state.thought.available_mcp_tools,\n\t\t\t\t\t\t\tavailable_skills: state.thought.available_skills,\n\t\t\t\t\t\t\tcurrent_step: state.thought.current_step,\n\t\t\t\t\t\t\tprevious_steps: state.thought.previous_steps,\n\t\t\t\t\t\t\tremaining_steps: state.thought.remaining_steps,\n\t\t\t\t\t\t\tthought_type: state.thought.thought_type,\n\t\t\t\t\t\t\tquality_score: state.thought.quality_score,\n\t\t\t\t\t\t\tconfidence: state.thought.confidence,\n\t\t\t\t\t\t\thypothesis_id: state.thought.hypothesis_id,\n\t\t\t\t\t\t\tconfidence_signals: state.reasoning.confidenceSignals,\n\t\t\t\t\t\t\treasoning_stats: state.reasoning.reasoningStats,\n\t\t\t\t\t\t\t...(state.reasoning.reasoningHints.length > 0 && {\n\t\t\t\t\t\t\t\treasoning_hints: state.reasoning.reasoningHints,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...(state.decision !== undefined && { strategy_hint: state.decision }),\n\t\t\t\t\t\t\t...(state.warnings.length > 0 && { warnings: state.warnings.slice(0, 3) }),\n\t\t\t\t\t\t\tsession_id: sessionId,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Run the configured reasoning strategy and return its decision.\n\t * Strategy errors omit the decision from the public response.\n\t * @private\n\t */\n\tprivate _runStrategy(\n\t\tcurrentThought: ThoughtData,\n\t\thistory: ThoughtData[],\n\t\tstats: ReturnType<ThoughtEvaluator['computeReasoningStats']>\n\t): StrategyDecision | undefined {\n\t\tconst sessionId = currentThought.session_id;\n\t\tlet decision: StrategyDecision | undefined;\n\t\ttry {\n\t\t\tconst evidence = buildActiveEvidenceProjection({\n\t\t\t\tsessionId,\n\t\t\t\thistory,\n\t\t\t\tbranches: this.historyManager.getBranches(sessionId),\n\t\t\t\tedgeStore: this._getEdgeStore(),\n\t\t\t});\n\t\t\tdecision = this.strategy.decide({\n\t\t\t\tsessionId,\n\t\t\t\tevidence,\n\t\t\t\tstats,\n\t\t\t\tcurrentThought,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis._logger.warn('Reasoning strategy threw — omitting strategy hint', {\n\t\t\t\tstrategy: this.strategy.name,\n\t\t\t\terror: getErrorMessage(error),\n\t\t\t});\n\t\t}\n\n\t\t// Auto-compression trigger: when strategy terminates a branch and\n\t\t// compression is enabled, summarize the branch subtree. Compression\n\t\t// failures must NEVER break the thought pipeline.\n\t\tif (decision?.action === 'terminate' && this._compressionService && currentThought.branch_id) {\n\t\t\ttry {\n\t\t\t\tconst branchRoot = this._findBranchRoot(sessionId, currentThought.branch_id);\n\t\t\t\tif (branchRoot) {\n\t\t\t\t\tthis._compressionService.compressBranch(\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tcurrentThought.branch_id,\n\t\t\t\t\t\tbranchRoot as ThoughtId\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tthis._logger.debug('Compression auto-trigger failed', {\n\t\t\t\t\terror: getErrorMessage(err),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn decision;\n\t}\n\n\t/**\n\t * Locate the root thought id for a branch.\n\t * Prefers GraphView.branchThoughts() when an EdgeStore is available;\n\t * falls back to historyManager.getBranches(sessionId)[branchId][0].id.\n\t * @private\n\t */\n\tprivate _findBranchRoot(sessionId: SessionId, branchId: BranchId): string | undefined {\n\t\tconst edgeStore = this._getEdgeStore();\n\t\tconst branches = this.historyManager.getBranches(sessionId);\n\t\tconst branchList = branches[branchId];\n\t\tconst firstId = branchList?.[0]?.id;\n\t\tif (edgeStore && firstId) {\n\t\t\tconst graph = new GraphView(edgeStore);\n\t\t\tconst ids = graph.branchThoughts(sessionId, firstId);\n\t\t\tif (ids.length > 0) return ids[0];\n\t\t}\n\t\treturn firstId;\n\t}\n\n\t/** Access the EdgeStore via IHistoryManager. @private */\n\tprivate _getEdgeStore(): IEdgeStore | undefined {\n\t\treturn this.historyManager.getEdgeStore();\n\t}\n\n\t/**\n\t * Validates and normalizes thought input.\n\t *\n\t * Ensures that thought numbers are consistent and within valid ranges.\n\t * If `thought_number` exceeds `total_thoughts`, `total_thoughts` is\n\t * automatically adjusted to match and a warning is emitted.\n\t *\n\t * @param input - The input to validate\n\t * @returns Object with validated input and any warnings generated\n\t * @private\n\t *\n\t * @example\n\t * ```typescript\n\t * // Auto-adjusts total_thoughts when thought_number exceeds it\n\t * const { result, warnings } = this.validateInput(input);\n\t * // result.total_thoughts === 10 (auto-adjusted from 5)\n\t * // warnings === ['Auto-adjusted total_thoughts from 5 to 10 to match thought_number']\n\t * ```\n\t */\n\tprivate validateInput(input: ThoughtData): {\n\t\tresult: ThoughtData;\n\t\twarnings: string[];\n\t} {\n\t\tconst warnings: string[] = [];\n\t\tif (input.thought_number > input.total_thoughts) {\n\t\t\tconst originalTotal = input.total_thoughts;\n\t\t\twarnings.push(\n\t\t\t\t`[${WARNING_CODES.TOTAL_THOUGHTS_ADJUSTED}] Auto-adjusted total_thoughts from ${originalTotal} to ${input.thought_number} to match thought_number`\n\t\t\t);\n\t\t\tthis._logger.warn('Auto-adjusted total_thoughts to match thought_number', {\n\t\t\t\tthought_number: input.thought_number,\n\t\t\t\toriginal_total_thoughts: originalTotal,\n\t\t\t\tadjusted_total_thoughts: input.thought_number,\n\t\t\t});\n\t\t\tinput.total_thoughts = input.thought_number;\n\t\t}\n\t\treturn { result: input, warnings };\n\t}\n\n\t/**\n\t * Validate new thought-type invariants behind feature flags.\n\t * @private\n\t */\n\tprivate _validateStatelessNewTypes(input: ThoughtData): void {\n\t\tconst t = input.thought_type;\n\t\tif ((t === 'tool_call' || t === 'tool_observation') && !this._features.toolInterleave) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t`Type '${t}' requires the toolInterleave feature flag. Set TRACELATTICE_FEATURES_TOOL_INTERLEAVE=true to enable it.`\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\t(t === 'assumption' || t === 'decomposition' || t === 'backtrack') &&\n\t\t\t!this._features.newThoughtTypes\n\t\t) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t`Type '${t}' requires the newThoughtTypes feature flag. Set TRACELATTICE_FEATURES_NEW_THOUGHT_TYPES=true to enable it, or use '${ThoughtProcessor._getWorkaroundType(t)}' type as a workaround.`\n\t\t\t);\n\t\t}\n\t\tif (t === 'tool_call') {\n\t\t\tif (!input.tool_name) {\n\t\t\t\tthrow new InvalidToolCallError(\n\t\t\t\t\t'tool_call thought ' + input.thought_number + ' missing required tool_name'\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis._validateToolName(input.tool_name);\n\t\t}\n\t\tif (t === 'tool_observation' && !input.continuation_token) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'continuation_token',\n\t\t\t\t'tool_observation thought ' + input.thought_number + ' missing continuation_token'\n\t\t\t);\n\t\t}\n\t\tif (t === 'backtrack') {\n\t\t\tif (input.backtrack_target === undefined) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t'backtrack_target',\n\t\t\t\t\t'backtrack thought ' + input.thought_number + ' requires backtrack_target'\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (input.backtrack_target > input.thought_number) {\n\t\t\t\tthrow new InvalidBacktrackError(\n\t\t\t\t\t'backtrack_target ' +\n\t\t\t\t\t\tinput.backtrack_target +\n\t\t\t\t\t\t' must be <= thought_number ' +\n\t\t\t\t\t\tinput.thought_number\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (t === 'tool_call') {\n\t\t\tthis._validateToolArgumentsShape(input.tool_arguments);\n\t\t}\n\t}\n\n\tprivate _validateNewTypes(input: ThoughtData): ValidatedThought {\n\t\treturn input as ValidatedThought;\n\t}\n\n\t/**\n\t * Validate a tool_call's tool_name against the configured allowlist.\n\t *\n\t * Fails closed: if no tool registry was wired, all tool_call invocations are\n\t * rejected. This prevents arbitrary tool name injection through the protocol.\n\t *\n\t * @param toolName - The tool name from the tool_call thought\n\t * @throws {UnknownToolError} When no registry is wired or the tool is not registered\n\t * @private\n\t */\n\tprivate _validateToolName(toolName: string): void {\n\t\tif (!this._toolRegistry) {\n\t\t\tthrow new UnknownToolError(\n\t\t\t\ttoolName,\n\t\t\t\t`Tool '${toolName}' rejected: no tool registry configured. Tool interleave requires a registered allowlist.`\n\t\t\t);\n\t\t}\n\t\tif (!this._toolRegistry.has(toolName)) {\n\t\t\tthrow new UnknownToolError(toolName);\n\t\t}\n\t}\n\n\t/**\n\t * Returns a workaround thought type for a feature-flagged type.\n\t * @private\n\t */\n\tprivate static _getWorkaroundType(t: 'assumption' | 'decomposition' | 'backtrack'): string {\n\t\tswitch (t) {\n\t\t\tcase 'assumption':\n\t\t\t\treturn 'regular';\n\t\t\tcase 'decomposition':\n\t\t\t\treturn 'hypothesis';\n\t\t\tcase 'backtrack':\n\t\t\t\treturn 'regular';\n\t\t\tdefault:\n\t\t\t\tassertNever(t);\n\t\t}\n\t}\n\n\t/**\n\t * Persist a tool_call thought and return a `suspended` envelope.\n\t * Strategy/evaluator are intentionally skipped.\n\t * @private\n\t */\n\tprivate _handleToolCall(\n\t\tinput: ToolCallThought,\n\t\tadmissionContext: ThoughtAdmissionContext\n\t): CallToolResult {\n\t\tif (input.id === undefined) {\n\t\t\tthrow new ValidationError('id', 'tool_call requires an admitted thought id');\n\t\t}\n\t\tthis.historyManager.addThought(input, admissionContext);\n\t\tif (!this._suspensionStore) {\n\t\t\tthrow new ValidationError('thought_type', 'tool_call requires suspensionStore');\n\t\t}\n\t\tconst record: SuspensionRecord = this._suspensionStore.suspend({\n\t\t\tsessionId: input.session_id,\n\t\t\ttoolCallThoughtNumber: input.thought_number,\n\t\t\ttoolCallThoughtId: input.id,\n\t\t\ttoolName: input.tool_name,\n\t\t\ttoolArguments: input.tool_arguments ?? {},\n\t\t\texpiresAt: 0,\n\t\t});\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text' as const,\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstatus: 'suspended',\n\t\t\t\t\t\t\tcontinuation_token: record.token,\n\t\t\t\t\t\t\ttool_name: record.toolName,\n\t\t\t\t\t\t\ttool_arguments: record.toolArguments,\n\t\t\t\t\t\t\texpires_at: record.expiresAt,\n\t\t\t\t\t\t\tthought_number: input.thought_number,\n\t\t\t\t\t\t\ttotal_thoughts: input.total_thoughts,\n\t\t\t\t\t\t\tsession_id: input.session_id,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Resume from a tool_observation and atomically admit it before consuming the record.\n\t * @private\n\t */\n\tprivate async _handleToolObservation(\n\t\tinput: ToolObservationThought,\n\t\tadmissionContext: ThoughtAdmissionContext\n\t): Promise<void> {\n\t\tif (!this._suspensionStore) {\n\t\t\tthrow new ValidationError('thought_type', 'tool_observation requires suspensionStore');\n\t\t}\n\t\tawait this._suspensionStore.compareAndAdmit(\n\t\t\tinput.continuation_token,\n\t\t\tinput.session_id,\n\t\t\t(record) => {\n\t\t\t\tthis.historyManager.addThought(input, {\n\t\t\t\t\t...admissionContext,\n\t\t\t\t\ttoolInvocationSourceThoughtId: record.toolCallThoughtId,\n\t\t\t\t});\n\t\t\t}\n\t\t);\n\t}\n}\n"],"names":["ThoughtProcessor","Map","historyManager","thoughtFormatter","thoughtEvaluator","logger","strategy","SequentialStrategy","_compressionService","_suspensionStore","_toolRegistry","_features","DEFAULT_FLAGS","_sessionLock","_outcomeRecorder","_lifecycle","SessionLifecycleCoordinator","_calibrator","NullLogger","message","meta","patterns","currentThoughtNumber","sessionId","warnings","p","a","b","pa","pb","cooldowns","undefined","hints","warning","lastFired","input","prepared","operation","error","canonicalSessionId","asSessionId","normalized","normalizeInput","parsed","v","SequentialThinkingSchema","firstIssue","field","item","String","ValidationError","internal","registerBranchId","asBranchId","thought","result","JSON","SequentialThinkingError","getErrorMessage","toolArguments","enforceJsonShape","JsonShapeError","resetState","existingSnapshot","validationSnapshot","resolveThoughtReference","thoughtNumber","checkedInput","refWarnings","resolvedReferences","validateThoughtCrossReferences","verificationOutcome","prepareVerificationOutcome","allWarnings","validated","admissionContext","formattedThought","signals","decision","outcome","history","branches","verificationTargets","confidenceSignals","reasoningStats","patternSignals","reasoningHints","state","currentThought","stats","evidence","buildActiveEvidenceProjection","branchRoot","err","branchId","edgeStore","branchList","firstId","graph","GraphView","ids","originalTotal","WARNING_CODES","t","InvalidToolCallError","InvalidBacktrackError","toolName","UnknownToolError","assertNever","record"],"mappings":";;;;;;;;;;;;;;;AA8IO,MAAMA;;;;;;;;;;;;IAEJ,QAAgB;IAGP,kBAAoC;IAM7C,iBAAiB,IAAIC,MAA2C;IAiBxE,YACSC,cAA+B,EAC/BC,gBAAkC,EAC1CC,gBAAkC,EAClCC,MAAe,EACEC,WAA+B,IAAIC,oBAAoB,EACvDC,mBAAwC,EACxCC,gBAAmC,EACnCC,aAA6B,EAC7BC,YAA0BC,aAAa,EACvCC,YAA2B,EAC3BC,gBAAmC,EACnCC,aAA0C,IAAIC,6BAA6B,EAC3EC,WAAyB,CACzC;aAbOf,cAAc,GAAdA;aACAC,gBAAgB,GAAhBA;aAGSG,QAAQ,GAARA;aACAE,mBAAmB,GAAnBA;aACAC,gBAAgB,GAAhBA;aACAC,aAAa,GAAbA;aACAC,SAA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,IAAI,CAAC,gBAAgB,EACzB,MAAM,IAAIzB,gBAAgB,gBAAgB;QAE3C,MAAM2D,SAA2B,IAAI,CAAC,gBAAgB,CAAC,OAAO,CAAC;YAC9D,WAAW1E,MAAM,UAAU;YAC3B,uBAAuBA,MAAM,cAAc;YAC3C,mBAAmBA,MAAM,EAAE;YAC3B,UAAUA,MAAM,SAAS;YACzB,eAAeA,MAAM,cAAc,IAAI,CAAC;YACxC,WAAW;QACZ;QACA,OAAO;YACN,SAAS;gBACR;oBACC,MAAM;oBACN,MAAMqB,KAAK,SAAS,CACnB;wBACC,QAAQ;wBACR,oBAAoBqD,OAAO,KAAK;wBAChC,WAAWA,OAAO,QAAQ;wBAC1B,gBAAgBA,OAAO,aAAa;wBACpC,YAAYA,OAAO,SAAS;wBAC5B,gBAAgB1E,MAAM,cAAc;wBACpC,gBAAgBA,MAAM,cAAc;wBACpC,YAAYA,MAAM,UAAU;oBAC7B,GACA,MACA;gBAEF;aACA;QACF;IACD;IAMA,MAAc,uBACbA,KAA6B,EAC7BwC,gBAAyC,EACzB;QAChB,IAAI,CAAC,IAAI,CAAC,gBAAgB,EACzB,MAAM,IAAIzB,gBAAgB,gBAAgB;QAE3C,MAAM,IAAI,CAAC,gBAAgB,CAAC,eAAe,CAC1Cf,MAAM,kBAAkB,EACxBA,MAAM,UAAU,EAChB,CAAC0E;YACA,IAAI,CAAC,cAAc,CAAC,UAAU,CAAC1E,OAAO;gBACrC,GAAGwC,gBAAgB;gBACnB,+BAA+BkC,OAAO,iBAAiB;YACxD;QACD;IAEF;AACD"}
|
|
1
|
+
{"version":3,"file":"core/ThoughtProcessor.js","sources":["../../src/core/ThoughtProcessor.ts"],"sourcesContent":["/**\n * Core thought processing logic and validation.\n *\n * This module provides the `ThoughtProcessor` class which handles the main\n * sequential thinking request processing pipeline, including input validation,\n * history management, and response formatting.\n *\n * @module processor\n */\n\nimport * as v from 'valibot';\n\nimport { NullLogger } from '../logger/NullLogger.js';\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport {\n\tasBranchId,\n\tasSessionId,\n\ttype BranchId,\n\ttype SessionId,\n\ttype ThoughtId,\n} from '../contracts/ids.js';\nimport type { IEdgeStore, IOutcomeRecorder } from '../contracts/interfaces.js';\nimport type { ICalibrator } from '../contracts/calibrator.js';\nimport type { ISuspensionStore, SuspensionRecord } from '../contracts/suspension.js';\nimport type {\n\tActiveEvidenceProjection,\n\tIReasoningStrategy,\n\tStrategyDecision,\n} from '../contracts/strategy.js';\nimport { DEFAULT_FLAGS, type FeatureFlags } from '../contracts/features.js';\nimport type { ISessionLock, IToolRegistry } from '../contracts/interfaces.js';\nimport {\n\tInvalidBacktrackError,\n\tInvalidToolCallError,\n\tSequentialThinkingError,\n\tUnknownToolError,\n\tValidationError,\n} from '../errors.js';\nimport { getErrorMessage, WARNING_CODES } from '../errors.js';\nimport { enforceJsonShape, JsonShapeError } from '../sanitize.js';\nimport { SequentialThinkingSchema } from '../schema.js';\nimport { GraphView } from './graph/GraphView.js';\nimport { buildActiveEvidenceProjection } from './reasoning/ActiveEvidenceProjection.js';\nimport { buildGraphContext, type GraphContext } from './reasoning/GraphContext.js';\nimport { assertNever } from '../utils.js';\nimport type {\n\tHistorySessionSnapshot,\n\tIHistoryManager,\n\tThoughtAdmissionContext,\n} from './IHistoryManager.js';\nimport { normalizeInput } from './InputNormalizer.js';\nimport type {\n\tThoughtData,\n\tToolCallThought,\n\tToolObservationThought,\n\tValidatedThought,\n} from './thought.js';\nimport type { ThoughtEvaluator } from './ThoughtEvaluator.js';\nimport type { ThoughtFormatter } from './ThoughtFormatter.js';\nimport type { PatternName } from '../contracts/reasoning-types.js';\nimport type { PatternSignal } from './reasoning.js';\nimport { SequentialStrategy } from './reasoning/strategies/SequentialStrategy.js';\nimport type { CompressionService } from './compression/CompressionService.js';\nimport { validateThoughtCrossReferences } from './CrossReferenceValidator.js';\nimport { SessionLifecycleCoordinator } from './SessionLifecycleCoordinator.js';\nimport { prepareVerificationOutcome } from './VerificationOutcomeAdmission.js';\n\ntype ConfidenceSignalsResult = ReturnType<ThoughtEvaluator['computeConfidenceSignals']>;\ntype ReasoningStatsResult = ReturnType<ThoughtEvaluator['computeReasoningStats']>;\n\ntype ReasoningSignalBundle = {\n\treadonly evidence: ActiveEvidenceProjection | undefined;\n\treadonly confidenceSignals: ConfidenceSignalsResult;\n\treadonly reasoningStats: ReasoningStatsResult;\n\treadonly reasoningHints: readonly string[];\n};\n\ntype ProcessedThoughtResponseState = {\n\treadonly thought: ThoughtData;\n\treadonly reasoning: {\n\t\treadonly confidenceSignals: ConfidenceSignalsResult;\n\t\treadonly reasoningStats: ReasoningStatsResult;\n\t\treadonly graphContext: GraphContext | undefined;\n\t\treadonly reasoningHints: readonly string[];\n\t};\n\treadonly decision: StrategyDecision | undefined;\n\treadonly warnings: readonly string[];\n};\n\ntype ThoughtProcessInput = ThoughtData & { readonly register_branch_id?: string };\n\ntype PreparedThought = {\n\treadonly thought: ThoughtData;\n\treadonly resetState: boolean;\n\treadonly registerBranchId: BranchId | undefined;\n\treadonly validationWarnings: readonly string[];\n};\n\n/**\n * The return type expected by MCP tool invocations.\n *\n * This structure matches the MCP protocol for tool results,\n * supporting both success and error responses.\n *\n * @example\n * ```typescript\n * const successResult: CallToolResult = {\n * content: [{ type: 'text', text: '{\"status\":\"success\"}' }]\n * };\n *\n * const errorResult: CallToolResult = {\n * content: [{ type: 'text', text: '{\"error\":\"Something went wrong\"}' }],\n * isError: true\n * };\n * ```\n */\nexport interface CallToolResult extends Record<string, unknown> {\n\t/** Array of content blocks (typically text) to return to the client. */\n\tcontent: Array<{\n\t\ttype: 'text';\n\t\ttext: string;\n\t}>;\n\n\t/** Whether this result represents an error condition. */\n\tisError?: boolean;\n}\n\n/**\n * Core processor for sequential thinking requests.\n *\n * Pipeline: validate → normalize → add to history → format → evaluate signals\n * → run reasoning strategy → return structured response.\n *\n * Auto-adjusts `total_thoughts` if `thought_number` exceeds it. All errors are\n * caught and returned as formatted error responses with `isError: true`.\n *\n * @example\n * ```typescript\n * const processor = new ThoughtProcessor(historyManager, formatter, new ThoughtEvaluator());\n * const result = await processor.process({\n * thought: '...',\n * thought_number: 1,\n * total_thoughts: 5,\n * next_thought_needed: true,\n * session_id: asSessionId('analysis')\n * });\n * ```\n */\nexport class ThoughtProcessor {\n\t/** Logger for debugging and monitoring. */\n\tprivate _logger: Logger;\n\n\t/** Evaluator for quality signal computation. */\n\tprivate readonly _thoughtEvaluator: ThoughtEvaluator;\n\n\t/**\n\t * Per-session cooldown tracker: session_id → pattern → last_fired_thought_number.\n\t * Prevents re-firing the same pattern hint within 3 thoughts.\n\t */\n\tprivate _hintCooldowns = new Map<SessionId, Map<PatternName, number>>();\n\n\t/**\n\t * Creates a new ThoughtProcessor instance.\n\t *\n\t * @param historyManager - History manager for storing thoughts\n\t * @param thoughtFormatter - Formatter for output formatting\n\t * @param thoughtEvaluator - Evaluator for quality signal computation\n\t * @param logger - Optional logger for diagnostics (defaults to NullLogger)\n\t * @param strategy - Reasoning strategy controlling next-action decisions (defaults to SequentialStrategy)\n\t * @param compressionService - Optional compression service for auto-compression on terminate\n\t * @param suspensionStore - Optional suspension store enabling tool interleave\n\t * @param toolRegistry - Optional tool registry for tool_name allowlist validation (required when toolInterleave is enabled)\n\t * @param features - Optional feature flags (defaults to DEFAULT_FLAGS — all opt-in flags off)\n\t * @param sessionLock - Optional per-session async lock; when provided, `process()` runs under it\n\t * @param outcomeRecorder - Optional per-session calibration outcome store\n\t */\n\tconstructor(\n\t\tprivate historyManager: IHistoryManager,\n\t\tprivate thoughtFormatter: ThoughtFormatter,\n\t\tthoughtEvaluator: ThoughtEvaluator,\n\t\tlogger?: Logger,\n\t\tprivate readonly strategy: IReasoningStrategy = new SequentialStrategy(),\n\t\tprivate readonly _compressionService?: CompressionService,\n\t\tprivate readonly _suspensionStore?: ISuspensionStore,\n\t\tprivate readonly _toolRegistry?: IToolRegistry,\n\t\tprivate readonly _features: FeatureFlags = DEFAULT_FLAGS,\n\t\tprivate readonly _sessionLock?: ISessionLock,\n\t\tprivate readonly _outcomeRecorder?: IOutcomeRecorder,\n\t\tprivate readonly _lifecycle: SessionLifecycleCoordinator = new SessionLifecycleCoordinator(),\n\t\tprivate readonly _calibrator?: ICalibrator\n\t) {\n\t\tthis._thoughtEvaluator = thoughtEvaluator;\n\t\tthis._logger = logger ?? new NullLogger();\n\t}\n\n\t/**\n\t * Internal logging method.\n\t * @param message - The message to log\n\t * @param meta - Optional metadata\n\t * @private\n\t */\n\tprivate log(message: string, meta?: Record<string, unknown>): void {\n\t\tthis._logger.info(message, meta);\n\t}\n\n\t/**\n\t * Priority ordering for warning patterns (lower = higher priority).\n\t * Ensures the most actionable patterns fill the hint cap first.\n\t */\n\tprivate static readonly _HINT_PRIORITY: Readonly<Partial<Record<PatternName, number>>> = {\n\t\trefuted_hypothesis_dependency: 1, // Invalid foundation — revise dependents first\n\t\tconfidence_drift: 2, // Degrading confidence\n\t\tunverified_hypothesis: 3, // Missing hypothesis evidence\n\t\tunaddressed_critique: 4, // Unresolved challenge\n\t\tno_alternatives_explored: 5, // Breadth gap\n\t\tconsecutive_without_verification: 6, // Routine pattern; monotonic_type stays unranked\n\t};\n\n\t/**\n\t * Generate actionable hints from pattern signals.\n\t * Rules: max 3 hints, warning-severity only, cooldown of 3 thoughts per pattern per session.\n\t *\n\t * Warning patterns are sorted by priority before selection (see _HINT_PRIORITY).\n\t * Higher-priority patterns (lower number) fill the hint cap first.\n\t *\n\t * @param patterns - Detected pattern signals\n\t * @param currentThoughtNumber - The current thought number being processed\n\t * @param sessionId - Session identifier for cooldown scoping\n\t * @returns Array of hint strings (max 3), empty if no warnings\n\t */\n\tprivate _generateHints(\n\t\tpatterns: PatternSignal[],\n\t\tcurrentThoughtNumber: number,\n\t\tsessionId: SessionId\n\t): string[] {\n\t\tconst warnings = patterns.filter((p) => p.severity === 'warning');\n\t\tif (warnings.length === 0) return [];\n\n\t\t// Sort by priority (lower number = higher priority)\n\t\twarnings.sort((a, b) => {\n\t\t\tconst pa = ThoughtProcessor._HINT_PRIORITY[a.pattern] ?? 99;\n\t\t\tconst pb = ThoughtProcessor._HINT_PRIORITY[b.pattern] ?? 99;\n\t\t\treturn pa - pb;\n\t\t});\n\n\t\tlet cooldowns = this._hintCooldowns.get(sessionId);\n\t\tif (cooldowns === undefined) {\n\t\t\tcooldowns = new Map();\n\t\t\tthis._hintCooldowns.set(sessionId, cooldowns);\n\t\t}\n\n\t\tconst hints: string[] = [];\n\t\tfor (const warning of warnings) {\n\t\t\tif (hints.length >= 3) break;\n\n\t\t\tconst lastFired = cooldowns.get(warning.pattern);\n\t\t\tif (lastFired !== undefined && currentThoughtNumber - lastFired < 3) {\n\t\t\t\tcontinue; // Still in cooldown\n\t\t\t}\n\n\t\t\thints.push(warning.message);\n\t\t\tcooldowns.set(warning.pattern, currentThoughtNumber);\n\t\t}\n\n\t\treturn hints;\n\t}\n\n\t/**\n\t * Processes a thought through the sequential thinking pipeline.\n\t *\n\t * This method validates the input, adds it to history, formats the output,\n\t * computes quality signals via the ThoughtEvaluator, and returns\n\t * a structured response with metadata about the current state.\n\t *\n\t * @param input - The thought data to process\n\t * @returns A Promise resolving to the formatted tool result containing:\n\t * - `thought_number` — Current thought index\n\t * - `total_thoughts` — Estimated total thoughts\n\t * - `next_thought_needed` — Whether to continue\n\t * - `branches` — Active branch IDs\n\t * - `thought_history_length` — Number of thoughts in history\n\t * - `available_mcp_tools` — MCP tools available for recommendation\n\t * - `available_skills` — Skills available for recommendation\n\t * - `current_step` — Current step recommendation\n\t * - `previous_steps` — Previously recommended steps\n\t * - `remaining_steps` — Upcoming step descriptions\n\t * - `thought_type` — Classification of thought purpose (optional)\n\t * - `quality_score` — Self-assessed quality score 0-1 (optional)\n\t * - `confidence` — Self-assessed confidence 0-1 (optional)\n\t * - `hypothesis_id` — Hypothesis link for verification chains (optional)\n\t * - `confidence_signals` — Computed reasoning quality signals (includes structural_quality and quality_components)\n\t * - `reasoning_stats` — Aggregated reasoning analytics\n\t * - `reasoning_hints` — (Conditional) Actionable hints from pattern analysis, max 3, warning-severity only (optional)\n\t *\n\t * @example\n\t * ```typescript\n\t * const result = await processor.process({\n\t * thought: 'I should read the README file',\n\t * thought_number: 1,\n\t * total_thoughts: 3,\n\t * next_thought_needed: true,\n\t * session_id: asSessionId('analysis')\n\t * });\n\t *\n\t * console.log(result.content[0].text);\n\t * // Output includes: thought_number, total_thoughts, next_thought_needed,\n\t * // branches, thought_history_length, and any recommendations\n\t * ```\n\t */\n\tpublic async process(input: ThoughtProcessInput): Promise<CallToolResult> {\n\t\ttry {\n\t\t\tconst prepared = this._prepareInput(input);\n\t\t\tconst sessionId = prepared.thought.session_id;\n\t\t\tconst operation = async (): Promise<CallToolResult> => {\n\t\t\t\tif (this._sessionLock !== undefined) {\n\t\t\t\t\treturn await this._sessionLock.withLock(sessionId, () => this._processInner(prepared));\n\t\t\t\t}\n\t\t\t\treturn await this._processInner(prepared);\n\t\t\t};\n\t\t\tif (prepared.resetState) {\n\t\t\t\tthis.historyManager.assertSessionResetAuthorized(sessionId);\n\t\t\t\treturn await this._lifecycle.withSessionReset(sessionId, operation);\n\t\t\t}\n\t\t\tthis.historyManager.inspectSession(sessionId);\n\t\t\treturn await this._lifecycle.runOperation(sessionId, operation);\n\t\t} catch (error) {\n\t\t\treturn this._buildErrorResponse(error);\n\t\t}\n\t}\n\n\t/** Resets one canonical session and its processor-owned auxiliary state. */\n\tpublic async resetSession(sessionId: string): Promise<void> {\n\t\tconst canonicalSessionId = asSessionId(sessionId);\n\t\tthis.historyManager.assertSessionResetAuthorized(canonicalSessionId);\n\t\tconst operation = async (): Promise<void> => {\n\t\t\tawait this.historyManager.resetSessionWithinExclusive(canonicalSessionId, () =>\n\t\t\t\tthis.clearSessionAuxiliaryState(canonicalSessionId)\n\t\t\t);\n\t\t};\n\t\tawait this._lifecycle.withSessionReset(canonicalSessionId, async () => {\n\t\t\tif (this._sessionLock !== undefined) {\n\t\t\t\tawait this._sessionLock.withLock(canonicalSessionId, operation);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait operation();\n\t\t});\n\t}\n\n\t/** Resets all history and processor-owned auxiliary state from a trusted context. */\n\tpublic async resetAll(): Promise<void> {\n\t\tawait this._lifecycle.withGlobalReset(\n\t\t\tasync () =>\n\t\t\t\tawait this.historyManager.resetAllWithinExclusive(() => this.clearAllAuxiliaryState())\n\t\t);\n\t}\n\n\tprivate _prepareInput(input: ThoughtProcessInput): PreparedThought {\n\t\tconst normalized = normalizeInput(input);\n\t\tif (typeof normalized === 'object' && normalized !== null) {\n\t\t\tthis._validateToolArgumentsShape(normalized.tool_arguments);\n\t\t}\n\t\tconst parsed = v.safeParse(SequentialThinkingSchema, normalized);\n\t\tif (!parsed.success) {\n\t\t\tconst firstIssue = parsed.issues[0];\n\t\t\tconst field = firstIssue?.path?.map((item) => String(item.key)).join('.') || 'input';\n\t\t\tthrow new ValidationError(field, firstIssue?.message ?? 'Invalid input');\n\t\t}\n\n\t\tconst internal = normalizeInput(parsed.output) as ThoughtData & {\n\t\t\tregister_branch_id?: string;\n\t\t};\n\t\tconst registerBranchId =\n\t\t\tinternal.register_branch_id === undefined\n\t\t\t\t? undefined\n\t\t\t\t: asBranchId(internal.register_branch_id);\n\t\tconst thought = { ...internal };\n\t\tdelete thought.register_branch_id;\n\t\tconst { result, warnings } = this.validateInput(thought);\n\t\tthis._validateStatelessNewTypes(result);\n\t\treturn {\n\t\t\tthought: result,\n\t\t\tresetState: result.reset_state === true,\n\t\t\tregisterBranchId,\n\t\t\tvalidationWarnings: warnings,\n\t\t};\n\t}\n\n\tprivate _buildErrorResponse(error: unknown): CallToolResult {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text',\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...(error instanceof SequentialThinkingError && { code: error.code }),\n\t\t\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t\t\t\tmessage: getErrorMessage(error),\n\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t};\n\t}\n\n\tprivate static _emptySessionSnapshot(): HistorySessionSnapshot {\n\t\treturn {\n\t\t\thistory: [],\n\t\t\tbranches: {},\n\t\t\tverificationTargets: new Map(),\n\t\t\tbranchIds: [],\n\t\t\tavailableMcpTools: undefined,\n\t\t\tavailableSkills: undefined,\n\t\t};\n\t}\n\n\t/** Clears all processor-owned state for one removed session. */\n\tpublic clearSessionAuxiliaryState(sessionId: SessionId): void {\n\t\tthis._hintCooldowns.delete(sessionId);\n\t\tthis._suspensionStore?.clearSession(sessionId);\n\t\tthis._outcomeRecorder?.clearOutcomes(sessionId);\n\t\tthis._calibrator?.clearSession(sessionId);\n\t}\n\n\t/** Clears all processor-owned state after global reset or successful shutdown. */\n\tpublic clearAllAuxiliaryState(): void {\n\t\tthis._suspensionStore?.clearAll();\n\t\tthis._outcomeRecorder?.clearAllOutcomes();\n\t\tthis._calibrator?.clearAll();\n\t\tthis._hintCooldowns.clear();\n\t}\n\n\tprivate _validateToolArgumentsShape(toolArguments: unknown): void {\n\t\ttry {\n\t\t\tenforceJsonShape(toolArguments ?? {});\n\t\t} catch (error) {\n\t\t\tif (error instanceof JsonShapeError) {\n\t\t\t\tthrow new ValidationError('tool_arguments', error.reason);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate async _processInner(prepared: PreparedThought): Promise<CallToolResult> {\n\t\tconst { thought, resetState, registerBranchId } = prepared;\n\t\tconst sessionId = thought.session_id;\n\t\tif (resetState) this.historyManager.assertSessionResetAuthorized(sessionId);\n\t\tconst validationSnapshot = resetState\n\t\t\t? ThoughtProcessor._emptySessionSnapshot()\n\t\t\t: this.historyManager.inspectSession(sessionId);\n\t\tif (!resetState) {\n\t\t\tif (!thought.available_mcp_tools && validationSnapshot.availableMcpTools) {\n\t\t\t\tthought.available_mcp_tools = [...validationSnapshot.availableMcpTools];\n\t\t\t}\n\t\t\tif (!thought.available_skills && validationSnapshot.availableSkills) {\n\t\t\t\tthought.available_skills = [...validationSnapshot.availableSkills];\n\t\t\t}\n\t\t}\n\t\tconst resolveThoughtReference = resetState\n\t\t\t? () => ({ kind: 'missing' as const })\n\t\t\t: (thoughtNumber: number) =>\n\t\t\t\t\tthis.historyManager.resolveThoughtReference(sessionId, thoughtNumber);\n\t\tconst {\n\t\t\tresult: checkedInput,\n\t\t\twarnings: refWarnings,\n\t\t\tresolvedReferences,\n\t\t} = validateThoughtCrossReferences(thought, {\n\t\t\tsnapshot: validationSnapshot,\n\t\t\tresolveThoughtReference,\n\t\t\tstrictBranchReferences: resetState || registerBranchId !== undefined,\n\t\t\tlogger: this._logger,\n\t\t});\n\t\tconst verificationOutcome = prepareVerificationOutcome({\n\t\t\tinput: checkedInput,\n\t\t\tsnapshot: validationSnapshot,\n\t\t\tresolvedReferences,\n\t\t\tsessionId,\n\t\t\trecorder: this._outcomeRecorder,\n\t\t});\n\t\tconst allWarnings = [...prepared.validationWarnings, ...refWarnings];\n\t\tconst validated = this._validateNewTypes(checkedInput);\n\t\tconst admissionContext: ThoughtAdmissionContext = { resolvedReferences };\n\t\tif (resetState && validated.thought_type === 'tool_observation') {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t'tool_observation cannot resume a suspension in reset replacement state'\n\t\t\t);\n\t\t}\n\n\t\tif (resetState) {\n\t\t\tawait this.historyManager.resetSessionWithinExclusive(sessionId, () =>\n\t\t\t\tthis.clearSessionAuxiliaryState(sessionId)\n\t\t\t);\n\t\t\tthis.log('State reset for session', { sessionId });\n\t\t}\n\t\tthis.historyManager.assertThoughtIdentityAvailable(checkedInput);\n\t\tif (registerBranchId !== undefined) {\n\t\t\tthis.historyManager.registerBranch(sessionId, registerBranchId);\n\t\t}\n\n\t\t// Tool-interleave suspend path: persist the tool_call thought, then return\n\t\t// a `suspended` envelope without running strategy/evaluator.\n\t\tif (validated.thought_type === 'tool_call' && this._suspensionStore) {\n\t\t\treturn this._handleToolCall(validated, admissionContext);\n\t\t}\n\n\t\t// Tool-interleave resume path: consume the suspension and continue the\n\t\t// normal pipeline (addThought → format → evaluate → strategy).\n\t\tif (validated.thought_type === 'tool_observation' && this._suspensionStore) {\n\t\t\tawait this._handleToolObservation(validated, admissionContext);\n\t\t} else {\n\t\t\tthis.historyManager.addThought(checkedInput, admissionContext);\n\t\t}\n\t\tthis._recordVerificationOutcome(verificationOutcome, sessionId);\n\n\t\tconst formattedThought = this.thoughtFormatter.formatThought(checkedInput);\n\t\tthis.log(formattedThought, { sessionId });\n\n\t\tconst signals = this._collectReasoningSignals(checkedInput);\n\n\t\t// Strategy decision — pluggable reasoning policy hook.\n\t\t// Built after history/stats so strategies see the latest state.\n\t\tconst decision = this._runStrategy(checkedInput, signals.evidence, signals.reasoningStats);\n\n\t\treturn this._buildSuccessResponse({\n\t\t\tthought: checkedInput,\n\t\t\treasoning: {\n\t\t\t\tconfidenceSignals: signals.confidenceSignals,\n\t\t\t\treasoningStats: signals.reasoningStats,\n\t\t\t\tgraphContext:\n\t\t\t\t\tsignals.evidence === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: buildGraphContext(sessionId, checkedInput, signals.evidence),\n\t\t\t\treasoningHints: signals.reasoningHints,\n\t\t\t},\n\t\t\tdecision,\n\t\t\twarnings: allWarnings,\n\t\t});\n\t}\n\n\tprivate _recordVerificationOutcome(\n\t\toutcome: ReturnType<typeof prepareVerificationOutcome>,\n\t\tsessionId: SessionId\n\t): void {\n\t\tif (outcome === undefined) return;\n\t\tif (this._outcomeRecorder?.enabled === true) {\n\t\t\tthis._outcomeRecorder.recordVerification(outcome);\n\t\t}\n\t\tif (this._calibrator?.enabled === true) this._calibrator.refit(sessionId);\n\t}\n\n\tprivate _collectReasoningSignals(input: ThoughtData): ReasoningSignalBundle {\n\t\tconst sessionId = input.session_id;\n\t\tconst history = this.historyManager.getHistory(sessionId);\n\t\tconst branches = this.historyManager.getBranches(sessionId);\n\t\tconst evidence = this._buildActiveEvidence(sessionId, history, branches);\n\t\tconst graphScope =\n\t\t\tevidence?.graph === undefined ? {} : { activeGraph: { sessionId, view: evidence.graph } };\n\t\tconst verificationTargets = this.historyManager.inspectSession(sessionId).verificationTargets;\n\t\tconst confidenceSignals = this._thoughtEvaluator.computeConfidenceSignals(history, branches, {\n\t\t\tcurrentThought: input,\n\t\t\tsessionId,\n\t\t\tverificationTargets,\n\t\t\t...graphScope,\n\t\t});\n\t\tconst reasoningStats = this._thoughtEvaluator.computeReasoningStats(history, branches, {\n\t\t\tverificationTargets,\n\t\t});\n\t\tconst patternSignals = this._thoughtEvaluator.computePatternSignals(history, branches, {\n\t\t\tverificationTargets,\n\t\t\t...graphScope,\n\t\t});\n\t\tconst reasoningHints = this._generateHints(patternSignals, input.thought_number, sessionId);\n\n\t\treturn {\n\t\t\tevidence,\n\t\t\tconfidenceSignals,\n\t\t\treasoningStats,\n\t\t\treasoningHints,\n\t\t};\n\t}\n\n\tprivate _buildActiveEvidence(\n\t\tsessionId: SessionId,\n\t\thistory: readonly ThoughtData[],\n\t\tbranches: Record<BranchId, ThoughtData[]>\n\t): ActiveEvidenceProjection | undefined {\n\t\ttry {\n\t\t\treturn buildActiveEvidenceProjection({\n\t\t\t\tsessionId,\n\t\t\t\thistory,\n\t\t\t\tbranches,\n\t\t\t\tedgeStore: this._getEdgeStore(),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis._logger.warn('Active evidence projection failed — omitting graph and strategy hints', {\n\t\t\t\tsessionId,\n\t\t\t\terror: getErrorMessage(error),\n\t\t\t});\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate _buildSuccessResponse(state: ProcessedThoughtResponseState): CallToolResult {\n\t\tconst sessionId = state.thought.session_id;\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text' as const,\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthought_number: state.thought.thought_number,\n\t\t\t\t\t\t\ttotal_thoughts: state.thought.total_thoughts,\n\t\t\t\t\t\t\tnext_thought_needed: state.thought.next_thought_needed ?? true,\n\t\t\t\t\t\t\tbranches: this.historyManager.getBranchIds(sessionId),\n\t\t\t\t\t\t\tthought_history_length: this.historyManager.getHistoryLength(sessionId),\n\t\t\t\t\t\t\tavailable_mcp_tools: state.thought.available_mcp_tools,\n\t\t\t\t\t\t\tavailable_skills: state.thought.available_skills,\n\t\t\t\t\t\t\tcurrent_step: state.thought.current_step,\n\t\t\t\t\t\t\tprevious_steps: state.thought.previous_steps,\n\t\t\t\t\t\t\tremaining_steps: state.thought.remaining_steps,\n\t\t\t\t\t\t\tthought_type: state.thought.thought_type,\n\t\t\t\t\t\t\tquality_score: state.thought.quality_score,\n\t\t\t\t\t\t\tconfidence: state.thought.confidence,\n\t\t\t\t\t\t\thypothesis_id: state.thought.hypothesis_id,\n\t\t\t\t\t\t\tconfidence_signals: state.reasoning.confidenceSignals,\n\t\t\t\t\t\t\treasoning_stats: state.reasoning.reasoningStats,\n\t\t\t\t\t\t\t...(state.reasoning.graphContext !== undefined && {\n\t\t\t\t\t\t\t\tgraph_context: state.reasoning.graphContext,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...(state.reasoning.reasoningHints.length > 0 && {\n\t\t\t\t\t\t\t\treasoning_hints: state.reasoning.reasoningHints,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...(state.decision !== undefined && { strategy_hint: state.decision }),\n\t\t\t\t\t\t\t...(state.warnings.length > 0 && { warnings: state.warnings.slice(0, 3) }),\n\t\t\t\t\t\t\tsession_id: sessionId,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Run the configured reasoning strategy and return its decision.\n\t * Strategy errors omit the decision from the public response.\n\t * @private\n\t */\n\tprivate _runStrategy(\n\t\tcurrentThought: ThoughtData,\n\t\tevidence: ActiveEvidenceProjection | undefined,\n\t\tstats: ReturnType<ThoughtEvaluator['computeReasoningStats']>\n\t): StrategyDecision | undefined {\n\t\tconst sessionId = currentThought.session_id;\n\t\tlet decision: StrategyDecision | undefined;\n\t\ttry {\n\t\t\tif (evidence !== undefined) {\n\t\t\t\tdecision = this.strategy.decide({ sessionId, evidence, stats, currentThought });\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis._logger.warn('Reasoning strategy threw — omitting strategy hint', {\n\t\t\t\tstrategy: this.strategy.name,\n\t\t\t\terror: getErrorMessage(error),\n\t\t\t});\n\t\t}\n\n\t\t// Auto-compression trigger: when strategy terminates a branch and\n\t\t// compression is enabled, summarize the branch subtree. Compression\n\t\t// failures must NEVER break the thought pipeline.\n\t\tif (decision?.action === 'terminate' && this._compressionService && currentThought.branch_id) {\n\t\t\ttry {\n\t\t\t\tconst branchRoot = this._findBranchRoot(sessionId, currentThought.branch_id);\n\t\t\t\tif (branchRoot) {\n\t\t\t\t\tthis._compressionService.compressBranch(\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tcurrentThought.branch_id,\n\t\t\t\t\t\tbranchRoot as ThoughtId\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tthis._logger.debug('Compression auto-trigger failed', {\n\t\t\t\t\terror: getErrorMessage(err),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn decision;\n\t}\n\n\t/**\n\t * Locate the root thought id for a branch.\n\t * Prefers GraphView.branchThoughts() when an EdgeStore is available;\n\t * falls back to historyManager.getBranches(sessionId)[branchId][0].id.\n\t * @private\n\t */\n\tprivate _findBranchRoot(sessionId: SessionId, branchId: BranchId): string | undefined {\n\t\tconst edgeStore = this._getEdgeStore();\n\t\tconst branches = this.historyManager.getBranches(sessionId);\n\t\tconst branchList = branches[branchId];\n\t\tconst firstId = branchList?.[0]?.id;\n\t\tif (edgeStore && firstId) {\n\t\t\tconst graph = new GraphView(edgeStore);\n\t\t\tconst ids = graph.branchThoughts(sessionId, firstId);\n\t\t\tif (ids.length > 0) return ids[0];\n\t\t}\n\t\treturn firstId;\n\t}\n\n\t/** Access the EdgeStore via IHistoryManager. @private */\n\tprivate _getEdgeStore(): IEdgeStore | undefined {\n\t\treturn this.historyManager.getEdgeStore();\n\t}\n\n\t/**\n\t * Validates and normalizes thought input.\n\t *\n\t * Ensures that thought numbers are consistent and within valid ranges.\n\t * If `thought_number` exceeds `total_thoughts`, `total_thoughts` is\n\t * automatically adjusted to match and a warning is emitted.\n\t *\n\t * @param input - The input to validate\n\t * @returns Object with validated input and any warnings generated\n\t * @private\n\t *\n\t * @example\n\t * ```typescript\n\t * // Auto-adjusts total_thoughts when thought_number exceeds it\n\t * const { result, warnings } = this.validateInput(input);\n\t * // result.total_thoughts === 10 (auto-adjusted from 5)\n\t * // warnings === ['Auto-adjusted total_thoughts from 5 to 10 to match thought_number']\n\t * ```\n\t */\n\tprivate validateInput(input: ThoughtData): {\n\t\tresult: ThoughtData;\n\t\twarnings: string[];\n\t} {\n\t\tconst warnings: string[] = [];\n\t\tif (input.thought_number > input.total_thoughts) {\n\t\t\tconst originalTotal = input.total_thoughts;\n\t\t\twarnings.push(\n\t\t\t\t`[${WARNING_CODES.TOTAL_THOUGHTS_ADJUSTED}] Auto-adjusted total_thoughts from ${originalTotal} to ${input.thought_number} to match thought_number`\n\t\t\t);\n\t\t\tthis._logger.warn('Auto-adjusted total_thoughts to match thought_number', {\n\t\t\t\tthought_number: input.thought_number,\n\t\t\t\toriginal_total_thoughts: originalTotal,\n\t\t\t\tadjusted_total_thoughts: input.thought_number,\n\t\t\t});\n\t\t\tinput.total_thoughts = input.thought_number;\n\t\t}\n\t\treturn { result: input, warnings };\n\t}\n\n\t/**\n\t * Validate new thought-type invariants behind feature flags.\n\t * @private\n\t */\n\tprivate _validateStatelessNewTypes(input: ThoughtData): void {\n\t\tconst t = input.thought_type;\n\t\tif ((t === 'tool_call' || t === 'tool_observation') && !this._features.toolInterleave) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t`Type '${t}' requires the toolInterleave feature flag. Set TRACELATTICE_FEATURES_TOOL_INTERLEAVE=true to enable it.`\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\t(t === 'assumption' || t === 'decomposition' || t === 'backtrack') &&\n\t\t\t!this._features.newThoughtTypes\n\t\t) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t`Type '${t}' requires the newThoughtTypes feature flag. Set TRACELATTICE_FEATURES_NEW_THOUGHT_TYPES=true to enable it, or use '${ThoughtProcessor._getWorkaroundType(t)}' type as a workaround.`\n\t\t\t);\n\t\t}\n\t\tif (t === 'tool_call') {\n\t\t\tif (!input.tool_name) {\n\t\t\t\tthrow new InvalidToolCallError(\n\t\t\t\t\t'tool_call thought ' + input.thought_number + ' missing required tool_name'\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis._validateToolName(input.tool_name);\n\t\t}\n\t\tif (t === 'tool_observation' && !input.continuation_token) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'continuation_token',\n\t\t\t\t'tool_observation thought ' + input.thought_number + ' missing continuation_token'\n\t\t\t);\n\t\t}\n\t\tif (t === 'backtrack') {\n\t\t\tif (input.backtrack_target === undefined) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t'backtrack_target',\n\t\t\t\t\t'backtrack thought ' + input.thought_number + ' requires backtrack_target'\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (input.backtrack_target > input.thought_number) {\n\t\t\t\tthrow new InvalidBacktrackError(\n\t\t\t\t\t'backtrack_target ' +\n\t\t\t\t\t\tinput.backtrack_target +\n\t\t\t\t\t\t' must be <= thought_number ' +\n\t\t\t\t\t\tinput.thought_number\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (t === 'tool_call') {\n\t\t\tthis._validateToolArgumentsShape(input.tool_arguments);\n\t\t}\n\t}\n\n\tprivate _validateNewTypes(input: ThoughtData): ValidatedThought {\n\t\treturn input as ValidatedThought;\n\t}\n\n\t/**\n\t * Validate a tool_call's tool_name against the configured allowlist.\n\t *\n\t * Fails closed: if no tool registry was wired, all tool_call invocations are\n\t * rejected. This prevents arbitrary tool name injection through the protocol.\n\t *\n\t * @param toolName - The tool name from the tool_call thought\n\t * @throws {UnknownToolError} When no registry is wired or the tool is not registered\n\t * @private\n\t */\n\tprivate _validateToolName(toolName: string): void {\n\t\tif (!this._toolRegistry) {\n\t\t\tthrow new UnknownToolError(\n\t\t\t\ttoolName,\n\t\t\t\t`Tool '${toolName}' rejected: no tool registry configured. Tool interleave requires a registered allowlist.`\n\t\t\t);\n\t\t}\n\t\tif (!this._toolRegistry.has(toolName)) {\n\t\t\tthrow new UnknownToolError(toolName);\n\t\t}\n\t}\n\n\t/**\n\t * Returns a workaround thought type for a feature-flagged type.\n\t * @private\n\t */\n\tprivate static _getWorkaroundType(t: 'assumption' | 'decomposition' | 'backtrack'): string {\n\t\tswitch (t) {\n\t\t\tcase 'assumption':\n\t\t\t\treturn 'regular';\n\t\t\tcase 'decomposition':\n\t\t\t\treturn 'hypothesis';\n\t\t\tcase 'backtrack':\n\t\t\t\treturn 'regular';\n\t\t\tdefault:\n\t\t\t\tassertNever(t);\n\t\t}\n\t}\n\n\t/**\n\t * Persist a tool_call thought and return a `suspended` envelope.\n\t * Strategy/evaluator are intentionally skipped.\n\t * @private\n\t */\n\tprivate _handleToolCall(\n\t\tinput: ToolCallThought,\n\t\tadmissionContext: ThoughtAdmissionContext\n\t): CallToolResult {\n\t\tif (input.id === undefined) {\n\t\t\tthrow new ValidationError('id', 'tool_call requires an admitted thought id');\n\t\t}\n\t\tthis.historyManager.addThought(input, admissionContext);\n\t\tif (!this._suspensionStore) {\n\t\t\tthrow new ValidationError('thought_type', 'tool_call requires suspensionStore');\n\t\t}\n\t\tconst record: SuspensionRecord = this._suspensionStore.suspend({\n\t\t\tsessionId: input.session_id,\n\t\t\ttoolCallThoughtNumber: input.thought_number,\n\t\t\ttoolCallThoughtId: input.id,\n\t\t\ttoolName: input.tool_name,\n\t\t\ttoolArguments: input.tool_arguments ?? {},\n\t\t\texpiresAt: 0,\n\t\t});\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text' as const,\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstatus: 'suspended',\n\t\t\t\t\t\t\tcontinuation_token: record.token,\n\t\t\t\t\t\t\ttool_name: record.toolName,\n\t\t\t\t\t\t\ttool_arguments: record.toolArguments,\n\t\t\t\t\t\t\texpires_at: record.expiresAt,\n\t\t\t\t\t\t\tthought_number: input.thought_number,\n\t\t\t\t\t\t\ttotal_thoughts: input.total_thoughts,\n\t\t\t\t\t\t\tsession_id: input.session_id,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Resume from a tool_observation and atomically admit it before consuming the record.\n\t * @private\n\t */\n\tprivate async _handleToolObservation(\n\t\tinput: ToolObservationThought,\n\t\tadmissionContext: ThoughtAdmissionContext\n\t): Promise<void> {\n\t\tif (!this._suspensionStore) {\n\t\t\tthrow new ValidationError('thought_type', 'tool_observation requires suspensionStore');\n\t\t}\n\t\tawait this._suspensionStore.compareAndAdmit(\n\t\t\tinput.continuation_token,\n\t\t\tinput.session_id,\n\t\t\t(record) => {\n\t\t\t\tthis.historyManager.addThought(input, {\n\t\t\t\t\t...admissionContext,\n\t\t\t\t\ttoolInvocationSourceThoughtId: record.toolCallThoughtId,\n\t\t\t\t});\n\t\t\t}\n\t\t);\n\t}\n}\n"],"names":["ThoughtProcessor","Map","historyManager","thoughtFormatter","thoughtEvaluator","logger","strategy","SequentialStrategy","_compressionService","_suspensionStore","_toolRegistry","_features","DEFAULT_FLAGS","_sessionLock","_outcomeRecorder","_lifecycle","SessionLifecycleCoordinator","_calibrator","NullLogger","message","meta","patterns","currentThoughtNumber","sessionId","warnings","p","a","b","pa","pb","cooldowns","undefined","hints","warning","lastFired","input","prepared","operation","error","canonicalSessionId","asSessionId","normalized","normalizeInput","parsed","v","SequentialThinkingSchema","firstIssue","field","item","String","ValidationError","internal","registerBranchId","asBranchId","thought","result","JSON","SequentialThinkingError","getErrorMessage","toolArguments","enforceJsonShape","JsonShapeError","resetState","validationSnapshot","resolveThoughtReference","thoughtNumber","checkedInput","refWarnings","resolvedReferences","validateThoughtCrossReferences","verificationOutcome","prepareVerificationOutcome","allWarnings","validated","admissionContext","formattedThought","signals","decision","buildGraphContext","outcome","history","branches","evidence","graphScope","verificationTargets","confidenceSignals","reasoningStats","patternSignals","reasoningHints","buildActiveEvidenceProjection","state","currentThought","stats","branchRoot","err","branchId","edgeStore","branchList","firstId","graph","GraphView","ids","originalTotal","WARNING_CODES","t","InvalidToolCallError","InvalidBacktrackError","toolName","UnknownToolError","assertNever","record"],"mappings":";;;;;;;;;;;;;;;;AAoJO,MAAMA;;;;;;;;;;;;IAEJ,QAAgB;IAGP,kBAAoC;IAM7C,iBAAiB,IAAIC,MAA2C;IAiBxE,YACSC,cAA+B,EAC/BC,gBAAkC,EAC1CC,gBAAkC,EAClCC,MAAe,EACEC,WAA+B,IAAIC,oBAAoB,EACvDC,mBAAwC,EACxCC,gBAAmC,EACnCC,aAA6B,EAC7BC,YAA0BC,aAAa,EACvCC,YAA2B,EAC3BC,gBAAmC,EACnCC,aAA0C,IAAIC,6BAA6B,EAC3EC,WAAyB,CACzC;aAbOf,cAAc,GAAdA;aACAC,gBAAgB,GAAhBA;aAGSG,QAAQ,GAARA;aACAE,mBAAmB,GAAnBA;aACAC,gBAAgB,GAAhBA;aACAC,aAAa,GAAbA;a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3E,MAAM,cAAc;wBACpC,gBAAgBA,MAAM,cAAc;wBACpC,YAAYA,MAAM,UAAU;oBAC7B,GACA,MACA;gBAEF;aACA;QACF;IACD;IAMA,MAAc,uBACbA,KAA6B,EAC7BuC,gBAAyC,EACzB;QAChB,IAAI,CAAC,IAAI,CAAC,gBAAgB,EACzB,MAAM,IAAIxB,gBAAgB,gBAAgB;QAE3C,MAAM,IAAI,CAAC,gBAAgB,CAAC,eAAe,CAC1Cf,MAAM,kBAAkB,EACxBA,MAAM,UAAU,EAChB,CAAC2E;YACA,IAAI,CAAC,cAAc,CAAC,UAAU,CAAC3E,OAAO;gBACrC,GAAGuC,gBAAgB;gBACnB,+BAA+BoC,OAAO,iBAAiB;YACxD;QACD;IAEF;AACD"}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { PatternSignal } from '../reasoning.js';
|
|
2
|
+
import type { ActiveGraphContext } from './GraphSignalComputer.js';
|
|
3
|
+
import type { VerificationLinks } from './VerificationLinks.js';
|
|
4
|
+
/** Warn about active dependencies on the latest refuted hypothesis outcomes. */
|
|
5
|
+
export declare function detectRefutedHypothesisDependency(links: VerificationLinks, activeGraph?: ActiveGraphContext): PatternSignal[];
|
|
6
|
+
/** Warn after three active thoughts when a critique target remains unaddressed. */
|
|
7
|
+
export declare function detectUnaddressedCritique(links: VerificationLinks, activeGraph?: ActiveGraphContext): PatternSignal[];
|
|
8
|
+
//# sourceMappingURL=GraphPatterns.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"GraphPatterns.d.ts","sourceRoot":"","sources":["../../../src/core/evaluator/GraphPatterns.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAErD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,0BAA0B,CAAC;AACnE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAEhE,gFAAgF;AAChF,wBAAgB,iCAAiC,CAChD,KAAK,EAAE,iBAAiB,EACxB,WAAW,CAAC,EAAE,kBAAkB,GAC9B,aAAa,EAAE,CAuCjB;AAED,mFAAmF;AACnF,wBAAgB,yBAAyB,CACxC,KAAK,EAAE,iBAAiB,EACxB,WAAW,CAAC,EAAE,kBAAkB,GAC9B,aAAa,EAAE,CAsCjB"}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
function detectRefutedHypothesisDependency(links, activeGraph) {
|
|
2
|
+
if (void 0 === activeGraph) return [];
|
|
3
|
+
const { view, sessionId } = activeGraph;
|
|
4
|
+
const thoughtsById = new Map(links.thoughts.flatMap((thought)=>thought.id ? [
|
|
5
|
+
[
|
|
6
|
+
thought.id,
|
|
7
|
+
thought
|
|
8
|
+
]
|
|
9
|
+
] : []));
|
|
10
|
+
const latest = new Map();
|
|
11
|
+
for (const thought of links.thoughts){
|
|
12
|
+
if ('verification' !== thought.thought_type || void 0 === thought.id || void 0 === thought.verification_result) continue;
|
|
13
|
+
const target = links.targetFor(thought.id);
|
|
14
|
+
if (void 0 !== target) latest.set(target, thought);
|
|
15
|
+
}
|
|
16
|
+
const signals = [];
|
|
17
|
+
for (const [id, verifier] of latest){
|
|
18
|
+
if (0 !== verifier.verification_result) continue;
|
|
19
|
+
const hypothesis = thoughtsById.get(id);
|
|
20
|
+
if (void 0 === hypothesis) continue;
|
|
21
|
+
const dependents = view.descendants(sessionId, id, void 0, [
|
|
22
|
+
'derives_from',
|
|
23
|
+
'merge',
|
|
24
|
+
'branch'
|
|
25
|
+
]).filter((dep)=>!view.inbound(sessionId, dep).some((r)=>'revises' === r.kind)).flatMap((dep)=>{
|
|
26
|
+
const thought = thoughtsById.get(dep);
|
|
27
|
+
return void 0 === thought ? [] : [
|
|
28
|
+
thought.thought_number
|
|
29
|
+
];
|
|
30
|
+
});
|
|
31
|
+
if (0 === dependents.length) continue;
|
|
32
|
+
const numbers = [
|
|
33
|
+
hypothesis.thought_number,
|
|
34
|
+
...dependents
|
|
35
|
+
];
|
|
36
|
+
signals.push({
|
|
37
|
+
pattern: 'refuted_hypothesis_dependency',
|
|
38
|
+
severity: 'warning',
|
|
39
|
+
message: `Thought(s) ${dependents.join(', ')} build on hypothesis at thought ${hypothesis.thought_number}, which was refuted at thought ${verifier.thought_number} - revise or backtrack them`,
|
|
40
|
+
thought_range: [
|
|
41
|
+
Math.min(...numbers),
|
|
42
|
+
Math.max(...numbers)
|
|
43
|
+
]
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
return signals;
|
|
47
|
+
}
|
|
48
|
+
function detectUnaddressedCritique(links, activeGraph) {
|
|
49
|
+
if (void 0 === activeGraph) return [];
|
|
50
|
+
const { view, sessionId } = activeGraph;
|
|
51
|
+
const positions = new Map(links.thoughts.flatMap((thought, index)=>thought.id ? [
|
|
52
|
+
[
|
|
53
|
+
thought.id,
|
|
54
|
+
index
|
|
55
|
+
]
|
|
56
|
+
] : []));
|
|
57
|
+
const thoughtsById = new Map(links.thoughts.flatMap((thought)=>thought.id ? [
|
|
58
|
+
[
|
|
59
|
+
thought.id,
|
|
60
|
+
thought
|
|
61
|
+
]
|
|
62
|
+
] : []));
|
|
63
|
+
const signals = [];
|
|
64
|
+
for (const [index, critique] of links.thoughts.entries())if ('critique' === critique.thought_type && void 0 !== critique.id && !(links.thoughts.length - index - 1 < 3)) for (const relation of view.outbound(sessionId, critique.id)){
|
|
65
|
+
if ('critiques' !== relation.kind) continue;
|
|
66
|
+
const target = thoughtsById.get(relation.id);
|
|
67
|
+
if (void 0 === target) continue;
|
|
68
|
+
const addressed = view.inbound(sessionId, relation.id).some((r)=>'revises' === r.kind || 'verifies' === r.kind && (positions.get(r.id) ?? -1) > index);
|
|
69
|
+
if (addressed) continue;
|
|
70
|
+
const numbers = [
|
|
71
|
+
critique.thought_number,
|
|
72
|
+
target.thought_number
|
|
73
|
+
];
|
|
74
|
+
signals.push({
|
|
75
|
+
pattern: 'unaddressed_critique',
|
|
76
|
+
severity: 'warning',
|
|
77
|
+
message: `Critique at thought ${critique.thought_number} of thought ${target.thought_number} has not been addressed by a revision or verification within 3 thoughts`,
|
|
78
|
+
thought_range: [
|
|
79
|
+
Math.min(...numbers),
|
|
80
|
+
Math.max(...numbers)
|
|
81
|
+
]
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
return signals;
|
|
85
|
+
}
|
|
86
|
+
export { detectRefutedHypothesisDependency, detectUnaddressedCritique };
|
|
87
|
+
|
|
88
|
+
//# sourceMappingURL=GraphPatterns.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"core/evaluator/GraphPatterns.js","sources":["../../../src/core/evaluator/GraphPatterns.ts"],"sourcesContent":["import type { ThoughtId } from '../../contracts/ids.js';\nimport type { PatternSignal } from '../reasoning.js';\nimport type { ThoughtData } from '../thought.js';\nimport type { ActiveGraphContext } from './GraphSignalComputer.js';\nimport type { VerificationLinks } from './VerificationLinks.js';\n\n/** Warn about active dependencies on the latest refuted hypothesis outcomes. */\nexport function detectRefutedHypothesisDependency(\n\tlinks: VerificationLinks,\n\tactiveGraph?: ActiveGraphContext\n): PatternSignal[] {\n\tif (activeGraph === undefined) return [];\n\tconst { view, sessionId } = activeGraph;\n\tconst thoughtsById = new Map(\n\t\tlinks.thoughts.flatMap((thought) => (thought.id ? [[thought.id, thought] as const] : []))\n\t);\n\tconst latest = new Map<ThoughtId, ThoughtData>();\n\tfor (const thought of links.thoughts) {\n\t\tif (\n\t\t\tthought.thought_type !== 'verification' ||\n\t\t\tthought.id === undefined ||\n\t\t\tthought.verification_result === undefined\n\t\t)\n\t\t\tcontinue;\n\t\tconst target = links.targetFor(thought.id);\n\t\tif (target !== undefined) latest.set(target, thought);\n\t}\n\tconst signals: PatternSignal[] = [];\n\tfor (const [id, verifier] of latest) {\n\t\tif (verifier.verification_result !== 0) continue;\n\t\tconst hypothesis = thoughtsById.get(id);\n\t\tif (hypothesis === undefined) continue;\n\t\tconst dependents = view\n\t\t\t.descendants(sessionId, id, undefined, ['derives_from', 'merge', 'branch'])\n\t\t\t.filter((dep) => !view.inbound(sessionId, dep).some((r) => r.kind === 'revises'))\n\t\t\t.flatMap((dep) => {\n\t\t\t\tconst thought = thoughtsById.get(dep);\n\t\t\t\treturn thought === undefined ? [] : [thought.thought_number];\n\t\t\t});\n\t\tif (dependents.length === 0) continue;\n\t\tconst numbers = [hypothesis.thought_number, ...dependents];\n\t\tsignals.push({\n\t\t\tpattern: 'refuted_hypothesis_dependency',\n\t\t\tseverity: 'warning',\n\t\t\tmessage: `Thought(s) ${dependents.join(', ')} build on hypothesis at thought ${hypothesis.thought_number}, which was refuted at thought ${verifier.thought_number} - revise or backtrack them`,\n\t\t\tthought_range: [Math.min(...numbers), Math.max(...numbers)],\n\t\t});\n\t}\n\treturn signals;\n}\n\n/** Warn after three active thoughts when a critique target remains unaddressed. */\nexport function detectUnaddressedCritique(\n\tlinks: VerificationLinks,\n\tactiveGraph?: ActiveGraphContext\n): PatternSignal[] {\n\tif (activeGraph === undefined) return [];\n\tconst { view, sessionId } = activeGraph;\n\tconst positions = new Map(\n\t\tlinks.thoughts.flatMap((thought, index) => (thought.id ? [[thought.id, index] as const] : []))\n\t);\n\tconst thoughtsById = new Map(\n\t\tlinks.thoughts.flatMap((thought) => (thought.id ? [[thought.id, thought] as const] : []))\n\t);\n\tconst signals: PatternSignal[] = [];\n\tfor (const [index, critique] of links.thoughts.entries()) {\n\t\tif (\n\t\t\tcritique.thought_type !== 'critique' ||\n\t\t\tcritique.id === undefined ||\n\t\t\tlinks.thoughts.length - index - 1 < 3\n\t\t)\n\t\t\tcontinue;\n\t\tfor (const relation of view.outbound(sessionId, critique.id)) {\n\t\t\tif (relation.kind !== 'critiques') continue;\n\t\t\tconst target = thoughtsById.get(relation.id);\n\t\t\tif (target === undefined) continue;\n\t\t\tconst addressed = view\n\t\t\t\t.inbound(sessionId, relation.id)\n\t\t\t\t.some(\n\t\t\t\t\t(r) =>\n\t\t\t\t\t\tr.kind === 'revises' || (r.kind === 'verifies' && (positions.get(r.id) ?? -1) > index)\n\t\t\t\t);\n\t\t\tif (addressed) continue;\n\t\t\tconst numbers = [critique.thought_number, target.thought_number];\n\t\t\tsignals.push({\n\t\t\t\tpattern: 'unaddressed_critique',\n\t\t\t\tseverity: 'warning',\n\t\t\t\tmessage: `Critique at thought ${critique.thought_number} of thought ${target.thought_number} has not been addressed by a revision or verification within 3 thoughts`,\n\t\t\t\tthought_range: [Math.min(...numbers), Math.max(...numbers)],\n\t\t\t});\n\t\t}\n\t}\n\treturn signals;\n}\n"],"names":["detectRefutedHypothesisDependency","links","activeGraph","undefined","view","sessionId","thoughtsById","Map","thought","latest","target","signals","id","verifier","hypothesis","dependents","dep","r","numbers","Math","detectUnaddressedCritique","positions","index","critique","relation","addressed"],"mappings":"AAOO,SAASA,kCACfC,KAAwB,EACxBC,WAAgC;IAEhC,IAAIA,AAAgBC,WAAhBD,aAA2B,OAAO,EAAE;IACxC,MAAM,EAAEE,IAAI,EAAEC,SAAS,EAAE,GAAGH;IAC5B,MAAMI,eAAe,IAAIC,IACxBN,MAAM,QAAQ,CAAC,OAAO,CAAC,CAACO,UAAaA,QAAQ,EAAE,GAAG;YAAC;gBAACA,QAAQ,EAAE;gBAAEA;aAAQ;SAAU,GAAG,EAAE;IAExF,MAAMC,SAAS,IAAIF;IACnB,KAAK,MAAMC,WAAWP,MAAM,QAAQ,CAAE;QACrC,IACCO,AAAyB,mBAAzBA,QAAQ,YAAY,IACpBA,AAAeL,WAAfK,QAAQ,EAAE,IACVA,AAAgCL,WAAhCK,QAAQ,mBAAmB,EAE3B;QACD,MAAME,SAAST,MAAM,SAAS,CAACO,QAAQ,EAAE;QACzC,IAAIE,AAAWP,WAAXO,QAAsBD,OAAO,GAAG,CAACC,QAAQF;IAC9C;IACA,MAAMG,UAA2B,EAAE;IACnC,KAAK,MAAM,CAACC,IAAIC,SAAS,IAAIJ,OAAQ;QACpC,IAAII,AAAiC,MAAjCA,SAAS,mBAAmB,EAAQ;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,EAAE;gBAAEA;aAAQ;SAAU,GAAG,EAAE;IAExF,MAAMG,UAA2B,EAAE;IACnC,KAAK,MAAM,CAACW,OAAOC,SAAS,IAAItB,MAAM,QAAQ,CAAC,OAAO,GACrD,IACCsB,AAA0B,eAA1BA,SAAS,YAAY,IACrBA,AAAgBpB,WAAhBoB,SAAS,EAAE,KACXtB,CAAAA,MAAM,QAAQ,CAAC,MAAM,GAAGqB,QAAQ,IAAI,IAGrC,KAAK,MAAME,YAAYpB,KAAK,QAAQ,CAACC,WAAWkB,SAAS,EAAE,EAAG;QAC7D,IAAIC,AAAkB,gBAAlBA,SAAS,IAAI,EAAkB;QACnC,MAAMd,SAASJ,aAAa,GAAG,CAACkB,SAAS,EAAE;QAC3C,IAAId,AAAWP,WAAXO,QAAsB;QAC1B,MAAMe,YAAYrB,KAChB,OAAO,CAACC,WAAWmB,SAAS,EAAE,EAC9B,IAAI,CACJ,CAACP,IACAA,AAAW,cAAXA,EAAE,IAAI,IAAmBA,AAAW,eAAXA,EAAE,IAAI,IAAoBI,AAAAA,CAAAA,UAAU,GAAG,CAACJ,EAAE,EAAE,KAAK,EAAC,IAAKK;QAEnF,IAAIG,WAAW;QACf,MAAMP,UAAU;YAACK,SAAS,cAAc;YAAEb,OAAO,cAAc;SAAC;QAChEC,QAAQ,IAAI,CAAC;YACZ,SAAS;YACT,UAAU;YACV,SAAS,CAAC,oBAAoB,EAAEY,SAAS,cAAc,CAAC,YAAY,EAAEb,OAAO,cAAc,CAAC,uEAAuE,CAAC;YACpK,eAAe;gBAACS,KAAK,GAAG,IAAID;gBAAUC,KAAK,GAAG,IAAID;aAAS;QAC5D;IACD;IAED,OAAOP;AACR"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { SessionId } from '../../contracts/ids.js';
|
|
2
|
+
import type { GraphView } from '../graph/GraphView.js';
|
|
3
|
+
import type { GraphSignals } from '../reasoning.js';
|
|
4
|
+
export interface ActiveGraphContext {
|
|
5
|
+
readonly sessionId: SessionId;
|
|
6
|
+
readonly view: GraphView;
|
|
7
|
+
}
|
|
8
|
+
/** Stateless, additive graph analytics; does not affect structural scoring. */
|
|
9
|
+
export declare class GraphSignalComputer {
|
|
10
|
+
compute(ctx: ActiveGraphContext): GraphSignals | undefined;
|
|
11
|
+
}
|
|
12
|
+
//# sourceMappingURL=GraphSignalComputer.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"GraphSignalComputer.d.ts","sourceRoot":"","sources":["../../../src/core/evaluator/GraphSignalComputer.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAEpD,MAAM,WAAW,kBAAkB;IAClC,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;CACzB;AAED,+EAA+E;AAC/E,qBAAa,mBAAmB;IACxB,OAAO,CAAC,GAAG,EAAE,kBAAkB,GAAG,YAAY,GAAG,SAAS;CAajE"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
class GraphSignalComputer {
|
|
2
|
+
compute(ctx) {
|
|
3
|
+
const metrics = ctx.view.metrics(ctx.sessionId);
|
|
4
|
+
if (0 === metrics.edge_count) return;
|
|
5
|
+
return {
|
|
6
|
+
...metrics,
|
|
7
|
+
branching_factor: roundToPrecision(metrics.edge_count / (metrics.node_count - metrics.leaf_count)),
|
|
8
|
+
relational_density: roundToPrecision((metrics.edge_count - metrics.edge_kind_counts.sequence) / metrics.edge_count)
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
function roundToPrecision(value) {
|
|
13
|
+
return Math.round(1e10 * value) / 1e10;
|
|
14
|
+
}
|
|
15
|
+
export { GraphSignalComputer };
|
|
16
|
+
|
|
17
|
+
//# sourceMappingURL=GraphSignalComputer.js.map
|