@iworkforces/tracelattice 2.0.6 → 2.0.8
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 +28 -1
- package/dist/cli.js +296 -196
- package/dist/contracts/summary.d.ts +0 -1
- package/dist/contracts/summary.d.ts.map +1 -1
- package/dist/core/PersistenceRestore.d.ts +1 -1
- package/dist/core/PersistenceRestore.d.ts.map +1 -1
- package/dist/core/PersistenceRestore.js.map +1 -1
- package/dist/core/ThoughtEvaluator.d.ts.map +1 -1
- package/dist/core/ThoughtEvaluator.js.map +1 -1
- package/dist/core/ThoughtFormatter.js.map +1 -1
- package/dist/core/ThoughtProcessor.d.ts.map +1 -1
- package/dist/core/ThoughtProcessor.js.map +1 -1
- package/dist/core/compression/CompressionService.d.ts +6 -4
- package/dist/core/compression/CompressionService.d.ts.map +1 -1
- package/dist/core/compression/CompressionService.js +19 -10
- package/dist/core/compression/CompressionService.js.map +1 -1
- package/dist/core/compression/DehydrationPolicy.d.ts +4 -4
- package/dist/core/compression/DehydrationPolicy.d.ts.map +1 -1
- package/dist/core/compression/DehydrationPolicy.js +3 -6
- package/dist/core/compression/DehydrationPolicy.js.map +1 -1
- package/dist/core/compression/InMemorySummaryStore.d.ts +2 -1
- package/dist/core/compression/InMemorySummaryStore.d.ts.map +1 -1
- package/dist/core/compression/InMemorySummaryStore.js.map +1 -1
- package/dist/core/evaluator/Calibrator.d.ts +1 -1
- package/dist/core/evaluator/Calibrator.d.ts.map +1 -1
- package/dist/core/evaluator/Calibrator.js.map +1 -1
- package/dist/core/evaluator/SignalComputer.d.ts +2 -1
- package/dist/core/evaluator/SignalComputer.d.ts.map +1 -1
- package/dist/core/evaluator/SignalComputer.js.map +1 -1
- package/dist/core/evaluator/internals.d.ts +1 -1
- package/dist/core/evaluator/internals.d.ts.map +1 -1
- package/dist/core/evaluator/internals.js.map +1 -1
- package/dist/core/graph/GraphView.d.ts +13 -1
- package/dist/core/graph/GraphView.d.ts.map +1 -1
- package/dist/core/graph/GraphView.js +34 -0
- package/dist/core/graph/GraphView.js.map +1 -1
- package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.d.ts +6 -6
- package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.d.ts.map +1 -1
- package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.js +16 -2
- package/dist/core/reasoning/strategies/TreeOfThoughtStrategy.js.map +1 -1
- package/dist/core/reasoning/strategies/totScoring.d.ts.map +1 -1
- package/dist/core/reasoning/strategies/totScoring.js.map +1 -1
- package/dist/core/reasoning.d.ts +1 -3
- package/dist/core/reasoning.d.ts.map +1 -1
- package/dist/core/thought.d.ts +1 -1
- package/dist/core/thought.d.ts.map +1 -1
- package/dist/lib.d.ts +20 -6
- package/dist/lib.d.ts.map +1 -1
- package/dist/lib.js +52 -3
- package/dist/lib.js.map +1 -1
- package/dist/transport/HttpHelpers.d.ts +4 -1
- package/dist/transport/HttpHelpers.d.ts.map +1 -1
- package/dist/transport/HttpHelpers.js +61 -11
- package/dist/transport/HttpHelpers.js.map +1 -1
- package/dist/transport/HttpRequestLifecycle.d.ts +15 -1
- package/dist/transport/HttpRequestLifecycle.d.ts.map +1 -1
- package/dist/transport/HttpRequestLifecycle.js +66 -4
- package/dist/transport/HttpRequestLifecycle.js.map +1 -1
- package/dist/transport/HttpTransport.d.ts +2 -0
- package/dist/transport/HttpTransport.d.ts.map +1 -1
- package/dist/transport/HttpTransport.js +75 -38
- package/dist/transport/HttpTransport.js.map +1 -1
- package/dist/transport/StreamableHttpTransport.d.ts +17 -29
- package/dist/transport/StreamableHttpTransport.d.ts.map +1 -1
- package/dist/transport/StreamableHttpTransport.js +153 -124
- package/dist/transport/StreamableHttpTransport.js.map +1 -1
- package/package.json +4 -4
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"summary.d.ts","sourceRoot":"","sources":["../../src/contracts/summary.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gCAAgC,CAAC;AAC9D,OAAO,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAE/D
|
|
1
|
+
{"version":3,"file":"summary.d.ts","sourceRoot":"","sources":["../../src/contracts/summary.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,gCAAgC,CAAC;AAC9D,OAAO,KAAK,EAAE,QAAQ,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,UAAU,CAAC;AAE/D;;;;;;;;;;;;;GAaG;AACH,MAAM,WAAW,aAAa;IAC7B;;;;;;;;;OASG;IACH,GAAG,CAAC,OAAO,EAAE,OAAO,GAAG,IAAI,CAAC;IAE5B;;;;;;;;;;;OAWG;IACH,GAAG,CAAC,EAAE,EAAE,SAAS,GAAG,OAAO,GAAG,SAAS,CAAC;IAExC;;;;;;;;;;;;OAYG;IACH,UAAU,CAAC,SAAS,EAAE,SAAS,GAAG,SAAS,OAAO,EAAE,CAAC;IAErD;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,SAAS,EAAE,SAAS,EAAE,QAAQ,EAAE,QAAQ,GAAG,SAAS,OAAO,EAAE,CAAC;IAExE;;;;;;;;;OASG;IACH,YAAY,CAAC,SAAS,EAAE,SAAS,GAAG,IAAI,CAAC;IAEzC;;;OAGG;IACH,QAAQ,IAAI,IAAI,CAAC;IAEjB;;;;;;;;;;;;OAYG;IACH,IAAI,CAAC,SAAS,CAAC,EAAE,SAAS,GAAG,MAAM,CAAC;CACpC"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { PersistenceBackend } from '../contracts/PersistenceBackend.js';
|
|
2
2
|
import { type BranchId, type SessionId } from '../contracts/ids.js';
|
|
3
|
-
import type { Summary } from '
|
|
3
|
+
import type { Summary } from './compression/Summary.js';
|
|
4
4
|
import type { Edge } from './graph/Edge.js';
|
|
5
5
|
import type { ThoughtData } from './thought.js';
|
|
6
6
|
export type RestoredBranch = {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PersistenceRestore.d.ts","sourceRoot":"","sources":["../../src/core/PersistenceRestore.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,kBAAkB,EAElB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAkC,KAAK,QAAQ,EAAE,KAAK,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACpG,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"PersistenceRestore.d.ts","sourceRoot":"","sources":["../../src/core/PersistenceRestore.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACX,kBAAkB,EAElB,MAAM,oCAAoC,CAAC;AAC5C,OAAO,EAAkC,KAAK,QAAQ,EAAE,KAAK,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACpG,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AAaxD,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAE5C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAEhD,MAAM,MAAM,cAAc,GAAG;IAC5B,QAAQ,CAAC,QAAQ,EAAE,QAAQ,CAAC;IAC5B,QAAQ,CAAC,QAAQ,EAAE,SAAS,WAAW,EAAE,CAAC;CAC1C,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG;IAC7B,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;IAC9B,QAAQ,CAAC,OAAO,EAAE,SAAS,WAAW,EAAE,CAAC;IACzC,QAAQ,CAAC,QAAQ,EAAE,SAAS,cAAc,EAAE,CAAC;IAC7C,QAAQ,CAAC,KAAK,EAAE,SAAS,IAAI,EAAE,CAAC;IAChC,QAAQ,CAAC,SAAS,EAAE,SAAS,OAAO,EAAE,CAAC;CACvC,CAAC;AAEF,MAAM,MAAM,0BAA0B,GAAG;IACxC,QAAQ,CAAC,QAAQ,EAAE,SAAS,eAAe,EAAE,CAAC;CAC9C,CAAC;AA2EF,wBAAsB,uBAAuB,CAC5C,OAAO,EAAE,kBAAkB,GACzB,OAAO,CAAC,0BAA0B,CAAC,CAiBrC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core/PersistenceRestore.js","sources":["../../src/core/PersistenceRestore.ts"],"sourcesContent":["import type {\n\tPersistenceBackend,\n\tSessionScopedPersistenceBackend,\n} from '../contracts/PersistenceBackend.js';\nimport { GLOBAL_SESSION_ID, asSessionId, type BranchId, type SessionId } from '../contracts/ids.js';\nimport type { Summary } from '
|
|
1
|
+
{"version":3,"file":"core/PersistenceRestore.js","sources":["../../src/core/PersistenceRestore.ts"],"sourcesContent":["import type {\n\tPersistenceBackend,\n\tSessionScopedPersistenceBackend,\n} from '../contracts/PersistenceBackend.js';\nimport { GLOBAL_SESSION_ID, asSessionId, type BranchId, type SessionId } from '../contracts/ids.js';\nimport type { Summary } from './compression/Summary.js';\nimport { PersistenceCompatibilityError, PersistenceUnavailableError } from '../errors.js';\nimport { requireSessionScopedPersistence } from '../persistence/SessionScopedPersistence.js';\nimport {\n\tassertBranchScope,\n\tassertEdgeScopes,\n\tassertPersistableThoughtCollections,\n\tassertSummaryScopes,\n\tassertThoughtScope,\n\tassertUniqueRecordIds,\n\tparsePersistenceBranchId,\n\ttype PersistedThoughtCollection,\n} from '../persistence/PersistenceScope.js';\nimport type { Edge } from './graph/Edge.js';\nimport { EdgeStore } from './graph/EdgeStore.js';\nimport type { ThoughtData } from './thought.js';\n\nexport type RestoredBranch = {\n\treadonly branchId: BranchId;\n\treadonly thoughts: readonly ThoughtData[];\n};\n\nexport type RestoredSession = {\n\treadonly sessionId: SessionId;\n\treadonly history: readonly ThoughtData[];\n\treadonly branches: readonly RestoredBranch[];\n\treadonly edges: readonly Edge[];\n\treadonly summaries: readonly Summary[];\n};\n\nexport type PersistenceRestoreSnapshot = {\n\treadonly sessions: readonly RestoredSession[];\n};\n\nfunction validateThoughts(\n\tsessionId: SessionId,\n\thistory: readonly ThoughtData[],\n\tbranches: readonly RestoredBranch[]\n): void {\n\tfor (const thought of history) assertThoughtScope('saveThoughtForSession', sessionId, thought);\n\tfor (const branch of branches) {\n\t\tassertBranchScope('saveBranchForSession', sessionId, branch.branchId, branch.thoughts);\n\t}\n\tconst collections: PersistedThoughtCollection[] = [\n\t\t{ sessionId, thoughts: history },\n\t\t...branches.map((branch) => ({ sessionId, thoughts: branch.thoughts })),\n\t];\n\tif (sessionId === GLOBAL_SESSION_ID) {\n\t\tassertPersistableThoughtCollections(\n\t\t\tcollections.map((collection) => ({\n\t\t\t\tsessionId,\n\t\t\t\tthoughts: collection.thoughts.filter((thought) => thought.id !== undefined),\n\t\t\t})),\n\t\t\t`restore:${sessionId}`\n\t\t);\n\t\treturn;\n\t}\n\tassertPersistableThoughtCollections(collections, `restore:${sessionId}`);\n}\n\nasync function stageSession(\n\tpersistence: SessionScopedPersistenceBackend,\n\tsessionId: SessionId\n): Promise<RestoredSession> {\n\tconst history = await persistence.loadHistoryForSession(sessionId);\n\tconst listedBranches = await persistence.listBranchesForSession(sessionId);\n\tconst branches: RestoredBranch[] = [];\n\tconst seenBranches = new Set<BranchId>();\n\tfor (const listedBranchId of listedBranches) {\n\t\tconst branchId = parsePersistenceBranchId(listedBranchId, `restore:${sessionId}:branches`);\n\t\tif (seenBranches.has(branchId)) {\n\t\t\tthrow new PersistenceCompatibilityError(\n\t\t\t\t`restore:${sessionId}:branches`,\n\t\t\t\t`duplicate branch id '${branchId}'`\n\t\t\t);\n\t\t}\n\t\tseenBranches.add(branchId);\n\t\tconst thoughts = await persistence.loadBranchForSession(sessionId, branchId);\n\t\tif (thoughts === undefined) {\n\t\t\tthrow new PersistenceCompatibilityError(\n\t\t\t\t`restore:${sessionId}:branches:${branchId}`,\n\t\t\t\t'listed branch is missing'\n\t\t\t);\n\t\t}\n\t\tbranches.push(Object.freeze({ branchId, thoughts: Object.freeze([...thoughts]) }));\n\t}\n\tvalidateThoughts(sessionId, history, branches);\n\n\tconst edges = await persistence.loadEdges(sessionId);\n\tassertEdgeScopes(sessionId, edges);\n\tassertUniqueRecordIds(edges, `restore:${sessionId}:edges`, 'edge');\n\tconst validationStore = new EdgeStore();\n\tfor (const restoredEdge of edges) validationStore.addEdge(restoredEdge);\n\n\tconst summaries = await persistence.loadSummaries(sessionId);\n\tassertSummaryScopes(sessionId, summaries);\n\tassertUniqueRecordIds(summaries, `restore:${sessionId}:summaries`, 'summary');\n\n\treturn Object.freeze({\n\t\tsessionId,\n\t\thistory: Object.freeze([...history]),\n\t\tbranches: Object.freeze(branches),\n\t\tedges: Object.freeze([...edges]),\n\t\tsummaries: Object.freeze([...summaries]),\n\t});\n}\n\nexport async function stagePersistenceRestore(\n\tbackend: PersistenceBackend\n): Promise<PersistenceRestoreSnapshot> {\n\tconst persistence = requireSessionScopedPersistence(backend, 'listSessions');\n\tif (!(await persistence.healthy())) throw new PersistenceUnavailableError();\n\n\tconst listedSessions = await persistence.listSessions();\n\tconst sessionIds: SessionId[] = [];\n\tconst seen = new Set<SessionId>();\n\tfor (const listedSessionId of listedSessions) {\n\t\tconst sessionId = asSessionId(listedSessionId);\n\t\tif (seen.has(sessionId)) continue;\n\t\tseen.add(sessionId);\n\t\tsessionIds.push(sessionId);\n\t}\n\n\tconst sessions: RestoredSession[] = [];\n\tfor (const sessionId of sessionIds) sessions.push(await stageSession(persistence, sessionId));\n\treturn Object.freeze({ sessions: Object.freeze(sessions) });\n}\n"],"names":["validateThoughts","sessionId","history","branches","thought","assertThoughtScope","branch","assertBranchScope","collections","GLOBAL_SESSION_ID","assertPersistableThoughtCollections","collection","undefined","stageSession","persistence","listedBranches","seenBranches","Set","listedBranchId","branchId","parsePersistenceBranchId","PersistenceCompatibilityError","thoughts","Object","edges","assertEdgeScopes","assertUniqueRecordIds","validationStore","EdgeStore","restoredEdge","summaries","assertSummaryScopes","stagePersistenceRestore","backend","requireSessionScopedPersistence","PersistenceUnavailableError","listedSessions","sessionIds","seen","listedSessionId","asSessionId","sessions"],"mappings":";;;;;AAuCA,SAASA,iBACRC,SAAoB,EACpBC,OAA+B,EAC/BC,QAAmC;IAEnC,KAAK,MAAMC,WAAWF,QAASG,mBAAmB,yBAAyBJ,WAAWG;IACtF,KAAK,MAAME,UAAUH,SACpBI,kBAAkB,wBAAwBN,WAAWK,OAAO,QAAQ,EAAEA,OAAO,QAAQ;IAEtF,MAAME,cAA4C;QACjD;YAAEP;YAAW,UAAUC;QAAQ;WAC5BC,SAAS,GAAG,CAAC,CAACG,SAAY;gBAAEL;gBAAW,UAAUK,OAAO,QAAQ;YAAC;KACpE;IACD,IAAIL,cAAcQ,mBAAmB,YACpCC,oCACCF,YAAY,GAAG,CAAC,CAACG,aAAgB;YAChCV;YACA,UAAUU,WAAW,QAAQ,CAAC,MAAM,CAAC,CAACP,UAAYA,AAAeQ,WAAfR,QAAQ,EAAE;QAC7D,KACA,CAAC,QAAQ,EAAEH,WAAW;IAIxBS,oCAAoCF,aAAa,CAAC,QAAQ,EAAEP,WAAW;AACxE;AAEA,eAAeY,aACdC,WAA4C,EAC5Cb,SAAoB;IAEpB,MAAMC,UAAU,MAAMY,YAAY,qBAAqB,CAACb;IACxD,MAAMc,iBAAiB,MAAMD,YAAY,sBAAsB,CAACb;IAChE,MAAME,WAA6B,EAAE;IACrC,MAAMa,eAAe,IAAIC;IACzB,KAAK,MAAMC,kBAAkBH,eAAgB;QAC5C,MAAMI,WAAWC,yBAAyBF,gBAAgB,CAAC,QAAQ,EAAEjB,UAAU,SAAS,CAAC;QACzF,IAAIe,aAAa,GAAG,CAACG,WACpB,MAAM,IAAIE,8BACT,CAAC,QAAQ,EAAEpB,UAAU,SAAS,CAAC,EAC/B,CAAC,qBAAqB,EAAEkB,SAAS,CAAC,CAAC;QAGrCH,aAAa,GAAG,CAACG;QACjB,MAAMG,WAAW,MAAMR,YAAY,oBAAoB,CAACb,WAAWkB;QACnE,IAAIG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MAAMwC,WAA8B,EAAE;IACtC,KAAK,MAAMxC,aAAaoC,WAAYI,SAAS,IAAI,CAAC,MAAM5B,aAAaC,aAAab;IAClF,OAAOsB,OAAO,MAAM,CAAC;QAAE,UAAUA,OAAO,MAAM,CAACkB;IAAU;AAC1D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ThoughtEvaluator.d.ts","sourceRoot":"","sources":["../../src/core/ThoughtEvaluator.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAGX,WAAW,EACX,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAqB,KAAK,SAAS,EAAE,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"ThoughtEvaluator.d.ts","sourceRoot":"","sources":["../../src/core/ThoughtEvaluator.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAGX,WAAW,EACX,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAqB,KAAK,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAExE,OAAO,KAAK,EAAE,iBAAiB,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AACvF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAKhD,4EAA4E;AAC5E,MAAM,WAAW,uBAAuB;IACvC,QAAQ,CAAC,cAAc,EAAE,WAAW,CAAC;IACrC,QAAQ,CAAC,SAAS,EAAE,SAAS,CAAC;CAC9B;AAmDD;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,gBAAgB;IAC5B,OAAO,CAAC,QAAQ,CAAC,eAAe,CAAiB;IACjD,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAa;IACzC,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAkB;IACnD,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAc;gBAE9B,UAAU,CAAC,EAAE,WAAW;IAOpC,yEAAyE;IAClE,wBAAwB,CAC9B,OAAO,EAAE,WAAW,EAAE,EACtB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,EAAE,CAAC,EACvC,OAAO,CAAC,EAAE,uBAAuB,GAC/B,iBAAiB;IAqBpB,gEAAgE;IACzD,qBAAqB,CAC3B,OAAO,EAAE,WAAW,EAAE,EACtB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,EAAE,CAAC,GACrC,cAAc;IAKjB,wFAAwF;IACjF,qBAAqB,CAC3B,OAAO,EAAE,WAAW,EAAE,EACtB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,EAAE,CAAC,GACrC,aAAa,EAAE;CAIlB"}
|
|
@@ -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 {\n\tCalibrationMetrics,\n\tCalibrationResult,\n\tICalibrator,\n} from '../contracts/calibrator.js';\nimport { GLOBAL_SESSION_ID, type SessionId } from '../contracts/ids.js';\nimport type { ConfidenceSignals, PatternSignal, ReasoningStats
|
|
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 {\n\tCalibrationMetrics,\n\tCalibrationResult,\n\tICalibrator,\n} from '../contracts/calibrator.js';\nimport { GLOBAL_SESSION_ID, type SessionId } from '../contracts/ids.js';\nimport type { ThoughtType } from '../contracts/reasoning-types.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';\n\n/** Explicit thought and canonical session used for response calibration. */\nexport interface ConfidenceSignalContext {\n\treadonly currentThought: ThoughtData;\n\treadonly sessionId: SessionId;\n}\n\n/**\n * No-op calibrator used when calibration is disabled or no calibrator is injected.\n *\n * @remarks\n * Returns the raw confidence unchanged, exposes `enabled = false`, and reports\n * empty metrics. Keeps the {@link ThoughtEvaluator} constructor zero-arg compatible.\n */\nclass NoOpCalibrator implements ICalibrator {\n\tpublic readonly enabled = false;\n\n\tpublic calibrate(\n\t\trawConfidence: number,\n\t\t_type: ThoughtType,\n\t\t_sessionId: SessionId\n\t): CalibrationResult {\n\t\tconst raw = Math.min(1, Math.max(0, rawConfidence));\n\t\treturn { raw, calibrated: raw, temperature: 1.0, priorWeight: 0 };\n\t}\n\n\tpublic metrics(_sessionId?: SessionId): CalibrationMetrics {\n\t\treturn {\n\t\t\tbrierScore: null,\n\t\t\tece: null,\n\t\t\tsampleCount: 0,\n\t\t\tperTypeBrier: {\n\t\t\t\tregular: null,\n\t\t\t\thypothesis: null,\n\t\t\t\tverification: null,\n\t\t\t\tcritique: null,\n\t\t\t\tsynthesis: null,\n\t\t\t\tmeta: null,\n\t\t\t\ttool_call: null,\n\t\t\t\ttool_observation: null,\n\t\t\t\tassumption: null,\n\t\t\t\tdecomposition: null,\n\t\t\t\tbacktrack: null,\n\t\t\t},\n\t\t};\n\t}\n\n\tpublic refit(_sessionId?: SessionId): void {\n\t\t// no-op\n\t}\n\n\tpublic clearSession(_sessionId: SessionId): void {}\n\n\tpublic clearAll(): void {}\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();\n * const signals = evaluator.computeConfidenceSignals(history, branches);\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 ?? new NoOpCalibrator();\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 { history: h, branches: b } = filterRetracted(history, branches);\n\t\tconst signals = this._signalComputer.computeConfidenceSignals(h, b);\n\t\tif (!this._calibrator.enabled) return signals;\n\n\t\tconst thought = context?.currentThought ?? h[h.length - 1];\n\t\tif (thought?.confidence === undefined) return signals;\n\t\tconst sessionId = context?.sessionId ?? thought.session_id ?? GLOBAL_SESSION_ID;\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): ReasoningStats {\n\t\tconst { history: h, branches: b } = filterRetracted(history, branches);\n\t\treturn this._aggregator.computeReasoningStats(h, b);\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): PatternSignal[] {\n\t\tconst { history: h, branches: b } = filterRetracted(history, branches);\n\t\treturn this._patternDetector.computePatternSignals(h, b);\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":["NoOpCalibrator","rawConfidence","_type","_sessionId","raw","Math","ThoughtEvaluator","calibrator","SignalComputer","Aggregator","PatternDetector","history","branches","context","h","b","filterRetracted","signals","thought","undefined","sessionId","GLOBAL_SESSION_ID","result","t","id","list","Object"],"mappings":";;;;AAoCA,MAAMA;IACW,UAAU,MAAM;IAEzB,UACNC,aAAqB,EACrBC,KAAkB,EAClBC,UAAqB,EACD;QACpB,MAAMC,MAAMC,KAAK,GAAG,CAAC,GAAGA,KAAK,GAAG,CAAC,GAAGJ;QACpC,OAAO;YAAEG;YAAK,YAAYA;YAAK,aAAa;YAAK,aAAa;QAAE;IACjE;IAEO,QAAQD,UAAsB,EAAsB;QAC1D,OAAO;YACN,YAAY;YACZ,KAAK;YACL,aAAa;YACb,cAAc;gBACb,SAAS;gBACT,YAAY;gBACZ,cAAc;gBACd,UAAU;gBACV,WAAW;gBACX,MAAM;gBACN,WAAW;gBACX,kBAAkB;gBAClB,YAAY;gBACZ,eAAe;gBACf,WAAW;YACZ;QACD;IACD;IAEO,MAAMA,UAAsB,EAAQ,CAE3C;IAEO,aAAaA,UAA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AC,EAAE,GAAGC,gBAAgBL,SAASC;QAC7D,OAAO,IAAI,CAAC,gBAAgB,CAAC,qBAAqB,CAACE,GAAGC;IACvD;AACD;AAOA,SAASC,gBACRL,OAAsB,EACtBC,QAAuC;IAEvC,MAAME,IAAIH,QAAQ,MAAM,CAAC,CAACY,IAAM,CAACA,EAAE,SAAS;IAC5C,MAAMR,IAAmC,CAAC;IAC1C,KAAK,MAAM,CAACS,IAAIC,KAAK,IAAIC,OAAO,OAAO,CAACd,UACvCG,CAAC,CAACS,GAAG,GAAGC,KAAK,MAAM,CAAC,CAACF,IAAM,CAACA,EAAE,SAAS;IAExC,OAAO;QAAE,SAAST;QAAG,UAAUC;IAAE;AAClC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core/ThoughtFormatter.js","sources":["../../src/core/ThoughtFormatter.ts"],"sourcesContent":["/**\n * Display formatting for thoughts and recommendations.\n *\n * This module provides the `ThoughtFormatter` class which handles all\n * presentation logic for thought data, including clean, simple output\n * formatting and structured display of tool/skill recommendations.\n *\n * @module formatter\n */\n\nimport chalk from 'chalk';\nimport type { IThoughtFormatter } from './IThoughtFormatter.js';\nimport type { ThoughtType } from './reasoning.js';\nimport type { StepRecommendation } from './step.js';\nimport type { ThoughtData } from './thought.js';\nimport { assertNever } from '../utils.js';\n\ntype ThoughtDisplay = {\n\treadonly icon: string;\n\treadonly label: string;\n\treadonly suffix: string;\n};\n\n/**\n * Formatter for thought data and step recommendations.\n *\n * This class separates presentation concerns from business logic, providing\n * clean, readable output for thoughts with structured display of\n * tool and skill recommendations.\n *\n * @remarks\n * Output Format is clean and simple:\n * - 💭 Thought - Regular thought (blue)\n * - 🔬 Hypothesis - Proposed explanation (magenta)\n * - ✅ Verification - Testing a hypothesis (green)\n * - 🔍 Critique - Self-critique of reasoning (red)\n * - 🧬 Synthesis - Combining thoughts/branches (cyan)\n * - 🧠 Meta - Metacognitive observation (gray)\n * - 🔄 Revision - Thought that revises a previous thought (yellow)\n * - 🌿 Branch - Thought that creates a new branch (green)\n * @example\n * ```typescript\n * const formatter = new ThoughtFormatter();\n *\n * // Format a thought with recommendations\n * const output = formatter.formatThought({\n * thought: 'I need to analyze the data structure',\n * thought_number: 1,\n * total_thoughts: 3,\n * next_thought_needed: true,\n * current_step: {\n * step_description: 'Analyze data structure',\n * recommended_tools: [{\n * tool_name: 'Read',\n * confidence: 0.95,\n * rationale: 'Direct file reading',\n * priority: 1,\n * suggested_inputs: { file_path: './data/schema.json' }\n * }],\n * expected_outcome: 'Understanding of data schema'\n * }\n * });\n *\n * console.log(output);\n * ```\n */\nexport class ThoughtFormatter implements IThoughtFormatter {\n\t/**\n\t * Formats a step recommendation into a readable string.\n\t *\n\t * Creates a structured display of the step description, recommended tools,\n\t * recommended skills, expected outcome, and conditions for the next step.\n\t *\n\t * @param step - The step recommendation to format\n\t * @returns A formatted string representation of the recommendation\n\t *\n\t * @example\n\t * ```typescript\n\t * const step: StepRecommendation = {\n\t * step_description: 'Search for API endpoints',\n\t * recommended_tools: [{\n\t * tool_name: 'Grep',\n\t * confidence: 0.9,\n\t * rationale: 'Best for searching code patterns',\n\t * priority: 1,\n\t * suggested_inputs: { pattern: 'export.*function' }\n\t * }],\n\t * expected_outcome: 'List of all exported API functions',\n\t * next_step_conditions: ['If no results, try broader pattern']\n\t * };\n\t *\n\t * const formatted = formatter.formatRecommendation(step);\n\t * console.log(formatted);\n\t * ```\n\t */\n\tpublic formatRecommendation(step: StepRecommendation): string {\n\t\tconst parts: string[] = [];\n\n\t\t// Add tools if present\n\t\tif (step.recommended_tools?.length) {\n\t\t\tconst toolNames = step.recommended_tools.map((t) => t.tool_name).join(', ');\n\t\t\tparts.push(chalk.cyan(`Tools: ${toolNames}`));\n\t\t}\n\n\t\t// Add skills if present\n\t\tif (step.recommended_skills?.length) {\n\t\t\tconst skillNames = step.recommended_skills.map((s) => s.skill_name).join(', ');\n\t\t\tparts.push(chalk.green(`Skills: ${skillNames}`));\n\t\t}\n\n\t\t// Add expected outcome\n\t\tif (step.expected_outcome) {\n\t\t\tparts.push(chalk.gray(`→ ${step.expected_outcome}`));\n\t\t}\n\n\t\treturn parts.join(' | ');\n\t}\n\n\t/**\n\t * Formats a thought into a clean, simple display.\n\t *\n\t * Creates a clean output containing the thought content with an appropriate\n\t * header indicating the thought type. Priority order for icon selection:\n\t * `is_revision` > `branch_from_thought` > `thought_type`.\n\t *\n\t * Supported `thought_type` icons:\n\t * - `'regular'` (or undefined): 💭 blue \"Thought\" (default)\n\t * - `'hypothesis'`: 🔬 magenta \"Hypothesis\"\n\t * - `'verification'`: ✅ green \"Verification\"\n\t * - `'critique'`: 🔍 red \"Critique\"\n\t * - `'synthesis'`: 🧬 cyan \"Synthesis\"\n\t * - `'meta'`: 🧠 gray \"Meta\"\n\t *\n\t * @param thoughtData - The thought data to format\n\t * @returns A formatted string with thought and recommendations\n\t *\n\t * @example\n\t * ```typescript\n\t * // Regular thought\n\t * const regular = formatter.formatThought({\n\t * thought: 'I should read the configuration file',\n\t * thought_number: 1,\n\t * total_thoughts: 3,\n\t * next_thought_needed: true\n\t * });\n\t * // Output: 💭 Thought 1/3: I should read the configuration file\n\t *\n\t * // With recommendation\n\t * const withRec = formatter.formatThought({\n\t * thought: 'I need to search the codebase',\n\t * thought_number: 1,\n\t * total_thoughts: 3,\n\t * next_thought_needed: true,\n\t * current_step: {\n\t * step_description: 'Search for files',\n\t * recommended_tools: [{ tool_name: 'Grep', priority: 1 }],\n\t * expected_outcome: 'List of matching files'\n\t * }\n\t * });\n\t * // Output:\n\t * // 💭 Thought 1/3: I need to search the codebase\n\t * // → Tools: Grep | List of matching files\n\t * ```\n\t */\n\tpublic formatThought(thoughtData: ThoughtData): string {\n\t\tconst {\n\t\t\tthought_number,\n\t\t\ttotal_thoughts,\n\t\t\tthought,\n\t\t\tcurrent_step,\n\t\t} = thoughtData;\n\n\t\tconst { icon, label, suffix } = resolveThoughtDisplay(thoughtData);\n\n\t\t// Build header: \"💭 Thought 1/3: \"\n\t\tconst retractedTag = thoughtData.retracted ? chalk.red.strikethrough('[RETRACTED] ') : '';\n\t\tconst header = `${icon} ${label} ${thought_number}/${total_thoughts}${suffix}: ${retractedTag}`;\n\n\t\t// Build content lines\n\t\tconst lines: string[] = [];\n\n\t\t// Add the thought content\n\t\tlines.push(`${header}${thought}`);\n\n\t\t// Add recommendation if present\n\t\tif (current_step) {\n\t\t\tconst recommendation = this.formatRecommendation(current_step);\n\t\t\tlines.push(` ${recommendation}`);\n\t\t}\n\n\t\t// Add id if present (for DAG debugging)\n\t\tif (thoughtData.id) {\n\t\t\tlines.push(` ${chalk.gray(`🆔 ${thoughtData.id}`)}`);\n\t\t}\n\n\t\t// Add meta observation if present\n\t\tif (thoughtData.meta_observation) {\n\t\t\tlines.push(` ${chalk.gray(`📝 ${thoughtData.meta_observation}`)}`);\n\t\t}\n\n\t\treturn lines.join('\\n');\n\t}\n}\n\nfunction resolveThoughtDisplay(thoughtData: ThoughtData): ThoughtDisplay {\n\tif (thoughtData.is_revision) {\n\t\treturn {\n\t\t\ticon: chalk.yellow('🔄'),\n\t\t\tlabel: 'Revision',\n\t\t\tsuffix: chalk.gray(` (revise #${thoughtData.revises_thought})`),\n\t\t};\n\t}\n\n\tif (thoughtData.branch_from_thought) {\n\t\treturn {\n\t\t\ticon: chalk.green('🌿'),\n\t\t\tlabel: 'Branch',\n\t\t\tsuffix: chalk.gray(` (from #${thoughtData.branch_from_thought})`),\n\t\t};\n\t}\n\n\tconst thoughtType: ThoughtType = thoughtData.thought_type ?? 'regular';\n\tswitch (thoughtType) {\n\t\tcase 'hypothesis':\n\t\t\treturn { icon: chalk.magenta('🔬'), label: 'Hypothesis', suffix: '' };\n\t\tcase 'verification':\n\t\t\treturn { icon: chalk.green('✅'), label: 'Verification', suffix: '' };\n\t\tcase 'critique':\n\t\t\treturn { icon: chalk.red('🔍'), label: 'Critique', suffix: '' };\n\t\tcase 'synthesis':\n\t\t\treturn { icon: chalk.cyan('🧬'), label: 'Synthesis', suffix: '' };\n\t\tcase 'meta':\n\t\t\treturn { icon: chalk.gray('🧠'), label: 'Meta', suffix: '' };\n\t\tcase 'tool_call':\n\t\t\treturn { icon: chalk.yellow('🔧'), label: 'Tool Call', suffix: '' };\n\t\tcase 'tool_observation':\n\t\t\treturn { icon: chalk.yellow('👁️'), label: 'Tool Observation', suffix: '' };\n\t\tcase 'assumption':\n\t\t\treturn { icon: chalk.yellow('💡'), label: 'Assumption', suffix: '' };\n\t\tcase 'decomposition':\n\t\t\treturn { icon: chalk.cyan('🧩'), label: 'Decomposition', suffix: '' };\n\t\tcase 'backtrack':\n\t\t\treturn { icon: chalk.red('↩️'), label: 'Backtrack', suffix: '' };\n\t\tcase 'regular':\n\t\t\treturn { icon: chalk.blue('💭'), label: 'Thought', suffix: '' };\n\t\tdefault:\n\t\t\tassertNever(thoughtType);\n\t}\n}\n"],"names":["ThoughtFormatter","step","parts","toolNames","t","chalk","skillNames","s","thoughtData","thought_number","total_thoughts","thought","current_step","icon","label","suffix","resolveThoughtDisplay","retractedTag","header","lines","recommendation","thoughtType","assertNever"],"mappings":";;AAkEO,MAAMA;IA6BL,qBAAqBC,IAAwB,EAAU;QAC7D,MAAMC,QAAkB,EAAE;QAG1B,IAAID,KAAK,iBAAiB,EAAE,QAAQ;YACnC,MAAME,YAAYF,KAAK,iBAAiB,CAAC,GAAG,CAAC,CAACG,IAAMA,EAAE,SAAS,EAAE,IAAI,CAAC;YACtEF,MAAM,IAAI,CAACG,MAAM,IAAI,CAAC,CAAC,OAAO,EAAEF,WAAW;QAC5C;QAGA,IAAIF,KAAK,kBAAkB,EAAE,QAAQ;YACpC,MAAMK,aAAaL,KAAK,kBAAkB,CAAC,GAAG,CAAC,CAACM,IAAMA,EAAE,UAAU,EAAE,IAAI,CAAC;YACzEL,MAAM,IAAI,CAACG,MAAM,KAAK,CAAC,CAAC,QAAQ,EAAEC,YAAY;QAC/C;QAGA,IAAIL,KAAK,gBAAgB,EACxBC,MAAM,IAAI,CAACG,M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,"file":"core/ThoughtFormatter.js","sources":["../../src/core/ThoughtFormatter.ts"],"sourcesContent":["/**\n * Display formatting for thoughts and recommendations.\n *\n * This module provides the `ThoughtFormatter` class which handles all\n * presentation logic for thought data, including clean, simple output\n * formatting and structured display of tool/skill recommendations.\n *\n * @module formatter\n */\n\nimport chalk from 'chalk';\nimport type { IThoughtFormatter } from './IThoughtFormatter.js';\nimport type { ThoughtType } from '../contracts/reasoning-types.js';\nimport type { StepRecommendation } from './step.js';\nimport type { ThoughtData } from './thought.js';\nimport { assertNever } from '../utils.js';\n\ntype ThoughtDisplay = {\n\treadonly icon: string;\n\treadonly label: string;\n\treadonly suffix: string;\n};\n\n/**\n * Formatter for thought data and step recommendations.\n *\n * This class separates presentation concerns from business logic, providing\n * clean, readable output for thoughts with structured display of\n * tool and skill recommendations.\n *\n * @remarks\n * Output Format is clean and simple:\n * - 💭 Thought - Regular thought (blue)\n * - 🔬 Hypothesis - Proposed explanation (magenta)\n * - ✅ Verification - Testing a hypothesis (green)\n * - 🔍 Critique - Self-critique of reasoning (red)\n * - 🧬 Synthesis - Combining thoughts/branches (cyan)\n * - 🧠 Meta - Metacognitive observation (gray)\n * - 🔄 Revision - Thought that revises a previous thought (yellow)\n * - 🌿 Branch - Thought that creates a new branch (green)\n * @example\n * ```typescript\n * const formatter = new ThoughtFormatter();\n *\n * // Format a thought with recommendations\n * const output = formatter.formatThought({\n * thought: 'I need to analyze the data structure',\n * thought_number: 1,\n * total_thoughts: 3,\n * next_thought_needed: true,\n * current_step: {\n * step_description: 'Analyze data structure',\n * recommended_tools: [{\n * tool_name: 'Read',\n * confidence: 0.95,\n * rationale: 'Direct file reading',\n * priority: 1,\n * suggested_inputs: { file_path: './data/schema.json' }\n * }],\n * expected_outcome: 'Understanding of data schema'\n * }\n * });\n *\n * console.log(output);\n * ```\n */\nexport class ThoughtFormatter implements IThoughtFormatter {\n\t/**\n\t * Formats a step recommendation into a readable string.\n\t *\n\t * Creates a structured display of the step description, recommended tools,\n\t * recommended skills, expected outcome, and conditions for the next step.\n\t *\n\t * @param step - The step recommendation to format\n\t * @returns A formatted string representation of the recommendation\n\t *\n\t * @example\n\t * ```typescript\n\t * const step: StepRecommendation = {\n\t * step_description: 'Search for API endpoints',\n\t * recommended_tools: [{\n\t * tool_name: 'Grep',\n\t * confidence: 0.9,\n\t * rationale: 'Best for searching code patterns',\n\t * priority: 1,\n\t * suggested_inputs: { pattern: 'export.*function' }\n\t * }],\n\t * expected_outcome: 'List of all exported API functions',\n\t * next_step_conditions: ['If no results, try broader pattern']\n\t * };\n\t *\n\t * const formatted = formatter.formatRecommendation(step);\n\t * console.log(formatted);\n\t * ```\n\t */\n\tpublic formatRecommendation(step: StepRecommendation): string {\n\t\tconst parts: string[] = [];\n\n\t\t// Add tools if present\n\t\tif (step.recommended_tools?.length) {\n\t\t\tconst toolNames = step.recommended_tools.map((t) => t.tool_name).join(', ');\n\t\t\tparts.push(chalk.cyan(`Tools: ${toolNames}`));\n\t\t}\n\n\t\t// Add skills if present\n\t\tif (step.recommended_skills?.length) {\n\t\t\tconst skillNames = step.recommended_skills.map((s) => s.skill_name).join(', ');\n\t\t\tparts.push(chalk.green(`Skills: ${skillNames}`));\n\t\t}\n\n\t\t// Add expected outcome\n\t\tif (step.expected_outcome) {\n\t\t\tparts.push(chalk.gray(`→ ${step.expected_outcome}`));\n\t\t}\n\n\t\treturn parts.join(' | ');\n\t}\n\n\t/**\n\t * Formats a thought into a clean, simple display.\n\t *\n\t * Creates a clean output containing the thought content with an appropriate\n\t * header indicating the thought type. Priority order for icon selection:\n\t * `is_revision` > `branch_from_thought` > `thought_type`.\n\t *\n\t * Supported `thought_type` icons:\n\t * - `'regular'` (or undefined): 💭 blue \"Thought\" (default)\n\t * - `'hypothesis'`: 🔬 magenta \"Hypothesis\"\n\t * - `'verification'`: ✅ green \"Verification\"\n\t * - `'critique'`: 🔍 red \"Critique\"\n\t * - `'synthesis'`: 🧬 cyan \"Synthesis\"\n\t * - `'meta'`: 🧠 gray \"Meta\"\n\t *\n\t * @param thoughtData - The thought data to format\n\t * @returns A formatted string with thought and recommendations\n\t *\n\t * @example\n\t * ```typescript\n\t * // Regular thought\n\t * const regular = formatter.formatThought({\n\t * thought: 'I should read the configuration file',\n\t * thought_number: 1,\n\t * total_thoughts: 3,\n\t * next_thought_needed: true\n\t * });\n\t * // Output: 💭 Thought 1/3: I should read the configuration file\n\t *\n\t * // With recommendation\n\t * const withRec = formatter.formatThought({\n\t * thought: 'I need to search the codebase',\n\t * thought_number: 1,\n\t * total_thoughts: 3,\n\t * next_thought_needed: true,\n\t * current_step: {\n\t * step_description: 'Search for files',\n\t * recommended_tools: [{ tool_name: 'Grep', priority: 1 }],\n\t * expected_outcome: 'List of matching files'\n\t * }\n\t * });\n\t * // Output:\n\t * // 💭 Thought 1/3: I need to search the codebase\n\t * // → Tools: Grep | List of matching files\n\t * ```\n\t */\n\tpublic formatThought(thoughtData: ThoughtData): string {\n\t\tconst {\n\t\t\tthought_number,\n\t\t\ttotal_thoughts,\n\t\t\tthought,\n\t\t\tcurrent_step,\n\t\t} = thoughtData;\n\n\t\tconst { icon, label, suffix } = resolveThoughtDisplay(thoughtData);\n\n\t\t// Build header: \"💭 Thought 1/3: \"\n\t\tconst retractedTag = thoughtData.retracted ? chalk.red.strikethrough('[RETRACTED] ') : '';\n\t\tconst header = `${icon} ${label} ${thought_number}/${total_thoughts}${suffix}: ${retractedTag}`;\n\n\t\t// Build content lines\n\t\tconst lines: string[] = [];\n\n\t\t// Add the thought content\n\t\tlines.push(`${header}${thought}`);\n\n\t\t// Add recommendation if present\n\t\tif (current_step) {\n\t\t\tconst recommendation = this.formatRecommendation(current_step);\n\t\t\tlines.push(` ${recommendation}`);\n\t\t}\n\n\t\t// Add id if present (for DAG debugging)\n\t\tif (thoughtData.id) {\n\t\t\tlines.push(` ${chalk.gray(`🆔 ${thoughtData.id}`)}`);\n\t\t}\n\n\t\t// Add meta observation if present\n\t\tif (thoughtData.meta_observation) {\n\t\t\tlines.push(` ${chalk.gray(`📝 ${thoughtData.meta_observation}`)}`);\n\t\t}\n\n\t\treturn lines.join('\\n');\n\t}\n}\n\nfunction resolveThoughtDisplay(thoughtData: ThoughtData): ThoughtDisplay {\n\tif (thoughtData.is_revision) {\n\t\treturn {\n\t\t\ticon: chalk.yellow('🔄'),\n\t\t\tlabel: 'Revision',\n\t\t\tsuffix: chalk.gray(` (revise #${thoughtData.revises_thought})`),\n\t\t};\n\t}\n\n\tif (thoughtData.branch_from_thought) {\n\t\treturn {\n\t\t\ticon: chalk.green('🌿'),\n\t\t\tlabel: 'Branch',\n\t\t\tsuffix: chalk.gray(` (from #${thoughtData.branch_from_thought})`),\n\t\t};\n\t}\n\n\tconst thoughtType: ThoughtType = thoughtData.thought_type ?? 'regular';\n\tswitch (thoughtType) {\n\t\tcase 'hypothesis':\n\t\t\treturn { icon: chalk.magenta('🔬'), label: 'Hypothesis', suffix: '' };\n\t\tcase 'verification':\n\t\t\treturn { icon: chalk.green('✅'), label: 'Verification', suffix: '' };\n\t\tcase 'critique':\n\t\t\treturn { icon: chalk.red('🔍'), label: 'Critique', suffix: '' };\n\t\tcase 'synthesis':\n\t\t\treturn { icon: chalk.cyan('🧬'), label: 'Synthesis', suffix: '' };\n\t\tcase 'meta':\n\t\t\treturn { icon: chalk.gray('🧠'), label: 'Meta', suffix: '' };\n\t\tcase 'tool_call':\n\t\t\treturn { icon: chalk.yellow('🔧'), label: 'Tool Call', suffix: '' };\n\t\tcase 'tool_observation':\n\t\t\treturn { icon: chalk.yellow('👁️'), label: 'Tool Observation', suffix: '' };\n\t\tcase 'assumption':\n\t\t\treturn { icon: chalk.yellow('💡'), label: 'Assumption', suffix: '' };\n\t\tcase 'decomposition':\n\t\t\treturn { icon: chalk.cyan('🧩'), label: 'Decomposition', suffix: '' };\n\t\tcase 'backtrack':\n\t\t\treturn { icon: chalk.red('↩️'), label: 'Backtrack', suffix: '' };\n\t\tcase 'regular':\n\t\t\treturn { icon: chalk.blue('💭'), label: 'Thought', suffix: '' };\n\t\tdefault:\n\t\t\tassertNever(thoughtType);\n\t}\n}\n"],"names":["ThoughtFormatter","step","parts","toolNames","t","chalk","skillNames","s","thoughtData","thought_number","total_thoughts","thought","current_step","icon","label","suffix","resolveThoughtDisplay","retractedTag","header","lines","recommendation","thoughtType","assertNever"],"mappings":";;AAkEO,MAAMA;IA6BL,qBAAqBC,IAAwB,EAAU;QAC7D,MAAMC,QAAkB,EAAE;QAG1B,IAAID,KAAK,iBAAiB,EAAE,QAAQ;YACnC,MAAME,YAAYF,KAAK,iBAAiB,CAAC,GAAG,CAAC,CAACG,IAAMA,EAAE,SAAS,EAAE,IAAI,CAAC;YACtEF,MAAM,IAAI,CAACG,MAAM,IAAI,CAAC,CAAC,OAAO,EAAEF,WAAW;QAC5C;QAGA,IAAIF,KAAK,kBAAkB,EAAE,QAAQ;YACpC,MAAMK,aAAaL,KAAK,kBAAkB,CAAC,GAAG,CAAC,CAACM,IAAMA,EAAE,UAAU,EAAE,IAAI,CAAC;YACzEL,MAAM,IAAI,CAACG,MAAM,KAAK,CAAC,CAAC,QAAQ,EAAEC,YAAY;QAC/C;QAGA,IAAIL,KAAK,gBAAgB,EACxBC,MAAM,IAAI,CAACG,MAAM,IAAI,CAAC,CAAC,EAAE,EAAEJ,KAAK,gBAAgB,EAAE;QAGnD,OAAOC,MAAM,IAAI,CAAC;IACnB;IAgDO,cAAcM,WAAwB,EAAU;QACtD,MAAM,EACLC,cAAc,EACdC,cAAc,EACdC,OAAO,EACPC,YAAY,EACZ,GAAGJ;QAEJ,MAAM,EAAEK,IAAI,EAAEC,KAAK,EAAEC,MAAM,EAAE,GAAGC,sBAAsBR;QAGtD,MAAMS,eAAeT,YAAY,SAAS,GAAGH,MAAM,GAAG,CAAC,aAAa,CAAC,kBAAkB;QACvF,MAAMa,SAAS,GAAGL,KAAK,CAAC,EAAEC,MAAM,CAAC,EAAEL,eAAe,CAAC,EAAEC,iBAAiBK,OAAO,EAAE,EAAEE,cAA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kBG;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;IA4CvB;;;OAGG;YACW,sBAAsB;CAepC"}
|
|
@@ -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\tGLOBAL_SESSION_ID,\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 { 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, 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 sessionId: SessionId;\n\treadonly exposeSessionId: boolean;\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 sessionId: SessionId;\n\treadonly exposeSessionId: boolean;\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({ thought: '...', thought_number: 1, total_thoughts: 5, next_thought_needed: true });\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\tconst sessionKey = sessionId ?? GLOBAL_SESSION_ID;\n\t\tif (!this._hintCooldowns.has(sessionKey)) {\n\t\t\tthis._hintCooldowns.set(sessionKey, new Map());\n\t\t}\n\t\tconst cooldowns = this._hintCooldowns.get(sessionKey)!;\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 * });\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 operation = async (): Promise<CallToolResult> => {\n\t\t\t\tif (this._sessionLock !== undefined) {\n\t\t\t\t\treturn await this._sessionLock.withLock(prepared.sessionId, () =>\n\t\t\t\t\t\tthis._processInner(prepared)\n\t\t\t\t\t);\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(prepared.sessionId);\n\t\t\t\treturn await this._lifecycle.withSessionReset(prepared.sessionId, operation);\n\t\t\t}\n\t\t\treturn await this._lifecycle.runOperation(prepared.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 exposeSessionId = internal.session_id !== undefined;\n\t\tconst sessionId = internal.session_id ?? GLOBAL_SESSION_ID;\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\tsessionId,\n\t\t\texposeSessionId,\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\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, sessionId, exposeSessionId, resetState, registerBranchId } = prepared;\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\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, sessionId, exposeSessionId, 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, sessionId, 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, sessionId);\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(\n\t\t\tcheckedInput,\n\t\t\tsignals.history,\n\t\t\tsignals.reasoningStats,\n\t\t\tsessionId\n\t\t);\n\n\t\treturn this._buildSuccessResponse({\n\t\t\tthought: checkedInput,\n\t\t\tsessionId,\n\t\t\texposeSessionId,\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(\n\t\tinput: ThoughtData,\n\t\tsessionId?: SessionId\n\t): ReasoningSignalBundle {\n\t\tconst history = this.historyManager.getHistory(sessionId);\n\t\tconst branches = this.historyManager.getBranches(sessionId);\n\t\tconst confidenceSignals = this._thoughtEvaluator.computeConfidenceSignals(history, branches, {\n\t\t\tcurrentThought: input,\n\t\t\tsessionId: sessionId ?? GLOBAL_SESSION_ID,\n\t\t});\n\t\tconst reasoningStats = this._thoughtEvaluator.computeReasoningStats(history, branches);\n\t\tconst patternSignals = this._thoughtEvaluator.computePatternSignals(history, branches);\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\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(state.sessionId),\n\t\t\t\t\t\t\tthought_history_length: this.historyManager.getHistoryLength(state.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\t...(state.exposeSessionId ? { session_id: state.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\tsessionId?: SessionId\n\t): StrategyDecision | undefined {\n\t\tlet decision: StrategyDecision | undefined;\n\t\ttry {\n\t\t\tconst edgeStore = this._getEdgeStore();\n\t\t\tconst graph = edgeStore ? new GraphView(edgeStore) : undefined;\n\t\t\tdecision = this.strategy.decide({\n\t\t\t\tsessionId: sessionId ?? GLOBAL_SESSION_ID,\n\t\t\t\thistory,\n\t\t\t\tgraph,\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 sid = sessionId ?? GLOBAL_SESSION_ID;\n\t\t\t\tconst branchRoot = this._findBranchRoot(sid, currentThought.branch_id);\n\t\t\t\tif (branchRoot) {\n\t\t\t\t\tthis._compressionService.compressBranch(\n\t\t\t\t\t\tsid,\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()[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\tsessionId: SessionId,\n\t\texposeSessionId: boolean,\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,\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\t...(exposeSessionId ? { session_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 * 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\tsessionId: SessionId,\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(input.continuation_token, sessionId, (record) => {\n\t\t\tthis.historyManager.addThought(input, {\n\t\t\t\t...admissionContext,\n\t\t\t\ttoolInvocationSourceThoughtId: record.toolCallThoughtId,\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","sessionKey","GLOBAL_SESSION_ID","cooldowns","hints","warning","lastFired","undefined","input","prepared","operation","error","canonicalSessionId","asSessionId","normalized","normalizeInput","parsed","v","SequentialThinkingSchema","firstIssue","field","item","String","ValidationError","internal","exposeSessionId","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","confidenceSignals","reasoningStats","patternSignals","reasoningHints","state","currentThought","stats","edgeStore","graph","GraphView","sid","branchRoot","err","branchId","branchList","firstId","ids","originalTotal","WARNING_CODES","t","InvalidToolCallError","InvalidBacktrackError","toolName","UnknownToolError","assertNever","record"],"mappings":";;;;;;;;;;;;;;AA2IO,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,SAAS,GAATA;aACAE,YAAY,GAAZA;aACAC,gBAAgB,GAAhBA;aACAC,UAAU,GAAVA;aACAE,WAAW,GAAXA;QAEjB,IAAI,CAAC,iBAAiB,GAAGb;QACzB,IAAI,CAAC,OAAO,GAAGC,UAAU,IAAIa;IAC9B;IAQQ,IAAIC,OAAe,EAAEC,IAA8B,EAAQ;QAClE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mBAAmBA,MAAM,EAAE;YAC3B,UAAUA,MAAM,SAAS;YACzB,eAAeA,MAAM,cAAc,IAAI,CAAC;YACxC,WAAW;QACZ;QACA,OAAO;YACN,SAAS;gBACR;oBACC,MAAM;oBACN,MAAMsB,KAAK,SAAS,CACnB;wBACC,QAAQ;wBACR,oBAAoBmD,OAAO,KAAK;wBAChC,WAAWA,OAAO,QAAQ;wBAC1B,gBAAgBA,OAAO,aAAa;wBACpC,YAAYA,OAAO,SAAS;wBAC5B,gBAAgBzE,MAAM,cAAc;wBACpC,gBAAgBA,MAAM,cAAc;wBACpC,GAAIiB,kBAAkB;4BAAE,YAAY/B;wBAAU,IAAI,CAAC,CAAC;oBACrD,GACA,MACA;gBAEF;aACA;QACF;IACD;IAMA,MAAc,uBACbc,KAA6B,EAC7Bd,SAAoB,EACpBuD,gBAAyC,EACzB;QAChB,IAAI,CAAC,IAAI,CAAC,gBAAgB,EACzB,MAAM,IAAI1B,gBAAgB,gBAAgB;QAE3C,MAAM,IAAI,CAAC,gBAAgB,CAAC,eAAe,CAACf,MAAM,kBAAkB,EAAEd,WAAW,CAACuF;YACjF,IAAI,CAAC,cAAc,CAAC,UAAU,CAACzE,OAAO;gBACrC,GAAGyC,gBAAgB;gBACnB,+BAA+BgC,OAAO,iBAAiB;YACxD;QACD;IACD;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\tGLOBAL_SESSION_ID,\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 { 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 sessionId: SessionId;\n\treadonly exposeSessionId: boolean;\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 sessionId: SessionId;\n\treadonly exposeSessionId: boolean;\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({ thought: '...', thought_number: 1, total_thoughts: 5, next_thought_needed: true });\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\tconst sessionKey = sessionId ?? GLOBAL_SESSION_ID;\n\t\tif (!this._hintCooldowns.has(sessionKey)) {\n\t\t\tthis._hintCooldowns.set(sessionKey, new Map());\n\t\t}\n\t\tconst cooldowns = this._hintCooldowns.get(sessionKey)!;\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 * });\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 operation = async (): Promise<CallToolResult> => {\n\t\t\t\tif (this._sessionLock !== undefined) {\n\t\t\t\t\treturn await this._sessionLock.withLock(prepared.sessionId, () =>\n\t\t\t\t\t\tthis._processInner(prepared)\n\t\t\t\t\t);\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(prepared.sessionId);\n\t\t\t\treturn await this._lifecycle.withSessionReset(prepared.sessionId, operation);\n\t\t\t}\n\t\t\treturn await this._lifecycle.runOperation(prepared.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 exposeSessionId = internal.session_id !== undefined;\n\t\tconst sessionId = internal.session_id ?? GLOBAL_SESSION_ID;\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\tsessionId,\n\t\t\texposeSessionId,\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\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, sessionId, exposeSessionId, resetState, registerBranchId } = prepared;\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\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, sessionId, exposeSessionId, 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, sessionId, 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, sessionId);\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(\n\t\t\tcheckedInput,\n\t\t\tsignals.history,\n\t\t\tsignals.reasoningStats,\n\t\t\tsessionId\n\t\t);\n\n\t\treturn this._buildSuccessResponse({\n\t\t\tthought: checkedInput,\n\t\t\tsessionId,\n\t\t\texposeSessionId,\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(\n\t\tinput: ThoughtData,\n\t\tsessionId?: SessionId\n\t): ReasoningSignalBundle {\n\t\tconst history = this.historyManager.getHistory(sessionId);\n\t\tconst branches = this.historyManager.getBranches(sessionId);\n\t\tconst confidenceSignals = this._thoughtEvaluator.computeConfidenceSignals(history, branches, {\n\t\t\tcurrentThought: input,\n\t\t\tsessionId: sessionId ?? GLOBAL_SESSION_ID,\n\t\t});\n\t\tconst reasoningStats = this._thoughtEvaluator.computeReasoningStats(history, branches);\n\t\tconst patternSignals = this._thoughtEvaluator.computePatternSignals(history, branches);\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\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(state.sessionId),\n\t\t\t\t\t\t\tthought_history_length: this.historyManager.getHistoryLength(state.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\t...(state.exposeSessionId ? { session_id: state.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\tsessionId?: SessionId\n\t): StrategyDecision | undefined {\n\t\tlet decision: StrategyDecision | undefined;\n\t\ttry {\n\t\t\tconst edgeStore = this._getEdgeStore();\n\t\t\tconst graph = edgeStore ? new GraphView(edgeStore) : undefined;\n\t\t\tdecision = this.strategy.decide({\n\t\t\t\tsessionId: sessionId ?? GLOBAL_SESSION_ID,\n\t\t\t\thistory,\n\t\t\t\tgraph,\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 sid = sessionId ?? GLOBAL_SESSION_ID;\n\t\t\t\tconst branchRoot = this._findBranchRoot(sid, currentThought.branch_id);\n\t\t\t\tif (branchRoot) {\n\t\t\t\t\tthis._compressionService.compressBranch(\n\t\t\t\t\t\tsid,\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()[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\tsessionId: SessionId,\n\t\texposeSessionId: boolean,\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,\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\t...(exposeSessionId ? { session_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 * 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\tsessionId: SessionId,\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(input.continuation_token, sessionId, (record) => {\n\t\t\tthis.historyManager.addThought(input, {\n\t\t\t\t...admissionContext,\n\t\t\t\ttoolInvocationSourceThoughtId: record.toolCallThoughtId,\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","sessionKey","GLOBAL_SESSION_ID","cooldowns","hints","warning","lastFired","undefined","input","prepared","operation","error","canonicalSessionId","asSessionId","normalized","normalizeInput","parsed","v","SequentialThinkingSchema","firstIssue","field","item","String","ValidationError","internal","exposeSessionId","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","confidenceSignals","reasoningStats","patternSignals","reasoningHints","state","currentThought","stats","edgeStore","graph","GraphView","sid","branchRoot","err","branchId","branchList","firstId","ids","originalTotal","WARNING_CODES","t","InvalidToolCallError","InvalidBacktrackError","toolName","UnknownToolError","assertNever","record"],"mappings":";;;;;;;;;;;;;;AA4IO,MAAMA;;;;;;;;;;;;IAEJ,QAAgB;IAGP,kBAAoC;IAM7C,iBAAiB,IAAIC,MAA2C;IAiBxE,YACSC,cAA+B,EAC/BC,gBAAkC,EAC1CC,gBAAkC,EA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,WAAW,CAACuF;YACjF,IAAI,CAAC,cAAc,CAAC,UAAU,CAACzE,OAAO;gBACrC,GAAGyC,gBAAgB;gBACnB,+BAA+BgC,OAAO,iBAAiB;YACxD;QACD;IACD;AACD"}
|
|
@@ -12,7 +12,8 @@
|
|
|
12
12
|
*
|
|
13
13
|
* @module core/compression/CompressionService
|
|
14
14
|
*/
|
|
15
|
-
import type { ISummaryStore
|
|
15
|
+
import type { ISummaryStore } from '../../contracts/summary.js';
|
|
16
|
+
import type { Summary } from './Summary.js';
|
|
16
17
|
import type { IEdgeStore } from '../../contracts/interfaces.js';
|
|
17
18
|
import type { Logger } from '../../logger/StructuredLogger.js';
|
|
18
19
|
import type { IHistoryManager } from '../IHistoryManager.js';
|
|
@@ -51,10 +52,11 @@ export declare class CompressionService {
|
|
|
51
52
|
/** Collect the root and all of its descendants (chronological BFS). */
|
|
52
53
|
private _collectCovered;
|
|
53
54
|
/**
|
|
54
|
-
* Resolve
|
|
55
|
-
*
|
|
55
|
+
* Resolve candidate ids against one stable session snapshot. Main-history
|
|
56
|
+
* records take precedence over branch copies; branch-only records are added
|
|
57
|
+
* in declared branch order. Graph ids absent from the snapshot are omitted.
|
|
56
58
|
*/
|
|
57
|
-
private
|
|
59
|
+
private _resolveThoughts;
|
|
58
60
|
/**
|
|
59
61
|
* Mean of (`calibrated_confidence` ?? `confidence` ?? 0) across covered.
|
|
60
62
|
* Returns 0 when no thoughts are covered.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"CompressionService.d.ts","sourceRoot":"","sources":["../../../src/core/compression/CompressionService.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,OAAO,EAAE,MAAM,
|
|
1
|
+
{"version":3,"file":"CompressionService.d.ts","sourceRoot":"","sources":["../../../src/core/compression/CompressionService.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,KAAK,EAAE,aAAa,E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 @@ class CompressionService {
|
|
|
56
56
|
compressBranch(sessionId, branchId, rootThoughtId) {
|
|
57
57
|
const existing = this._findExistingForRoot(sessionId, branchId, rootThoughtId);
|
|
58
58
|
if (existing) return existing;
|
|
59
|
-
const
|
|
60
|
-
const
|
|
59
|
+
const snapshot = this._deps.historyManager.inspectSession(sessionId);
|
|
60
|
+
const candidateIds = this._collectCovered(sessionId, rootThoughtId);
|
|
61
|
+
const thoughts = this._resolveThoughts(snapshot, candidateIds);
|
|
62
|
+
const coveredIds = thoughts.flatMap((thought)=>void 0 === thought.id ? [] : [
|
|
63
|
+
thought.id
|
|
64
|
+
]);
|
|
61
65
|
const summary = {
|
|
62
66
|
id: generateUlid(),
|
|
63
67
|
sessionId,
|
|
@@ -90,16 +94,21 @@ class CompressionService {
|
|
|
90
94
|
...descendants
|
|
91
95
|
];
|
|
92
96
|
}
|
|
93
|
-
|
|
94
|
-
const history = this._deps.historyManager.getHistory(sessionId);
|
|
97
|
+
_resolveThoughts(snapshot, candidateIds) {
|
|
95
98
|
const byId = new Map();
|
|
96
|
-
for (const
|
|
97
|
-
const
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
99
|
+
for (const thought of snapshot.history)if (void 0 !== thought.id && !byId.has(thought.id)) byId.set(thought.id, thought);
|
|
100
|
+
for (const branchId of snapshot.branchIds)for (const thought of snapshot.branches[branchId] ?? [])if (void 0 !== thought.id && !byId.has(thought.id)) byId.set(thought.id, thought);
|
|
101
|
+
const resolved = [];
|
|
102
|
+
const seen = new Set();
|
|
103
|
+
for (const id of candidateIds){
|
|
104
|
+
if (seen.has(id)) continue;
|
|
105
|
+
const thought = byId.get(id);
|
|
106
|
+
if (void 0 !== thought) {
|
|
107
|
+
seen.add(id);
|
|
108
|
+
resolved.push(thought);
|
|
109
|
+
}
|
|
101
110
|
}
|
|
102
|
-
return
|
|
111
|
+
return resolved;
|
|
103
112
|
}
|
|
104
113
|
_meanConfidence(thoughts) {
|
|
105
114
|
if (0 === thoughts.length) return 0;
|