@iworkforces/tracelattice 2.3.5 → 2.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -5
- package/dist/ServerConfig.d.ts +16 -0
- package/dist/ServerConfig.d.ts.map +1 -1
- package/dist/ServerConfig.js +11 -0
- package/dist/ServerConfig.js.map +1 -1
- package/dist/cli.js +239 -22
- package/dist/cli.js.map +1 -1
- package/dist/config/ConfigLoader.d.ts +2 -0
- package/dist/config/ConfigLoader.d.ts.map +1 -1
- package/dist/config/ConfigLoader.js +2 -0
- package/dist/config/ConfigLoader.js.map +1 -1
- package/dist/contracts/PersistenceBackend.d.ts +26 -0
- package/dist/contracts/PersistenceBackend.d.ts.map +1 -1
- package/dist/contracts/persistence-backlog.d.ts +21 -0
- package/dist/contracts/persistence-backlog.d.ts.map +1 -0
- package/dist/contracts/persistence-backlog.js +1 -0
- package/dist/core/HistoryManager.d.ts +15 -1
- package/dist/core/HistoryManager.d.ts.map +1 -1
- package/dist/core/HistoryManager.js +12 -2
- package/dist/core/HistoryManager.js.map +1 -1
- package/dist/core/IHistoryManager.d.ts +2 -0
- package/dist/core/IHistoryManager.d.ts.map +1 -1
- package/dist/core/PersistenceBuffer.d.ts +25 -0
- package/dist/core/PersistenceBuffer.d.ts.map +1 -1
- package/dist/core/PersistenceBuffer.js +27 -5
- package/dist/core/PersistenceBuffer.js.map +1 -1
- package/dist/core/PersistenceBufferErrors.d.ts +10 -0
- package/dist/core/PersistenceBufferErrors.d.ts.map +1 -1
- package/dist/core/PersistenceBufferErrors.js +13 -1
- package/dist/core/PersistenceBufferErrors.js.map +1 -1
- package/dist/core/PersistenceRestore.d.ts.map +1 -1
- package/dist/core/PersistenceRestore.js +25 -30
- package/dist/core/PersistenceRestore.js.map +1 -1
- package/dist/core/PersistenceWorkQueue.d.ts +9 -0
- package/dist/core/PersistenceWorkQueue.d.ts.map +1 -1
- package/dist/core/PersistenceWorkQueue.js +18 -0
- package/dist/core/PersistenceWorkQueue.js.map +1 -1
- package/dist/core/ThoughtEvaluator.d.ts +6 -0
- package/dist/core/ThoughtEvaluator.d.ts.map +1 -1
- package/dist/core/ThoughtEvaluator.js +15 -1
- package/dist/core/ThoughtEvaluator.js.map +1 -1
- package/dist/core/ThoughtProcessor.d.ts.map +1 -1
- package/dist/core/ThoughtProcessor.js +3 -10
- package/dist/core/ThoughtProcessor.js.map +1 -1
- package/dist/core/evaluator/VerificationLinks.d.ts +5 -0
- package/dist/core/evaluator/VerificationLinks.d.ts.map +1 -1
- package/dist/core/evaluator/VerificationLinks.js +47 -53
- package/dist/core/evaluator/VerificationLinks.js.map +1 -1
- package/dist/core/reasoning/ActiveEvidenceProjection.d.ts.map +1 -1
- package/dist/core/reasoning/ActiveEvidenceProjection.js +4 -3
- package/dist/core/reasoning/ActiveEvidenceProjection.js.map +1 -1
- package/dist/errors.d.ts +1 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +2 -1
- package/dist/errors.js.map +1 -1
- package/dist/health/HealthChecker.d.ts +42 -1
- package/dist/health/HealthChecker.d.ts.map +1 -1
- package/dist/health/HealthChecker.js +60 -8
- package/dist/health/HealthChecker.js.map +1 -1
- package/dist/lib.d.ts +2 -2
- package/dist/lib.d.ts.map +1 -1
- package/dist/lib.js +1 -0
- package/dist/lib.js.map +1 -1
- package/dist/metrics/metrics.impl.js.map +1 -1
- package/dist/persistence/FilePersistence.d.ts +2 -1
- package/dist/persistence/FilePersistence.d.ts.map +1 -1
- package/dist/persistence/FilePersistence.js +6 -1
- package/dist/persistence/FilePersistence.js.map +1 -1
- package/dist/persistence/FileSnapshotV2.d.ts +2 -0
- package/dist/persistence/FileSnapshotV2.d.ts.map +1 -1
- package/dist/persistence/FileSnapshotV2.js +39 -1
- package/dist/persistence/FileSnapshotV2.js.map +1 -1
- package/dist/persistence/MemoryPersistence.d.ts +4 -1
- package/dist/persistence/MemoryPersistence.d.ts.map +1 -1
- package/dist/persistence/MemoryPersistence.js +30 -0
- package/dist/persistence/MemoryPersistence.js.map +1 -1
- package/dist/persistence/SqlitePersistence.d.ts +6 -1
- package/dist/persistence/SqlitePersistence.d.ts.map +1 -1
- package/dist/persistence/SqlitePersistence.js +31 -4
- package/dist/persistence/SqlitePersistence.js.map +1 -1
- package/dist/transport/StreamableHttpTransport.d.ts +12 -0
- package/dist/transport/StreamableHttpTransport.d.ts.map +1 -1
- package/dist/transport/StreamableHttpTransport.js +19 -5
- package/dist/transport/StreamableHttpTransport.js.map +1 -1
- package/package.json +20 -20
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core/PersistenceWorkQueue.js","sources":["../../src/core/PersistenceWorkQueue.ts"],"sourcesContent":["/**\n * Pure attributable queue for accepted persistence work.\n *\n * @module core/PersistenceWorkQueue\n */\n\n// allow: SIZE_OK - Task 8 requires this single-responsibility queue in exactly one production file.\n\nimport type {\n\tPersistenceGenerationResult,\n\tPersistenceWork,\n\tPersistenceWorkFailure,\n\tPersistenceWorkToken,\n} from '../contracts/persistence-work.js';\nimport type { BranchId, SessionId, ThoughtId } from '../contracts/ids.js';\nimport { assertNever } from '../utils.js';\nimport type { Summary } from './compression/Summary.js';\nimport {\n\tDurableThoughtIdentityIndex,\n\ttype DurableIdentitySession,\n\tnormalizeDurableHistoryRetention,\n} from './DurableThoughtIdentityIndex.js';\nimport type { Edge } from './graph/Edge.js';\nimport type { ThoughtData } from './thought.js';\n\n/** Selects whether retained terminal failures are eligible for a generation. */\nexport type PersistenceSelectionMode = 'explicit' | 'background';\n\ntype WorkKind = PersistenceWork['kind'];\ntype WorkOf<K extends WorkKind> = Extract<PersistenceWork, { readonly kind: K }>;\n\ntype QueueEntry<K extends WorkKind> = {\n\treadonly acceptedSequence: number;\n\treadonly work: WorkOf<K>;\n\tterminalFailure: PersistenceWorkFailure | undefined;\n};\n\ntype ThoughtEntry = QueueEntry<'thought'>;\ntype BacktrackEntry = QueueEntry<'backtrack'>;\ntype BranchEntry = QueueEntry<'branch'>;\ntype EdgeEntry = QueueEntry<'edge'>;\ntype SummaryEntry = QueueEntry<'summary'>;\ntype AnyQueueEntry = ThoughtEntry | BacktrackEntry | BranchEntry | EdgeEntry | SummaryEntry;\n\ntype Acceptance = {\n\treadonly token: PersistenceWorkToken;\n\treadonly sequence: number;\n};\n\n/**\n * Stores accepted persistence work independently from live session state.\n *\n * Thought entries retain FIFO acceptance order. Auxiliary snapshots coalesce at\n * their stable coordinate and use versioned compare-and-set acknowledgement.\n * Generation state remains caller-owned in a `Set` passed to selection methods.\n *\n * @example\n * ```ts\n * const queue = new PersistenceWorkQueue();\n * queue.enqueueThought(sessionId, thought);\n * const selected = new Set<PersistenceWorkToken>();\n * const work = queue.nextEligibleWork(selected, 'explicit');\n * if (work !== undefined) queue.acknowledgeSuccess(work);\n * ```\n */\nexport class PersistenceWorkQueue {\n\tprivate readonly _thoughts: Array<ThoughtEntry | BacktrackEntry> = [];\n\tprivate readonly _thoughtIdentities = new Map<SessionId, Map<ThoughtId, number>>();\n\tprivate readonly _durableThoughtIdentities: DurableThoughtIdentityIndex;\n\tprivate readonly _persistBranches: boolean;\n\tprivate readonly _branches = new Map<SessionId, Map<BranchId, BranchEntry>>();\n\tprivate readonly _edges = new Map<SessionId, EdgeEntry>();\n\tprivate readonly _summaries = new Map<SessionId, SummaryEntry>();\n\n\tprivate readonly _branchVersions = new Map<SessionId, Map<BranchId, number>>();\n\tprivate readonly _edgeVersions = new Map<SessionId, number>();\n\tprivate readonly _summaryVersions = new Map<SessionId, number>();\n\tprivate _nextSequence = 1;\n\n\tpublic constructor(durableHistorySize = 10_000, persistBranches = true) {\n\t\tthis._durableThoughtIdentities = new DurableThoughtIdentityIndex(\n\t\t\tnormalizeDurableHistoryRetention(durableHistorySize)\n\t\t);\n\t\tthis._persistBranches = persistBranches;\n\t}\n\n\t/**\n\t * Accepts one thought as a distinct FIFO work item.\n\t *\n\t * @param sessionId - Session that owns the thought write.\n\t * @param thought - Thought payload accepted by the coordinator.\n\t * @returns The exact immutable work handle used for acknowledgement.\n\t */\n\tpublic enqueueThought(sessionId: SessionId, thought: ThoughtData): WorkOf<'thought'> {\n\t\tconst acceptance = this._accept();\n\t\tconst work: WorkOf<'thought'> = Object.freeze({\n\t\t\tkind: 'thought',\n\t\t\ttoken: acceptance.token,\n\t\t\tsessionId,\n\t\t\tthought: this._freezeClone(thought),\n\t\t});\n\t\tthis._thoughts.push({\n\t\t\tacceptedSequence: acceptance.sequence,\n\t\t\twork,\n\t\t\tterminalFailure: undefined,\n\t\t});\n\t\tif (thought.id !== undefined) this._addThoughtIdentity(sessionId, thought.id);\n\t\treturn work;\n\t}\n\n\tpublic enqueueBacktrack(\n\t\tsessionId: SessionId,\n\t\tthought: ThoughtData,\n\t\ttargetThoughtId: ThoughtId\n\t): WorkOf<'backtrack'> {\n\t\tconst acceptance = this._accept();\n\t\tconst work: WorkOf<'backtrack'> = Object.freeze({\n\t\t\tkind: 'backtrack',\n\t\t\ttoken: acceptance.token,\n\t\t\tsessionId,\n\t\t\tthought: this._freezeClone(thought),\n\t\t\ttargetThoughtId,\n\t\t});\n\t\tthis._thoughts.push({\n\t\t\tacceptedSequence: acceptance.sequence,\n\t\t\twork,\n\t\t\tterminalFailure: undefined,\n\t\t});\n\t\tif (thought.id !== undefined) this._addThoughtIdentity(sessionId, thought.id);\n\t\treturn work;\n\t}\n\n\tpublic hasThoughtIdentity(sessionId: SessionId, thoughtId: ThoughtId): boolean {\n\t\treturn (\n\t\t\tthis._thoughtIdentities.get(sessionId)?.has(thoughtId) === true ||\n\t\t\tthis._durableThoughtIdentities.has(sessionId, thoughtId)\n\t\t);\n\t}\n\n\tpublic replaceDurableThoughtIdentities(sessions: readonly DurableIdentitySession[]): void {\n\t\tthis._durableThoughtIdentities.replaceAll(sessions);\n\t}\n\n\t/**\n\t * Replaces the pending snapshot for one session-owned branch.\n\t *\n\t * @param sessionId - Session that owns the branch.\n\t * @param branchId - Stable branch coordinate within the session.\n\t * @param thoughts - Branch snapshot; its array is copied before storage.\n\t * @returns The new immutable, versioned work handle.\n\t */\n\tpublic replaceBranch(\n\t\tsessionId: SessionId,\n\t\tbranchId: BranchId,\n\t\tthoughts: readonly ThoughtData[]\n\t): WorkOf<'branch'> {\n\t\tconst versionMap = this._branchVersions.get(sessionId) ?? new Map<BranchId, number>();\n\t\tthis._branchVersions.set(sessionId, versionMap);\n\t\tconst version = (versionMap.get(branchId) ?? 0) + 1;\n\t\tversionMap.set(branchId, version);\n\n\t\tconst acceptance = this._accept();\n\t\tconst work: WorkOf<'branch'> = Object.freeze({\n\t\t\tkind: 'branch',\n\t\t\toperation: 'save',\n\t\t\ttoken: acceptance.token,\n\t\t\tsessionId,\n\t\t\tkey: branchId,\n\t\t\tversion,\n\t\t\tsnapshot: this._freezeClone(thoughts),\n\t\t});\n\t\tconst branchMap = this._branches.get(sessionId) ?? new Map<BranchId, BranchEntry>();\n\t\tthis._branches.set(sessionId, branchMap);\n\t\tbranchMap.set(branchId, {\n\t\t\tacceptedSequence: acceptance.sequence,\n\t\t\twork,\n\t\t\tterminalFailure: undefined,\n\t\t});\n\t\treturn work;\n\t}\n\n\t/**\n\t * @param sessionId - Session that owns the branch.\n\t * @param branchId - Stable branch coordinate within the session.\n\t * @returns The new immutable, versioned deletion work handle.\n\t */\n\tpublic deleteBranch(sessionId: SessionId, branchId: BranchId): WorkOf<'branch'> {\n\t\tconst versionMap = this._branchVersions.get(sessionId) ?? new Map<BranchId, number>();\n\t\tthis._branchVersions.set(sessionId, versionMap);\n\t\tconst version = (versionMap.get(branchId) ?? 0) + 1;\n\t\tversionMap.set(branchId, version);\n\n\t\tconst acceptance = this._accept();\n\t\tconst work: WorkOf<'branch'> = Object.freeze({\n\t\t\tkind: 'branch',\n\t\t\toperation: 'delete',\n\t\t\ttoken: acceptance.token,\n\t\t\tsessionId,\n\t\t\tkey: branchId,\n\t\t\tversion,\n\t\t});\n\t\tconst branchMap = this._branches.get(sessionId) ?? new Map<BranchId, BranchEntry>();\n\t\tthis._branches.set(sessionId, branchMap);\n\t\tbranchMap.set(branchId, {\n\t\t\tacceptedSequence: acceptance.sequence,\n\t\t\twork,\n\t\t\tterminalFailure: undefined,\n\t\t});\n\t\treturn work;\n\t}\n\n\t/**\n\t * Replaces the pending edge snapshot for a session.\n\t *\n\t * @param sessionId - Stable session coordinate for the edge set.\n\t * @param edges - Edge snapshot; its array is copied before storage.\n\t * @returns The new immutable, versioned work handle.\n\t */\n\tpublic replaceEdges(sessionId: SessionId, edges: readonly Edge[]): WorkOf<'edge'> {\n\t\tconst version = (this._edgeVersions.get(sessionId) ?? 0) + 1;\n\t\tthis._edgeVersions.set(sessionId, version);\n\t\tconst acceptance = this._accept();\n\t\tconst work: WorkOf<'edge'> = Object.freeze({\n\t\t\tkind: 'edge',\n\t\t\ttoken: acceptance.token,\n\t\t\tsessionId,\n\t\t\tkey: sessionId,\n\t\t\tversion,\n\t\t\tsnapshot: this._freezeClone(edges),\n\t\t});\n\t\tthis._edges.set(sessionId, {\n\t\t\tacceptedSequence: acceptance.sequence,\n\t\t\twork,\n\t\t\tterminalFailure: undefined,\n\t\t});\n\t\treturn work;\n\t}\n\n\t/**\n\t * Replaces the pending summary snapshot for a session.\n\t *\n\t * @param sessionId - Stable session coordinate for the summary set.\n\t * @param summaries - Summary snapshot; its array is copied before storage.\n\t * @returns The new immutable, versioned work handle.\n\t */\n\tpublic replaceSummaries(sessionId: SessionId, summaries: readonly Summary[]): WorkOf<'summary'> {\n\t\tconst version = (this._summaryVersions.get(sessionId) ?? 0) + 1;\n\t\tthis._summaryVersions.set(sessionId, version);\n\t\tconst acceptance = this._accept();\n\t\tconst work: WorkOf<'summary'> = Object.freeze({\n\t\t\tkind: 'summary',\n\t\t\ttoken: acceptance.token,\n\t\t\tsessionId,\n\t\t\tkey: sessionId,\n\t\t\tversion,\n\t\t\tsnapshot: this._freezeClone(summaries),\n\t\t});\n\t\tthis._summaries.set(sessionId, {\n\t\t\tacceptedSequence: acceptance.sequence,\n\t\t\twork,\n\t\t\tterminalFailure: undefined,\n\t\t});\n\t\treturn work;\n\t}\n\n\t/**\n\t * Reports whether a generation can select current work.\n\t *\n\t * @param selectedTokens - Tokens already selected by the caller's generation.\n\t * @param mode - Explicit generations re-arm failures; background generations skip them.\n\t * @param sessionId - Optional session projection.\n\t * @returns `true` when at least one current entry is eligible.\n\t */\n\tpublic hasEligibleWork(\n\t\tselectedTokens: ReadonlySet<PersistenceWorkToken>,\n\t\tmode: PersistenceSelectionMode,\n\t\tsessionId?: SessionId\n\t): boolean {\n\t\treturn this._findEligible(selectedTokens, mode, sessionId) !== undefined;\n\t}\n\n\t/**\n\t * Selects the oldest currently eligible work and records it in the generation set.\n\t *\n\t * @param selectedTokens - Mutable set owned by the caller's generation.\n\t * @param mode - Explicit generations re-arm failures; background generations skip them.\n\t * @param sessionId - Optional session projection.\n\t * @returns The selected work, or `undefined` when no current entry is eligible.\n\t */\n\tpublic nextEligibleWork(\n\t\tselectedTokens: Set<PersistenceWorkToken>,\n\t\tmode: PersistenceSelectionMode,\n\t\tsessionId?: SessionId\n\t): PersistenceWork | undefined {\n\t\tconst entry = this._findEligible(selectedTokens, mode, sessionId);\n\t\tif (entry === undefined) return undefined;\n\t\tselectedTokens.add(entry.work.token);\n\t\treturn entry.work;\n\t}\n\n\t/**\n\t * Acknowledges successful persistence using exact token/version CAS semantics.\n\t *\n\t * @param work - Previously selected work handle.\n\t */\n\tpublic acknowledgeSuccess(work: PersistenceWork): void {\n\t\tconst entry = this._currentEntry(work);\n\t\tif (entry === undefined) return;\n\t\tswitch (work.kind) {\n\t\t\tcase 'thought': {\n\t\t\t\tconst index = this._thoughts.findIndex((candidate) => candidate === entry);\n\t\t\t\tif (index >= 0) {\n\t\t\t\t\tthis._thoughts.splice(index, 1);\n\t\t\t\t\tif (work.thought.id !== undefined) {\n\t\t\t\t\t\tthis._removeThoughtIdentity(work.sessionId, work.thought.id);\n\t\t\t\t\t}\n\t\t\t\t\tthis._durableThoughtIdentities.appendThought(work.sessionId, work.thought);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'backtrack': {\n\t\t\t\tconst index = this._thoughts.findIndex((candidate) => candidate === entry);\n\t\t\t\tif (index >= 0) {\n\t\t\t\t\tthis._thoughts.splice(index, 1);\n\t\t\t\t\tif (work.thought.id !== undefined) {\n\t\t\t\t\t\tthis._removeThoughtIdentity(work.sessionId, work.thought.id);\n\t\t\t\t\t}\n\t\t\t\t\tthis._durableThoughtIdentities.appendThought(work.sessionId, work.thought);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'branch':\n\t\t\t\tthis._branches.get(work.sessionId)?.delete(work.key);\n\t\t\t\tif (!this._persistBranches) return;\n\t\t\t\tif (work.operation === 'save') {\n\t\t\t\t\tthis._durableThoughtIdentities.replaceBranch(work.sessionId, work.key, work.snapshot);\n\t\t\t\t} else {\n\t\t\t\t\tthis._durableThoughtIdentities.deleteBranch(work.sessionId, work.key);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\tcase 'edge':\n\t\t\t\tthis._edges.delete(work.key);\n\t\t\t\treturn;\n\t\t\tcase 'summary':\n\t\t\t\tthis._summaries.delete(work.key);\n\t\t\t\treturn;\n\t\t\tdefault:\n\t\t\t\tassertNever(work);\n\t\t}\n\t}\n\n\t/**\n\t * Attaches a terminal failure only when both work and failure still match current work.\n\t *\n\t * @param work - Previously selected work handle.\n\t * @param failure - Terminal backend failure attributed to that handle.\n\t */\n\tpublic acknowledgeFailure(work: PersistenceWork, failure: PersistenceWorkFailure): void {\n\t\tif (!this._matchesFailure(work, failure)) return;\n\t\tconst entry = this._currentEntry(work);\n\t\tif (entry !== undefined) entry.terminalFailure = Object.freeze({ ...failure });\n\t}\n\n\t/**\n\t * Returns an immutable acceptance-ordered snapshot of current terminal failures.\n\t *\n\t * @param selectedTokens - Optional generation-token projection.\n\t * @param sessionId - Optional session projection.\n\t * @returns A fresh readonly failure array containing only failures on current entries.\n\t */\n\tpublic currentFailures(\n\t\tselectedTokens?: ReadonlySet<PersistenceWorkToken>,\n\t\tsessionId?: SessionId\n\t): readonly PersistenceWorkFailure[] {\n\t\tconst failures = this._entries()\n\t\t\t.filter(\n\t\t\t\t(entry) =>\n\t\t\t\t\tentry.terminalFailure !== undefined &&\n\t\t\t\t\t(selectedTokens === undefined || selectedTokens.has(entry.work.token)) &&\n\t\t\t\t\t(sessionId === undefined || entry.work.sessionId === sessionId)\n\t\t\t)\n\t\t\t.sort((left, right) => left.acceptedSequence - right.acceptedSequence)\n\t\t\t.flatMap((entry) => (entry.terminalFailure === undefined ? [] : [entry.terminalFailure]));\n\t\treturn Object.freeze(failures);\n\t}\n\n\t/**\n\t * Captures the current immutable result for a generation or session projection.\n\t *\n\t * @param selectedTokens - Optional generation-token projection.\n\t * @param sessionId - Optional session projection.\n\t * @returns A result containing a fresh readonly failure snapshot.\n\t */\n\tpublic generationResult(\n\t\tselectedTokens?: ReadonlySet<PersistenceWorkToken>,\n\t\tsessionId?: SessionId\n\t): PersistenceGenerationResult {\n\t\treturn Object.freeze({ failures: this.currentFailures(selectedTokens, sessionId) });\n\t}\n\n\t/** @returns Number of accepted thought writes not yet acknowledged successful. */\n\tpublic get pendingThoughtCount(): number {\n\t\treturn this._thoughts.length;\n\t}\n\n\t/** @returns Number of all current thought and coalesced auxiliary entries. */\n\tpublic get pendingWorkCount(): number {\n\t\tlet branchCount = 0;\n\t\tfor (const branches of this._branches.values()) branchCount += branches.size;\n\t\treturn this._thoughts.length + branchCount + this._edges.size + this._summaries.size;\n\t}\n\n\t/** @returns Whether any accepted work remains for a session across all work kinds. */\n\tpublic hasSessionWork(sessionId: SessionId): boolean {\n\t\treturn this._entries().some((entry) => entry.work.sessionId === sessionId);\n\t}\n\n\t/** @returns Whether current retained work for a session owns a terminal failure. */\n\tpublic hasSessionTerminalFailure(sessionId: SessionId): boolean {\n\t\treturn this.currentFailures(undefined, sessionId).length > 0;\n\t}\n\n\t/**\n\t * Forgets version coordinates only after all accepted work for a session is gone.\n\t *\n\t * @returns `false` without mutation while any accepted work remains.\n\t */\n\tpublic forgetQuiescentSession(sessionId: SessionId): boolean {\n\t\tif (this.hasSessionWork(sessionId)) return false;\n\t\tthis._branches.delete(sessionId);\n\t\tthis._branchVersions.delete(sessionId);\n\t\tthis._edgeVersions.delete(sessionId);\n\t\tthis._summaryVersions.delete(sessionId);\n\t\treturn true;\n\t}\n\n\t/** Discards every retained work item and version coordinate for one deleted session. */\n\tpublic discardSession(sessionId: SessionId): void {\n\t\tfor (let index = this._thoughts.length - 1; index >= 0; index -= 1) {\n\t\t\tif (this._thoughts[index]?.work.sessionId === sessionId) this._thoughts.splice(index, 1);\n\t\t}\n\t\tthis._thoughtIdentities.delete(sessionId);\n\t\tthis._durableThoughtIdentities.clearSession(sessionId);\n\t\tthis._branches.delete(sessionId);\n\t\tthis._edges.delete(sessionId);\n\t\tthis._summaries.delete(sessionId);\n\t\tthis._branchVersions.delete(sessionId);\n\t\tthis._edgeVersions.delete(sessionId);\n\t\tthis._summaryVersions.delete(sessionId);\n\t}\n\n\t/** Discards all retained work after a successful durable global reset. */\n\tpublic discardAll(): void {\n\t\tthis._thoughts.length = 0;\n\t\tthis._thoughtIdentities.clear();\n\t\tthis._durableThoughtIdentities.clearAll();\n\t\tthis._branches.clear();\n\t\tthis._edges.clear();\n\t\tthis._summaries.clear();\n\t\tthis._branchVersions.clear();\n\t\tthis._edgeVersions.clear();\n\t\tthis._summaryVersions.clear();\n\t}\n\n\tprivate _accept(): Acceptance {\n\t\tconst sequence = this._nextSequence;\n\t\tthis._nextSequence += 1;\n\t\treturn { token: `persistence-work-${sequence}`, sequence };\n\t}\n\n\tprivate _freezeClone<T>(value: T): T {\n\t\tconst clone = structuredClone(value);\n\t\treturn this._deepFreeze(clone);\n\t}\n\n\tprivate _deepFreeze<T>(value: T): T {\n\t\tif (value !== null && typeof value === 'object') {\n\t\t\tfor (const nested of Object.values(value)) this._deepFreeze(nested);\n\t\t\tObject.freeze(value);\n\t\t}\n\t\treturn value;\n\t}\n\n\tprivate _addThoughtIdentity(sessionId: SessionId, thoughtId: ThoughtId): void {\n\t\tconst identities = this._thoughtIdentities.get(sessionId) ?? new Map<ThoughtId, number>();\n\t\tidentities.set(thoughtId, (identities.get(thoughtId) ?? 0) + 1);\n\t\tthis._thoughtIdentities.set(sessionId, identities);\n\t}\n\n\tprivate _removeThoughtIdentity(sessionId: SessionId, thoughtId: ThoughtId): void {\n\t\tconst identities = this._thoughtIdentities.get(sessionId);\n\t\tconst count = identities?.get(thoughtId);\n\t\tif (identities === undefined || count === undefined) return;\n\t\tif (count > 1) identities.set(thoughtId, count - 1);\n\t\telse identities.delete(thoughtId);\n\t\tif (identities.size === 0) this._thoughtIdentities.delete(sessionId);\n\t}\n\n\tprivate _entries(): AnyQueueEntry[] {\n\t\tconst entries: AnyQueueEntry[] = [...this._thoughts];\n\t\tfor (const branches of this._branches.values()) entries.push(...branches.values());\n\t\tentries.push(...this._edges.values(), ...this._summaries.values());\n\t\treturn entries;\n\t}\n\n\tprivate _findEligible(\n\t\tselectedTokens: ReadonlySet<PersistenceWorkToken>,\n\t\tmode: PersistenceSelectionMode,\n\t\tsessionId?: SessionId\n\t): AnyQueueEntry | undefined {\n\t\tlet oldest: AnyQueueEntry | undefined;\n\t\tfor (const entry of this._entries()) {\n\t\t\tif (selectedTokens.has(entry.work.token)) continue;\n\t\t\tif (sessionId !== undefined && entry.work.sessionId !== sessionId) continue;\n\t\t\tif (!this._modeAllows(mode, entry.terminalFailure !== undefined)) continue;\n\t\t\tif (oldest === undefined || entry.acceptedSequence < oldest.acceptedSequence) oldest = entry;\n\t\t}\n\t\treturn oldest;\n\t}\n\n\tprivate _modeAllows(mode: PersistenceSelectionMode, hasTerminalFailure: boolean): boolean {\n\t\tswitch (mode) {\n\t\t\tcase 'explicit':\n\t\t\t\treturn true;\n\t\t\tcase 'background':\n\t\t\t\treturn !hasTerminalFailure;\n\t\t\tdefault:\n\t\t\t\treturn assertNever(mode);\n\t\t}\n\t}\n\n\tprivate _currentEntry(work: PersistenceWork): AnyQueueEntry | undefined {\n\t\tlet entry: AnyQueueEntry | undefined;\n\t\tswitch (work.kind) {\n\t\t\tcase 'thought':\n\t\t\tcase 'backtrack':\n\t\t\t\tentry = this._thoughts.find((candidate) => candidate.work.token === work.token);\n\t\t\t\tbreak;\n\t\t\tcase 'branch':\n\t\t\t\tentry = this._branches.get(work.sessionId)?.get(work.key);\n\t\t\t\tbreak;\n\t\t\tcase 'edge':\n\t\t\t\tentry = this._edges.get(work.key);\n\t\t\t\tbreak;\n\t\t\tcase 'summary':\n\t\t\t\tentry = this._summaries.get(work.key);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn assertNever(work);\n\t\t}\n\t\treturn entry !== undefined && this._matchesWork(entry.work, work) ? entry : undefined;\n\t}\n\n\tprivate _matchesWork(current: PersistenceWork, selected: PersistenceWork): boolean {\n\t\tif (\n\t\t\tcurrent.kind !== selected.kind ||\n\t\t\tcurrent.token !== selected.token ||\n\t\t\tcurrent.sessionId !== selected.sessionId\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tswitch (selected.kind) {\n\t\t\tcase 'thought':\n\t\t\t\treturn current.kind === 'thought';\n\t\t\tcase 'backtrack':\n\t\t\t\treturn current.kind === 'backtrack' && current.targetThoughtId === selected.targetThoughtId;\n\t\t\tcase 'branch':\n\t\t\t\treturn (\n\t\t\t\t\tcurrent.kind === 'branch' &&\n\t\t\t\t\tcurrent.operation === selected.operation &&\n\t\t\t\t\tcurrent.key === selected.key &&\n\t\t\t\t\tcurrent.version === selected.version\n\t\t\t\t);\n\t\t\tcase 'edge':\n\t\t\t\treturn (\n\t\t\t\t\tcurrent.kind === 'edge' &&\n\t\t\t\t\tcurrent.key === selected.key &&\n\t\t\t\t\tcurrent.version === selected.version\n\t\t\t\t);\n\t\t\tcase 'summary':\n\t\t\t\treturn (\n\t\t\t\t\tcurrent.kind === 'summary' &&\n\t\t\t\t\tcurrent.key === selected.key &&\n\t\t\t\t\tcurrent.version === selected.version\n\t\t\t\t);\n\t\t\tdefault:\n\t\t\t\treturn assertNever(selected);\n\t\t}\n\t}\n\n\tprivate _matchesFailure(work: PersistenceWork, failure: PersistenceWorkFailure): boolean {\n\t\tif (\n\t\t\twork.kind !== failure.kind ||\n\t\t\twork.token !== failure.token ||\n\t\t\twork.sessionId !== failure.sessionId\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tswitch (work.kind) {\n\t\t\tcase 'thought':\n\t\t\tcase 'backtrack':\n\t\t\t\treturn true;\n\t\t\tcase 'branch':\n\t\t\t\treturn (\n\t\t\t\t\tfailure.kind === 'branch' &&\n\t\t\t\t\twork.operation === failure.operation &&\n\t\t\t\t\twork.key === failure.key &&\n\t\t\t\t\twork.version === failure.version\n\t\t\t\t);\n\t\t\tcase 'edge':\n\t\t\tcase 'summary':\n\t\t\t\treturn 'key' in failure && work.key === failure.key && work.version === failure.version;\n\t\t\tdefault:\n\t\t\t\treturn assertNever(work);\n\t\t}\n\t}\n}\n"],"names":["PersistenceWorkQueue","Map","durableHistorySize","persistBranches","DurableThoughtIdentityIndex","normalizeDurableHistoryRetention","sessionId","thought","acceptance","work","Object","undefined","targetThoughtId","thoughtId","sessions","branchId","thoughts","versionMap","version","branchMap","edges","summaries","selectedTokens","mode","entry","index","candidate","assertNever","failure","failures","left","right","branchCount","branches","sequence","value","clone","structuredClone","nested","identities","count","entries","oldest","hasTerminalFailure","current","selected"],"mappings":";;AAiEO,MAAMA;IACK,YAAkD,EAAE,CAAC;IACrD,qBAAqB,IAAIC,MAAyC;IAClE,0BAAuD;IACvD,iBAA0B;IAC1B,YAAY,IAAIA,MAA6C;IAC7D,SAAS,IAAIA,MAA4B;IACzC,aAAa,IAAIA,MAA+B;IAEhD,kBAAkB,IAAIA,MAAwC;IAC9D,gBAAgB,IAAIA,MAAyB;IAC7C,mBAAmB,IAAIA,MAAyB;IACzD,gBAAgB,EAAE;IAE1B,YAAmBC,qB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BACJ,OACCD,AAAiB,aAAjBA,QAAQ,IAAI,IACZA,QAAQ,SAAS,KAAKC,SAAS,SAAS,IACxCD,QAAQ,GAAG,KAAKC,SAAS,GAAG,IAC5BD,QAAQ,OAAO,KAAKC,SAAS,OAAO;YAEtC,KAAK;gBACJ,OACCD,AAAiB,WAAjBA,QAAQ,IAAI,IACZA,QAAQ,GAAG,KAAKC,SAAS,GAAG,IAC5BD,QAAQ,OAAO,KAAKC,SAAS,OAAO;YAEtC,KAAK;gBACJ,OACCD,AAAiB,cAAjBA,QAAQ,IAAI,IACZA,QAAQ,GAAG,KAAKC,SAAS,GAAG,IAC5BD,QAAQ,OAAO,KAAKC,SAAS,OAAO;YAEtC;gBACC,OAAOlB,YAAYkB;QACrB;IACD;IAEQ,gBAAgBpC,IAAqB,EAAEmB,OAA+B,EAAW;QACxF,IACCnB,KAAK,IAAI,KAAKmB,QAAQ,IAAI,IAC1BnB,KAAK,KAAK,KAAKmB,QAAQ,KAAK,IAC5BnB,KAAK,SAAS,KAAKmB,QAAQ,SAAS,EAEpC,OAAO;QAER,OAAQnB,KAAK,IAAI;YAChB,KAAK;YACL,KAAK;gBACJ,OAAO;YACR,KAAK;gBACJ,OACCmB,AAAiB,aAAjBA,QAAQ,IAAI,IACZnB,KAAK,SAAS,KAAKmB,QAAQ,SAAS,IACpCnB,KAAK,GAAG,KAAKmB,QAAQ,GAAG,IACxBnB,KAAK,OAAO,KAAKmB,QAAQ,OAAO;YAElC,KAAK;YACL,KAAK;gBACJ,OAAO,SAASA,WAAWnB,KAAK,GAAG,KAAKmB,QAAQ,GAAG,IAAInB,KAAK,OAAO,KAAKmB,QAAQ,OAAO;YACxF;gBACC,OAAOD,YAAYlB;QACrB;IACD;AACD"}
|
|
1
|
+
{"version":3,"file":"core/PersistenceWorkQueue.js","sources":["../../src/core/PersistenceWorkQueue.ts"],"sourcesContent":["/**\n * Pure attributable queue for accepted persistence work.\n *\n * @module core/PersistenceWorkQueue\n */\n\n// allow: SIZE_OK - Task 8 requires this single-responsibility queue in exactly one production file.\n\nimport type {\n\tPersistenceGenerationResult,\n\tPersistenceWork,\n\tPersistenceWorkFailure,\n\tPersistenceWorkToken,\n} from '../contracts/persistence-work.js';\nimport type { BranchId, SessionId, ThoughtId } from '../contracts/ids.js';\nimport { assertNever } from '../utils.js';\nimport type { Summary } from './compression/Summary.js';\nimport {\n\tDurableThoughtIdentityIndex,\n\ttype DurableIdentitySession,\n\tnormalizeDurableHistoryRetention,\n} from './DurableThoughtIdentityIndex.js';\nimport type { Edge } from './graph/Edge.js';\nimport type { ThoughtData } from './thought.js';\n\n/** Selects whether retained terminal failures are eligible for a generation. */\nexport type PersistenceSelectionMode = 'explicit' | 'background';\n\ntype WorkKind = PersistenceWork['kind'];\ntype WorkOf<K extends WorkKind> = Extract<PersistenceWork, { readonly kind: K }>;\n\ntype QueueEntry<K extends WorkKind> = {\n\treadonly acceptedSequence: number;\n\treadonly work: WorkOf<K>;\n\tterminalFailure: PersistenceWorkFailure | undefined;\n};\n\ntype ThoughtEntry = QueueEntry<'thought'>;\ntype BacktrackEntry = QueueEntry<'backtrack'>;\ntype BranchEntry = QueueEntry<'branch'>;\ntype EdgeEntry = QueueEntry<'edge'>;\ntype SummaryEntry = QueueEntry<'summary'>;\ntype AnyQueueEntry = ThoughtEntry | BacktrackEntry | BranchEntry | EdgeEntry | SummaryEntry;\n\ntype Acceptance = {\n\treadonly token: PersistenceWorkToken;\n\treadonly sequence: number;\n};\n\n/**\n * Stores accepted persistence work independently from live session state.\n *\n * Thought entries retain FIFO acceptance order. Auxiliary snapshots coalesce at\n * their stable coordinate and use versioned compare-and-set acknowledgement.\n * Generation state remains caller-owned in a `Set` passed to selection methods.\n *\n * @example\n * ```ts\n * const queue = new PersistenceWorkQueue();\n * queue.enqueueThought(sessionId, thought);\n * const selected = new Set<PersistenceWorkToken>();\n * const work = queue.nextEligibleWork(selected, 'explicit');\n * if (work !== undefined) queue.acknowledgeSuccess(work);\n * ```\n */\nexport class PersistenceWorkQueue {\n\tprivate readonly _thoughts: Array<ThoughtEntry | BacktrackEntry> = [];\n\tprivate readonly _thoughtIdentities = new Map<SessionId, Map<ThoughtId, number>>();\n\tprivate readonly _pendingThoughtsBySession = new Map<SessionId, number>();\n\tprivate readonly _durableThoughtIdentities: DurableThoughtIdentityIndex;\n\tprivate readonly _persistBranches: boolean;\n\tprivate readonly _branches = new Map<SessionId, Map<BranchId, BranchEntry>>();\n\tprivate readonly _edges = new Map<SessionId, EdgeEntry>();\n\tprivate readonly _summaries = new Map<SessionId, SummaryEntry>();\n\n\tprivate readonly _branchVersions = new Map<SessionId, Map<BranchId, number>>();\n\tprivate readonly _edgeVersions = new Map<SessionId, number>();\n\tprivate readonly _summaryVersions = new Map<SessionId, number>();\n\tprivate _nextSequence = 1;\n\n\tpublic constructor(durableHistorySize = 10_000, persistBranches = true) {\n\t\tthis._durableThoughtIdentities = new DurableThoughtIdentityIndex(\n\t\t\tnormalizeDurableHistoryRetention(durableHistorySize)\n\t\t);\n\t\tthis._persistBranches = persistBranches;\n\t}\n\n\t/**\n\t * Accepts one thought as a distinct FIFO work item.\n\t *\n\t * @param sessionId - Session that owns the thought write.\n\t * @param thought - Thought payload accepted by the coordinator.\n\t * @returns The exact immutable work handle used for acknowledgement.\n\t */\n\tpublic enqueueThought(sessionId: SessionId, thought: ThoughtData): WorkOf<'thought'> {\n\t\tconst acceptance = this._accept();\n\t\tconst work: WorkOf<'thought'> = Object.freeze({\n\t\t\tkind: 'thought',\n\t\t\ttoken: acceptance.token,\n\t\t\tsessionId,\n\t\t\tthought: this._freezeClone(thought),\n\t\t});\n\t\tthis._thoughts.push({\n\t\t\tacceptedSequence: acceptance.sequence,\n\t\t\twork,\n\t\t\tterminalFailure: undefined,\n\t\t});\n\t\tthis._incrementPendingThoughts(sessionId);\n\t\tif (thought.id !== undefined) this._addThoughtIdentity(sessionId, thought.id);\n\t\treturn work;\n\t}\n\n\tpublic enqueueBacktrack(\n\t\tsessionId: SessionId,\n\t\tthought: ThoughtData,\n\t\ttargetThoughtId: ThoughtId\n\t): WorkOf<'backtrack'> {\n\t\tconst acceptance = this._accept();\n\t\tconst work: WorkOf<'backtrack'> = Object.freeze({\n\t\t\tkind: 'backtrack',\n\t\t\ttoken: acceptance.token,\n\t\t\tsessionId,\n\t\t\tthought: this._freezeClone(thought),\n\t\t\ttargetThoughtId,\n\t\t});\n\t\tthis._thoughts.push({\n\t\t\tacceptedSequence: acceptance.sequence,\n\t\t\twork,\n\t\t\tterminalFailure: undefined,\n\t\t});\n\t\tthis._incrementPendingThoughts(sessionId);\n\t\tif (thought.id !== undefined) this._addThoughtIdentity(sessionId, thought.id);\n\t\treturn work;\n\t}\n\n\tpublic hasThoughtIdentity(sessionId: SessionId, thoughtId: ThoughtId): boolean {\n\t\treturn (\n\t\t\tthis._thoughtIdentities.get(sessionId)?.has(thoughtId) === true ||\n\t\t\tthis._durableThoughtIdentities.has(sessionId, thoughtId)\n\t\t);\n\t}\n\n\tpublic replaceDurableThoughtIdentities(sessions: readonly DurableIdentitySession[]): void {\n\t\tthis._durableThoughtIdentities.replaceAll(sessions);\n\t}\n\n\t/**\n\t * Replaces the pending snapshot for one session-owned branch.\n\t *\n\t * @param sessionId - Session that owns the branch.\n\t * @param branchId - Stable branch coordinate within the session.\n\t * @param thoughts - Branch snapshot; its array is copied before storage.\n\t * @returns The new immutable, versioned work handle.\n\t */\n\tpublic replaceBranch(\n\t\tsessionId: SessionId,\n\t\tbranchId: BranchId,\n\t\tthoughts: readonly ThoughtData[]\n\t): WorkOf<'branch'> {\n\t\tconst versionMap = this._branchVersions.get(sessionId) ?? new Map<BranchId, number>();\n\t\tthis._branchVersions.set(sessionId, versionMap);\n\t\tconst version = (versionMap.get(branchId) ?? 0) + 1;\n\t\tversionMap.set(branchId, version);\n\n\t\tconst acceptance = this._accept();\n\t\tconst work: WorkOf<'branch'> = Object.freeze({\n\t\t\tkind: 'branch',\n\t\t\toperation: 'save',\n\t\t\ttoken: acceptance.token,\n\t\t\tsessionId,\n\t\t\tkey: branchId,\n\t\t\tversion,\n\t\t\tsnapshot: this._freezeClone(thoughts),\n\t\t});\n\t\tconst branchMap = this._branches.get(sessionId) ?? new Map<BranchId, BranchEntry>();\n\t\tthis._branches.set(sessionId, branchMap);\n\t\tbranchMap.set(branchId, {\n\t\t\tacceptedSequence: acceptance.sequence,\n\t\t\twork,\n\t\t\tterminalFailure: undefined,\n\t\t});\n\t\treturn work;\n\t}\n\n\t/**\n\t * @param sessionId - Session that owns the branch.\n\t * @param branchId - Stable branch coordinate within the session.\n\t * @returns The new immutable, versioned deletion work handle.\n\t */\n\tpublic deleteBranch(sessionId: SessionId, branchId: BranchId): WorkOf<'branch'> {\n\t\tconst versionMap = this._branchVersions.get(sessionId) ?? new Map<BranchId, number>();\n\t\tthis._branchVersions.set(sessionId, versionMap);\n\t\tconst version = (versionMap.get(branchId) ?? 0) + 1;\n\t\tversionMap.set(branchId, version);\n\n\t\tconst acceptance = this._accept();\n\t\tconst work: WorkOf<'branch'> = Object.freeze({\n\t\t\tkind: 'branch',\n\t\t\toperation: 'delete',\n\t\t\ttoken: acceptance.token,\n\t\t\tsessionId,\n\t\t\tkey: branchId,\n\t\t\tversion,\n\t\t});\n\t\tconst branchMap = this._branches.get(sessionId) ?? new Map<BranchId, BranchEntry>();\n\t\tthis._branches.set(sessionId, branchMap);\n\t\tbranchMap.set(branchId, {\n\t\t\tacceptedSequence: acceptance.sequence,\n\t\t\twork,\n\t\t\tterminalFailure: undefined,\n\t\t});\n\t\treturn work;\n\t}\n\n\t/**\n\t * Replaces the pending edge snapshot for a session.\n\t *\n\t * @param sessionId - Stable session coordinate for the edge set.\n\t * @param edges - Edge snapshot; its array is copied before storage.\n\t * @returns The new immutable, versioned work handle.\n\t */\n\tpublic replaceEdges(sessionId: SessionId, edges: readonly Edge[]): WorkOf<'edge'> {\n\t\tconst version = (this._edgeVersions.get(sessionId) ?? 0) + 1;\n\t\tthis._edgeVersions.set(sessionId, version);\n\t\tconst acceptance = this._accept();\n\t\tconst work: WorkOf<'edge'> = Object.freeze({\n\t\t\tkind: 'edge',\n\t\t\ttoken: acceptance.token,\n\t\t\tsessionId,\n\t\t\tkey: sessionId,\n\t\t\tversion,\n\t\t\tsnapshot: this._freezeClone(edges),\n\t\t});\n\t\tthis._edges.set(sessionId, {\n\t\t\tacceptedSequence: acceptance.sequence,\n\t\t\twork,\n\t\t\tterminalFailure: undefined,\n\t\t});\n\t\treturn work;\n\t}\n\n\t/**\n\t * Replaces the pending summary snapshot for a session.\n\t *\n\t * @param sessionId - Stable session coordinate for the summary set.\n\t * @param summaries - Summary snapshot; its array is copied before storage.\n\t * @returns The new immutable, versioned work handle.\n\t */\n\tpublic replaceSummaries(sessionId: SessionId, summaries: readonly Summary[]): WorkOf<'summary'> {\n\t\tconst version = (this._summaryVersions.get(sessionId) ?? 0) + 1;\n\t\tthis._summaryVersions.set(sessionId, version);\n\t\tconst acceptance = this._accept();\n\t\tconst work: WorkOf<'summary'> = Object.freeze({\n\t\t\tkind: 'summary',\n\t\t\ttoken: acceptance.token,\n\t\t\tsessionId,\n\t\t\tkey: sessionId,\n\t\t\tversion,\n\t\t\tsnapshot: this._freezeClone(summaries),\n\t\t});\n\t\tthis._summaries.set(sessionId, {\n\t\t\tacceptedSequence: acceptance.sequence,\n\t\t\twork,\n\t\t\tterminalFailure: undefined,\n\t\t});\n\t\treturn work;\n\t}\n\n\t/**\n\t * Reports whether a generation can select current work.\n\t *\n\t * @param selectedTokens - Tokens already selected by the caller's generation.\n\t * @param mode - Explicit generations re-arm failures; background generations skip them.\n\t * @param sessionId - Optional session projection.\n\t * @returns `true` when at least one current entry is eligible.\n\t */\n\tpublic hasEligibleWork(\n\t\tselectedTokens: ReadonlySet<PersistenceWorkToken>,\n\t\tmode: PersistenceSelectionMode,\n\t\tsessionId?: SessionId\n\t): boolean {\n\t\treturn this._findEligible(selectedTokens, mode, sessionId) !== undefined;\n\t}\n\n\t/**\n\t * Selects the oldest currently eligible work and records it in the generation set.\n\t *\n\t * @param selectedTokens - Mutable set owned by the caller's generation.\n\t * @param mode - Explicit generations re-arm failures; background generations skip them.\n\t * @param sessionId - Optional session projection.\n\t * @returns The selected work, or `undefined` when no current entry is eligible.\n\t */\n\tpublic nextEligibleWork(\n\t\tselectedTokens: Set<PersistenceWorkToken>,\n\t\tmode: PersistenceSelectionMode,\n\t\tsessionId?: SessionId\n\t): PersistenceWork | undefined {\n\t\tconst entry = this._findEligible(selectedTokens, mode, sessionId);\n\t\tif (entry === undefined) return undefined;\n\t\tselectedTokens.add(entry.work.token);\n\t\treturn entry.work;\n\t}\n\n\t/**\n\t * Acknowledges successful persistence using exact token/version CAS semantics.\n\t *\n\t * @param work - Previously selected work handle.\n\t */\n\tpublic acknowledgeSuccess(work: PersistenceWork): void {\n\t\tconst entry = this._currentEntry(work);\n\t\tif (entry === undefined) return;\n\t\tswitch (work.kind) {\n\t\t\tcase 'thought': {\n\t\t\t\tconst index = this._thoughts.findIndex((candidate) => candidate === entry);\n\t\t\t\tif (index >= 0) {\n\t\t\t\t\tthis._thoughts.splice(index, 1);\n\t\t\t\t\tthis._decrementPendingThoughts(work.sessionId);\n\t\t\t\t\tif (work.thought.id !== undefined) {\n\t\t\t\t\t\tthis._removeThoughtIdentity(work.sessionId, work.thought.id);\n\t\t\t\t\t}\n\t\t\t\t\tthis._durableThoughtIdentities.appendThought(work.sessionId, work.thought);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'backtrack': {\n\t\t\t\tconst index = this._thoughts.findIndex((candidate) => candidate === entry);\n\t\t\t\tif (index >= 0) {\n\t\t\t\t\tthis._thoughts.splice(index, 1);\n\t\t\t\t\tthis._decrementPendingThoughts(work.sessionId);\n\t\t\t\t\tif (work.thought.id !== undefined) {\n\t\t\t\t\t\tthis._removeThoughtIdentity(work.sessionId, work.thought.id);\n\t\t\t\t\t}\n\t\t\t\t\tthis._durableThoughtIdentities.appendThought(work.sessionId, work.thought);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tcase 'branch':\n\t\t\t\tthis._branches.get(work.sessionId)?.delete(work.key);\n\t\t\t\tif (!this._persistBranches) return;\n\t\t\t\tif (work.operation === 'save') {\n\t\t\t\t\tthis._durableThoughtIdentities.replaceBranch(work.sessionId, work.key, work.snapshot);\n\t\t\t\t} else {\n\t\t\t\t\tthis._durableThoughtIdentities.deleteBranch(work.sessionId, work.key);\n\t\t\t\t}\n\t\t\t\treturn;\n\t\t\tcase 'edge':\n\t\t\t\tthis._edges.delete(work.key);\n\t\t\t\treturn;\n\t\t\tcase 'summary':\n\t\t\t\tthis._summaries.delete(work.key);\n\t\t\t\treturn;\n\t\t\tdefault:\n\t\t\t\tassertNever(work);\n\t\t}\n\t}\n\n\t/**\n\t * Attaches a terminal failure only when both work and failure still match current work.\n\t *\n\t * @param work - Previously selected work handle.\n\t * @param failure - Terminal backend failure attributed to that handle.\n\t */\n\tpublic acknowledgeFailure(work: PersistenceWork, failure: PersistenceWorkFailure): void {\n\t\tif (!this._matchesFailure(work, failure)) return;\n\t\tconst entry = this._currentEntry(work);\n\t\tif (entry !== undefined) entry.terminalFailure = Object.freeze({ ...failure });\n\t}\n\n\t/**\n\t * Returns an immutable acceptance-ordered snapshot of current terminal failures.\n\t *\n\t * @param selectedTokens - Optional generation-token projection.\n\t * @param sessionId - Optional session projection.\n\t * @returns A fresh readonly failure array containing only failures on current entries.\n\t */\n\tpublic currentFailures(\n\t\tselectedTokens?: ReadonlySet<PersistenceWorkToken>,\n\t\tsessionId?: SessionId\n\t): readonly PersistenceWorkFailure[] {\n\t\tconst failures = this._entries()\n\t\t\t.filter(\n\t\t\t\t(entry) =>\n\t\t\t\t\tentry.terminalFailure !== undefined &&\n\t\t\t\t\t(selectedTokens === undefined || selectedTokens.has(entry.work.token)) &&\n\t\t\t\t\t(sessionId === undefined || entry.work.sessionId === sessionId)\n\t\t\t)\n\t\t\t.sort((left, right) => left.acceptedSequence - right.acceptedSequence)\n\t\t\t.flatMap((entry) => (entry.terminalFailure === undefined ? [] : [entry.terminalFailure]));\n\t\treturn Object.freeze(failures);\n\t}\n\n\t/**\n\t * Captures the current immutable result for a generation or session projection.\n\t *\n\t * @param selectedTokens - Optional generation-token projection.\n\t * @param sessionId - Optional session projection.\n\t * @returns A result containing a fresh readonly failure snapshot.\n\t */\n\tpublic generationResult(\n\t\tselectedTokens?: ReadonlySet<PersistenceWorkToken>,\n\t\tsessionId?: SessionId\n\t): PersistenceGenerationResult {\n\t\treturn Object.freeze({ failures: this.currentFailures(selectedTokens, sessionId) });\n\t}\n\n\t/** @returns Number of accepted thought writes not yet acknowledged successful. */\n\tpublic get pendingThoughtCount(): number {\n\t\treturn this._thoughts.length;\n\t}\n\n\t/**\n\t * @param sessionId - Session whose unacknowledged writes are counted.\n\t * @returns Unacknowledged thought and backtrack entries for the session, terminal failures\n\t * included. Coalesced branch, edge and summary entries are not counted.\n\t */\n\tpublic pendingThoughtCountForSession(sessionId: SessionId): number {\n\t\treturn this._pendingThoughtsBySession.get(sessionId) ?? 0;\n\t}\n\n\t/** @returns Number of all current thought and coalesced auxiliary entries. */\n\tpublic get pendingWorkCount(): number {\n\t\tlet branchCount = 0;\n\t\tfor (const branches of this._branches.values()) branchCount += branches.size;\n\t\treturn this._thoughts.length + branchCount + this._edges.size + this._summaries.size;\n\t}\n\n\t/** @returns Whether any accepted work remains for a session across all work kinds. */\n\tpublic hasSessionWork(sessionId: SessionId): boolean {\n\t\treturn this._entries().some((entry) => entry.work.sessionId === sessionId);\n\t}\n\n\t/** @returns Whether current retained work for a session owns a terminal failure. */\n\tpublic hasSessionTerminalFailure(sessionId: SessionId): boolean {\n\t\treturn this.currentFailures(undefined, sessionId).length > 0;\n\t}\n\n\t/**\n\t * Forgets version coordinates only after all accepted work for a session is gone.\n\t *\n\t * @returns `false` without mutation while any accepted work remains.\n\t */\n\tpublic forgetQuiescentSession(sessionId: SessionId): boolean {\n\t\tif (this.hasSessionWork(sessionId)) return false;\n\t\tthis._branches.delete(sessionId);\n\t\tthis._branchVersions.delete(sessionId);\n\t\tthis._edgeVersions.delete(sessionId);\n\t\tthis._summaryVersions.delete(sessionId);\n\t\treturn true;\n\t}\n\n\t/** Discards every retained work item and version coordinate for one deleted session. */\n\tpublic discardSession(sessionId: SessionId): void {\n\t\tfor (let index = this._thoughts.length - 1; index >= 0; index -= 1) {\n\t\t\tif (this._thoughts[index]?.work.sessionId === sessionId) this._thoughts.splice(index, 1);\n\t\t}\n\t\tthis._pendingThoughtsBySession.delete(sessionId);\n\t\tthis._thoughtIdentities.delete(sessionId);\n\t\tthis._durableThoughtIdentities.clearSession(sessionId);\n\t\tthis._branches.delete(sessionId);\n\t\tthis._edges.delete(sessionId);\n\t\tthis._summaries.delete(sessionId);\n\t\tthis._branchVersions.delete(sessionId);\n\t\tthis._edgeVersions.delete(sessionId);\n\t\tthis._summaryVersions.delete(sessionId);\n\t}\n\n\t/** Discards all retained work after a successful durable global reset. */\n\tpublic discardAll(): void {\n\t\tthis._thoughts.length = 0;\n\t\tthis._pendingThoughtsBySession.clear();\n\t\tthis._thoughtIdentities.clear();\n\t\tthis._durableThoughtIdentities.clearAll();\n\t\tthis._branches.clear();\n\t\tthis._edges.clear();\n\t\tthis._summaries.clear();\n\t\tthis._branchVersions.clear();\n\t\tthis._edgeVersions.clear();\n\t\tthis._summaryVersions.clear();\n\t}\n\n\tprivate _accept(): Acceptance {\n\t\tconst sequence = this._nextSequence;\n\t\tthis._nextSequence += 1;\n\t\treturn { token: `persistence-work-${sequence}`, sequence };\n\t}\n\n\tprivate _freezeClone<T>(value: T): T {\n\t\tconst clone = structuredClone(value);\n\t\treturn this._deepFreeze(clone);\n\t}\n\n\tprivate _deepFreeze<T>(value: T): T {\n\t\tif (value !== null && typeof value === 'object') {\n\t\t\tfor (const nested of Object.values(value)) this._deepFreeze(nested);\n\t\t\tObject.freeze(value);\n\t\t}\n\t\treturn value;\n\t}\n\n\tprivate _incrementPendingThoughts(sessionId: SessionId): void {\n\t\tthis._pendingThoughtsBySession.set(\n\t\t\tsessionId,\n\t\t\tthis.pendingThoughtCountForSession(sessionId) + 1\n\t\t);\n\t}\n\n\tprivate _decrementPendingThoughts(sessionId: SessionId): void {\n\t\tconst remaining = this.pendingThoughtCountForSession(sessionId) - 1;\n\t\tif (remaining > 0) this._pendingThoughtsBySession.set(sessionId, remaining);\n\t\telse this._pendingThoughtsBySession.delete(sessionId);\n\t}\n\n\tprivate _addThoughtIdentity(sessionId: SessionId, thoughtId: ThoughtId): void {\n\t\tconst identities = this._thoughtIdentities.get(sessionId) ?? new Map<ThoughtId, number>();\n\t\tidentities.set(thoughtId, (identities.get(thoughtId) ?? 0) + 1);\n\t\tthis._thoughtIdentities.set(sessionId, identities);\n\t}\n\n\tprivate _removeThoughtIdentity(sessionId: SessionId, thoughtId: ThoughtId): void {\n\t\tconst identities = this._thoughtIdentities.get(sessionId);\n\t\tconst count = identities?.get(thoughtId);\n\t\tif (identities === undefined || count === undefined) return;\n\t\tif (count > 1) identities.set(thoughtId, count - 1);\n\t\telse identities.delete(thoughtId);\n\t\tif (identities.size === 0) this._thoughtIdentities.delete(sessionId);\n\t}\n\n\tprivate _entries(): AnyQueueEntry[] {\n\t\tconst entries: AnyQueueEntry[] = [...this._thoughts];\n\t\tfor (const branches of this._branches.values()) entries.push(...branches.values());\n\t\tentries.push(...this._edges.values(), ...this._summaries.values());\n\t\treturn entries;\n\t}\n\n\tprivate _findEligible(\n\t\tselectedTokens: ReadonlySet<PersistenceWorkToken>,\n\t\tmode: PersistenceSelectionMode,\n\t\tsessionId?: SessionId\n\t): AnyQueueEntry | undefined {\n\t\tlet oldest: AnyQueueEntry | undefined;\n\t\tfor (const entry of this._entries()) {\n\t\t\tif (selectedTokens.has(entry.work.token)) continue;\n\t\t\tif (sessionId !== undefined && entry.work.sessionId !== sessionId) continue;\n\t\t\tif (!this._modeAllows(mode, entry.terminalFailure !== undefined)) continue;\n\t\t\tif (oldest === undefined || entry.acceptedSequence < oldest.acceptedSequence) oldest = entry;\n\t\t}\n\t\treturn oldest;\n\t}\n\n\tprivate _modeAllows(mode: PersistenceSelectionMode, hasTerminalFailure: boolean): boolean {\n\t\tswitch (mode) {\n\t\t\tcase 'explicit':\n\t\t\t\treturn true;\n\t\t\tcase 'background':\n\t\t\t\treturn !hasTerminalFailure;\n\t\t\tdefault:\n\t\t\t\treturn assertNever(mode);\n\t\t}\n\t}\n\n\tprivate _currentEntry(work: PersistenceWork): AnyQueueEntry | undefined {\n\t\tlet entry: AnyQueueEntry | undefined;\n\t\tswitch (work.kind) {\n\t\t\tcase 'thought':\n\t\t\tcase 'backtrack':\n\t\t\t\tentry = this._thoughts.find((candidate) => candidate.work.token === work.token);\n\t\t\t\tbreak;\n\t\t\tcase 'branch':\n\t\t\t\tentry = this._branches.get(work.sessionId)?.get(work.key);\n\t\t\t\tbreak;\n\t\t\tcase 'edge':\n\t\t\t\tentry = this._edges.get(work.key);\n\t\t\t\tbreak;\n\t\t\tcase 'summary':\n\t\t\t\tentry = this._summaries.get(work.key);\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\treturn assertNever(work);\n\t\t}\n\t\treturn entry !== undefined && this._matchesWork(entry.work, work) ? entry : undefined;\n\t}\n\n\tprivate _matchesWork(current: PersistenceWork, selected: PersistenceWork): boolean {\n\t\tif (\n\t\t\tcurrent.kind !== selected.kind ||\n\t\t\tcurrent.token !== selected.token ||\n\t\t\tcurrent.sessionId !== selected.sessionId\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tswitch (selected.kind) {\n\t\t\tcase 'thought':\n\t\t\t\treturn current.kind === 'thought';\n\t\t\tcase 'backtrack':\n\t\t\t\treturn current.kind === 'backtrack' && current.targetThoughtId === selected.targetThoughtId;\n\t\t\tcase 'branch':\n\t\t\t\treturn (\n\t\t\t\t\tcurrent.kind === 'branch' &&\n\t\t\t\t\tcurrent.operation === selected.operation &&\n\t\t\t\t\tcurrent.key === selected.key &&\n\t\t\t\t\tcurrent.version === selected.version\n\t\t\t\t);\n\t\t\tcase 'edge':\n\t\t\t\treturn (\n\t\t\t\t\tcurrent.kind === 'edge' &&\n\t\t\t\t\tcurrent.key === selected.key &&\n\t\t\t\t\tcurrent.version === selected.version\n\t\t\t\t);\n\t\t\tcase 'summary':\n\t\t\t\treturn (\n\t\t\t\t\tcurrent.kind === 'summary' &&\n\t\t\t\t\tcurrent.key === selected.key &&\n\t\t\t\t\tcurrent.version === selected.version\n\t\t\t\t);\n\t\t\tdefault:\n\t\t\t\treturn assertNever(selected);\n\t\t}\n\t}\n\n\tprivate _matchesFailure(work: PersistenceWork, failure: PersistenceWorkFailure): boolean {\n\t\tif (\n\t\t\twork.kind !== failure.kind ||\n\t\t\twork.token !== failure.token ||\n\t\t\twork.sessionId !== failure.sessionId\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tswitch (work.kind) {\n\t\t\tcase 'thought':\n\t\t\tcase 'backtrack':\n\t\t\t\treturn true;\n\t\t\tcase 'branch':\n\t\t\t\treturn (\n\t\t\t\t\tfailure.kind === 'branch' &&\n\t\t\t\t\twork.operation === failure.operation &&\n\t\t\t\t\twork.key === failure.key &&\n\t\t\t\t\twork.version === failure.version\n\t\t\t\t);\n\t\t\tcase 'edge':\n\t\t\tcase 'summary':\n\t\t\t\treturn 'key' in failure && work.key === failure.key && work.version === failure.version;\n\t\t\tdefault:\n\t\t\t\treturn assertNever(work);\n\t\t}\n\t}\n}\n"],"names":["PersistenceWorkQueue","Map","durableHistorySize","persistBranches","DurableThoughtIdentityIndex","normalizeDurableHistoryRetention","sessionId","thought","acceptance","work","Object","undefined","targetThoughtId","thoughtId","sessions","branchId","thoughts","versionMap","version","branchMap","edges","summaries","selectedTokens","mode","entry","index","candidate","assertNever","failure","failures","left","right","branchCount","branches","sequence","value","clone","structuredClone","nested","remaining","identities","count","entries","oldest","hasTerminalFailure","current","selected"],"mappings":";;AAiEO,MAAMA;IACK,YAAkD,EAAE,CAAC;IACrD,qBAAqB,IAAI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OAAO;YAEtC,KAAK;gBACJ,OACCD,AAAiB,cAAjBA,QAAQ,IAAI,IACZA,QAAQ,GAAG,KAAKC,SAAS,GAAG,IAC5BD,QAAQ,OAAO,KAAKC,SAAS,OAAO;YAEtC;gBACC,OAAOnB,YAAYmB;QACrB;IACD;IAEQ,gBAAgBrC,IAAqB,EAAEmB,OAA+B,EAAW;QACxF,IACCnB,KAAK,IAAI,KAAKmB,QAAQ,IAAI,IAC1BnB,KAAK,KAAK,KAAKmB,QAAQ,KAAK,IAC5BnB,KAAK,SAAS,KAAKmB,QAAQ,SAAS,EAEpC,OAAO;QAER,OAAQnB,KAAK,IAAI;YAChB,KAAK;YACL,KAAK;gBACJ,OAAO;YACR,KAAK;gBACJ,OACCmB,AAAiB,aAAjBA,QAAQ,IAAI,IACZnB,KAAK,SAAS,KAAKmB,QAAQ,SAAS,IACpCnB,KAAK,GAAG,KAAKmB,QAAQ,GAAG,IACxBnB,KAAK,OAAO,KAAKmB,QAAQ,OAAO;YAElC,KAAK;YACL,KAAK;gBACJ,OAAO,SAASA,WAAWnB,KAAK,GAAG,KAAKmB,QAAQ,GAAG,IAAInB,KAAK,OAAO,KAAKmB,QAAQ,OAAO;YACxF;gBACC,OAAOD,YAAYlB;QACrB;IACD;AACD"}
|
|
@@ -50,9 +50,15 @@ export declare class ThoughtEvaluator {
|
|
|
50
50
|
constructor(calibrator: ICalibrator);
|
|
51
51
|
/** Compute confidence signals from history context. Pure computation. */
|
|
52
52
|
computeConfidenceSignals(history: ThoughtData[], branches: Record<string, ThoughtData[]>, context: ConfidenceSignalContext): ConfidenceSignals;
|
|
53
|
+
private _computeConfidenceSignals;
|
|
53
54
|
/** Compute aggregated reasoning analytics. Pure computation. */
|
|
54
55
|
computeReasoningStats(history: ThoughtData[], branches: Record<string, ThoughtData[]>, context?: VerificationLinkContext): ReasoningStats;
|
|
55
56
|
/** Detect reasoning patterns (anti-patterns and positive signals). Pure computation. */
|
|
56
57
|
computePatternSignals(history: ThoughtData[], branches: Record<string, ThoughtData[]>, context?: PatternSignalContext): PatternSignal[];
|
|
58
|
+
computeAdmissionSignals(history: ThoughtData[], branches: Record<string, ThoughtData[]>, context: ConfidenceSignalContext): {
|
|
59
|
+
readonly confidenceSignals: ConfidenceSignals;
|
|
60
|
+
readonly reasoningStats: ReasoningStats;
|
|
61
|
+
readonly patternSignals: PatternSignal[];
|
|
62
|
+
};
|
|
57
63
|
}
|
|
58
64
|
//# sourceMappingURL=ThoughtEvaluator.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ThoughtEvaluator.d.ts","sourceRoot":"","sources":["../../src/core/ThoughtEvaluator.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChE,OAAO,KAAK,EAAE,iBAAiB,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AACvF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"ThoughtEvaluator.d.ts","sourceRoot":"","sources":["../../src/core/ThoughtEvaluator.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAC9D,OAAO,KAAK,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AAChE,OAAO,KAAK,EAAE,iBAAiB,EAAE,aAAa,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AACvF,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAOhD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,oCAAoC,CAAC;AAE7E,MAAM,WAAW,uBAAuB;IACvC,QAAQ,CAAC,mBAAmB,CAAC,EAAE,WAAW,CAAC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,EAAE,MAAM,CAAC,MAAM,EAAE,WAAW,EAAE,CAAC,EACvC,OAAO,EAAE,uBAAuB,GAC9B;QACF,QAAQ,CAAC,iBAAiB,EAAE,iBAAiB,CAAC;QAC9C,QAAQ,CAAC,cAAc,EAAE,cAAc,CAAC;QACxC,QAAQ,CAAC,cAAc,EAAE,aAAa,EAAE,CAAC;KACzC;CAkBD"}
|
|
@@ -18,9 +18,12 @@ class ThoughtEvaluator {
|
|
|
18
18
|
computeConfidenceSignals(history, branches, context) {
|
|
19
19
|
const links = resolveVerificationLinks(history, branches, context.verificationTargets);
|
|
20
20
|
const { branches: b } = filterRetracted(history, branches);
|
|
21
|
+
return this._computeConfidenceSignals(links, b, context);
|
|
22
|
+
}
|
|
23
|
+
_computeConfidenceSignals(links, branches, context) {
|
|
21
24
|
const baseSignals = this._signalComputer.computeConfidenceSignals([
|
|
22
25
|
...links.thoughts
|
|
23
|
-
],
|
|
26
|
+
], branches, links);
|
|
24
27
|
const graphSignals = void 0 === context.activeGraph ? void 0 : this._graphSignalComputer.compute(context.activeGraph);
|
|
25
28
|
const signals = void 0 === graphSignals ? baseSignals : {
|
|
26
29
|
...baseSignals,
|
|
@@ -49,6 +52,17 @@ class ThoughtEvaluator {
|
|
|
49
52
|
const links = resolveVerificationLinks(history, branches, context.verificationTargets);
|
|
50
53
|
return this._patternDetector.computePatternSignals(h, b, links, context.activeGraph);
|
|
51
54
|
}
|
|
55
|
+
computeAdmissionSignals(history, branches, context) {
|
|
56
|
+
const links = resolveVerificationLinks(history, branches, context.verificationTargets);
|
|
57
|
+
const active = filterRetracted(history, branches);
|
|
58
|
+
return {
|
|
59
|
+
confidenceSignals: this._computeConfidenceSignals(links, active.branches, context),
|
|
60
|
+
reasoningStats: this._aggregator.computeReasoningStats([
|
|
61
|
+
...links.thoughts
|
|
62
|
+
], active.branches, links),
|
|
63
|
+
patternSignals: this._patternDetector.computePatternSignals(active.history, active.branches, links, context.activeGraph)
|
|
64
|
+
};
|
|
65
|
+
}
|
|
52
66
|
}
|
|
53
67
|
function filterRetracted(history, branches) {
|
|
54
68
|
const h = history.filter((t)=>!t.retracted);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core/ThoughtEvaluator.js","sources":["../../src/core/ThoughtEvaluator.ts"],"sourcesContent":["/**\n * Quality signal computation for sequential thinking.\n *\n * Thin facade that composes the extracted evaluator submodules\n * ({@link SignalComputer}, {@link Aggregator}, {@link PatternDetector})\n * to preserve the original {@link ThoughtEvaluator} public API.\n *\n * @module core/ThoughtEvaluator\n */\n\nimport type { ICalibrator } from '../contracts/calibrator.js';\nimport type { SessionId, ThoughtId } from '../contracts/ids.js';\nimport type { ConfidenceSignals, PatternSignal, ReasoningStats } from './reasoning.js';\nimport type { ThoughtData } from './thought.js';\nimport { Aggregator } from './evaluator/Aggregator.js';\nimport { PatternDetector } from './evaluator/PatternDetector.js';\nimport { SignalComputer } from './evaluator/SignalComputer.js';\nimport { resolveVerificationLinks } from './evaluator/VerificationLinks.js';\nimport { GraphSignalComputer } from './evaluator/GraphSignalComputer.js';\nimport type { ActiveGraphContext } from './evaluator/GraphSignalComputer.js';\n\nexport interface VerificationLinkContext {\n\treadonly verificationTargets?: ReadonlyMap<ThoughtId, ThoughtId>;\n}\n\n/** Explicit thought and canonical session used for response calibration. */\nexport interface GraphAwareContext {\n\treadonly activeGraph?: ActiveGraphContext;\n}\n\nexport interface PatternSignalContext extends VerificationLinkContext, GraphAwareContext {}\n\nexport interface ConfidenceSignalContext extends VerificationLinkContext, GraphAwareContext {\n\treadonly currentThought: ThoughtData;\n\treadonly sessionId: SessionId;\n}\n\n/**\n * Stateless service that computes quality signals and reasoning analytics\n * from thought history and branch data.\n *\n * @remarks\n * All methods are pure computations — no side effects, no I/O, no internal state.\n * Designed to be registered as transient in the DI container.\n *\n * @example\n * ```typescript\n * const evaluator = new ThoughtEvaluator(calibrator);\n * const signals = evaluator.computeConfidenceSignals(history, branches, context);\n * const stats = evaluator.computeReasoningStats(history, branches);\n * const patterns = evaluator.computePatternSignals(history, branches);\n * ```\n */\nexport class ThoughtEvaluator {\n\tprivate readonly _signalComputer: SignalComputer;\n\tprivate readonly _aggregator: Aggregator;\n\tprivate readonly _patternDetector: PatternDetector;\n\tprivate readonly _calibrator: ICalibrator;\n\tprivate readonly _graphSignalComputer = new GraphSignalComputer();\n\n\tconstructor(calibrator: ICalibrator) {\n\t\tthis._signalComputer = new SignalComputer();\n\t\tthis._aggregator = new Aggregator();\n\t\tthis._patternDetector = new PatternDetector();\n\t\tthis._calibrator = calibrator;\n\t}\n\n\t/** Compute confidence signals from history context. Pure computation. */\n\tpublic computeConfidenceSignals(\n\t\thistory: ThoughtData[],\n\t\tbranches: Record<string, ThoughtData[]>,\n\t\tcontext: ConfidenceSignalContext\n\t): ConfidenceSignals {\n\t\tconst links = resolveVerificationLinks(history, branches, context.verificationTargets);\n\t\tconst { branches: b } = filterRetracted(history, branches);\n\t\tconst baseSignals = this._signalComputer.computeConfidenceSignals(\n\t\t\t[...links.thoughts],\n\t\t\
|
|
1
|
+
{"version":3,"file":"core/ThoughtEvaluator.js","sources":["../../src/core/ThoughtEvaluator.ts"],"sourcesContent":["/**\n * Quality signal computation for sequential thinking.\n *\n * Thin facade that composes the extracted evaluator submodules\n * ({@link SignalComputer}, {@link Aggregator}, {@link PatternDetector})\n * to preserve the original {@link ThoughtEvaluator} public API.\n *\n * @module core/ThoughtEvaluator\n */\n\nimport type { ICalibrator } from '../contracts/calibrator.js';\nimport type { SessionId, ThoughtId } from '../contracts/ids.js';\nimport type { ConfidenceSignals, PatternSignal, ReasoningStats } from './reasoning.js';\nimport type { ThoughtData } from './thought.js';\nimport { Aggregator } from './evaluator/Aggregator.js';\nimport { PatternDetector } from './evaluator/PatternDetector.js';\nimport { SignalComputer } from './evaluator/SignalComputer.js';\nimport { resolveVerificationLinks } from './evaluator/VerificationLinks.js';\nimport type { VerificationLinks } from './evaluator/VerificationLinks.js';\nimport { GraphSignalComputer } from './evaluator/GraphSignalComputer.js';\nimport type { ActiveGraphContext } from './evaluator/GraphSignalComputer.js';\n\nexport interface VerificationLinkContext {\n\treadonly verificationTargets?: ReadonlyMap<ThoughtId, ThoughtId>;\n}\n\n/** Explicit thought and canonical session used for response calibration. */\nexport interface GraphAwareContext {\n\treadonly activeGraph?: ActiveGraphContext;\n}\n\nexport interface PatternSignalContext extends VerificationLinkContext, GraphAwareContext {}\n\nexport interface ConfidenceSignalContext extends VerificationLinkContext, GraphAwareContext {\n\treadonly currentThought: ThoughtData;\n\treadonly sessionId: SessionId;\n}\n\n/**\n * Stateless service that computes quality signals and reasoning analytics\n * from thought history and branch data.\n *\n * @remarks\n * All methods are pure computations — no side effects, no I/O, no internal state.\n * Designed to be registered as transient in the DI container.\n *\n * @example\n * ```typescript\n * const evaluator = new ThoughtEvaluator(calibrator);\n * const signals = evaluator.computeConfidenceSignals(history, branches, context);\n * const stats = evaluator.computeReasoningStats(history, branches);\n * const patterns = evaluator.computePatternSignals(history, branches);\n * ```\n */\nexport class ThoughtEvaluator {\n\tprivate readonly _signalComputer: SignalComputer;\n\tprivate readonly _aggregator: Aggregator;\n\tprivate readonly _patternDetector: PatternDetector;\n\tprivate readonly _calibrator: ICalibrator;\n\tprivate readonly _graphSignalComputer = new GraphSignalComputer();\n\n\tconstructor(calibrator: ICalibrator) {\n\t\tthis._signalComputer = new SignalComputer();\n\t\tthis._aggregator = new Aggregator();\n\t\tthis._patternDetector = new PatternDetector();\n\t\tthis._calibrator = calibrator;\n\t}\n\n\t/** Compute confidence signals from history context. Pure computation. */\n\tpublic computeConfidenceSignals(\n\t\thistory: ThoughtData[],\n\t\tbranches: Record<string, ThoughtData[]>,\n\t\tcontext: ConfidenceSignalContext\n\t): ConfidenceSignals {\n\t\tconst links = resolveVerificationLinks(history, branches, context.verificationTargets);\n\t\tconst { branches: b } = filterRetracted(history, branches);\n\t\treturn this._computeConfidenceSignals(links, b, context);\n\t}\n\n\tprivate _computeConfidenceSignals(\n\t\tlinks: VerificationLinks,\n\t\tbranches: Record<string, ThoughtData[]>,\n\t\tcontext: ConfidenceSignalContext\n\t): ConfidenceSignals {\n\t\tconst baseSignals = this._signalComputer.computeConfidenceSignals(\n\t\t\t[...links.thoughts],\n\t\t\tbranches,\n\t\t\tlinks\n\t\t);\n\t\tconst graphSignals =\n\t\t\tcontext.activeGraph === undefined\n\t\t\t\t? undefined\n\t\t\t\t: this._graphSignalComputer.compute(context.activeGraph);\n\t\tconst signals =\n\t\t\tgraphSignals === undefined ? baseSignals : { ...baseSignals, graph_signals: graphSignals };\n\t\tif (!this._calibrator.enabled) return signals;\n\n\t\tconst thought = context.currentThought;\n\t\tif (thought.confidence === undefined) return signals;\n\t\tconst sessionId = context.sessionId;\n\n\t\tconst result = this._calibrator.calibrate(\n\t\t\tthought.confidence,\n\t\t\tthought.thought_type ?? 'regular',\n\t\t\tsessionId\n\t\t);\n\t\treturn {\n\t\t\t...signals,\n\t\t\tcalibrated_confidence: result.calibrated,\n\t\t\tcalibration_metrics: this._calibrator.metrics(sessionId),\n\t\t};\n\t}\n\n\t/** Compute aggregated reasoning analytics. Pure computation. */\n\tpublic computeReasoningStats(\n\t\thistory: ThoughtData[],\n\t\tbranches: Record<string, ThoughtData[]>,\n\t\tcontext: VerificationLinkContext = {}\n\t): ReasoningStats {\n\t\tconst links = resolveVerificationLinks(history, branches, context.verificationTargets);\n\t\tconst { branches: b } = filterRetracted(history, branches);\n\t\treturn this._aggregator.computeReasoningStats([...links.thoughts], b, links);\n\t}\n\n\t/** Detect reasoning patterns (anti-patterns and positive signals). Pure computation. */\n\tpublic computePatternSignals(\n\t\thistory: ThoughtData[],\n\t\tbranches: Record<string, ThoughtData[]>,\n\t\tcontext: PatternSignalContext = {}\n\t): PatternSignal[] {\n\t\tconst { history: h, branches: b } = filterRetracted(history, branches);\n\t\tconst links = resolveVerificationLinks(history, branches, context.verificationTargets);\n\t\treturn this._patternDetector.computePatternSignals(h, b, links, context.activeGraph);\n\t}\n\n\tpublic computeAdmissionSignals(\n\t\thistory: ThoughtData[],\n\t\tbranches: Record<string, ThoughtData[]>,\n\t\tcontext: ConfidenceSignalContext\n\t): {\n\t\treadonly confidenceSignals: ConfidenceSignals;\n\t\treadonly reasoningStats: ReasoningStats;\n\t\treadonly patternSignals: PatternSignal[];\n\t} {\n\t\tconst links = resolveVerificationLinks(history, branches, context.verificationTargets);\n\t\tconst active = filterRetracted(history, branches);\n\t\treturn {\n\t\t\tconfidenceSignals: this._computeConfidenceSignals(links, active.branches, context),\n\t\t\treasoningStats: this._aggregator.computeReasoningStats(\n\t\t\t\t[...links.thoughts],\n\t\t\t\tactive.branches,\n\t\t\t\tlinks\n\t\t\t),\n\t\t\tpatternSignals: this._patternDetector.computePatternSignals(\n\t\t\t\tactive.history,\n\t\t\t\tactive.branches,\n\t\t\t\tlinks,\n\t\t\t\tcontext.activeGraph\n\t\t\t),\n\t\t};\n\t}\n}\n\n/**\n * Filters out logically retracted thoughts from history and branches.\n * Retracted thoughts remain in storage (event-sourcing) but are excluded\n * from quality signal calculations.\n */\nfunction filterRetracted(\n\thistory: ThoughtData[],\n\tbranches: Record<string, ThoughtData[]>\n): { history: ThoughtData[]; branches: Record<string, ThoughtData[]> } {\n\tconst h = history.filter((t) => !t.retracted);\n\tconst b: Record<string, ThoughtData[]> = {};\n\tfor (const [id, list] of Object.entries(branches)) {\n\t\tb[id] = list.filter((t) => !t.retracted);\n\t}\n\treturn { history: h, branches: b };\n}\n"],"names":["ThoughtEvaluator","GraphSignalComputer","calibrator","SignalComputer","Aggregator","PatternDetector","history","branches","context","links","resolveVerificationLinks","b","filterRetracted","baseSignals","graphSignals","undefined","signals","thought","sessionId","result","h","active","t","id","list","Object"],"mappings":";;;;;AAsDO,MAAMA;IACK,gBAAgC;IAChC,YAAwB;IACxB,iBAAkC;IAClC,YAAyB;IACzB,uBAAuB,IAAIC,sBAAsB;IAElE,YAAYC,UAAuB,CAAE;QACpC,IAAI,CAAC,eAAe,GAAG,IAAIC;QAC3B,IAA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CAAC,qBAAqB;IAWpC,gEAAgE;IACzD,0BAA0B,CAAC,SAAS,EAAE,SAAS,GAAG,IAAI;IAO7D,kFAAkF;IAC3E,sBAAsB,IAAI,IAAI;IAOrC,OAAO,CAAC,2BAA2B;YAWrB,aAAa;IAiG3B,OAAO,CAAC,0BAA0B;IAWlC,OAAO,CAAC,wBAAwB;IAyBhC,OAAO,CAAC,oBAAoB;IAqB5B,OAAO,CAAC,qBAAqB;IA0C7B;;;;OAIG;IACH,OAAO,CAAC,YAAY;IAyCpB;;;;;OAKG;IACH,OAAO,CAAC,eAAe;IAavB,yDAAyD;IACzD,OAAO,CAAC,aAAa;IAIrB;;;;;;;;;;;;;;;;;;OAkBG;IACH,OAAO,CAAC,aAAa;IAoBrB;;;OAGG;IACH,OAAO,CAAC,0BAA0B;IAoDlC,OAAO,CAAC,iBAAiB;IAIzB;;;;;;;;;OASG;IACH,OAAO,CAAC,iBAAiB;IAYzB;;;OAGG;IACH,OAAO,CAAC,MAAM,CAAC,kBAAkB;IAajC;;;;OAIG;IACH,OAAO,CAAC,eAAe;IA0CvB;;;OAGG;YACW,sBAAsB;CAkBpC"}
|
|
@@ -91,7 +91,7 @@ class ThoughtProcessor {
|
|
|
91
91
|
this.historyManager.assertSessionResetAuthorized(sessionId);
|
|
92
92
|
return await this._lifecycle.withSessionReset(sessionId, operation);
|
|
93
93
|
}
|
|
94
|
-
this.historyManager.
|
|
94
|
+
this.historyManager.assertSessionAccessible(sessionId);
|
|
95
95
|
return await this._lifecycle.runOperation(sessionId, operation);
|
|
96
96
|
} catch (error) {
|
|
97
97
|
return this._buildErrorResponse(error);
|
|
@@ -267,20 +267,13 @@ class ThoughtProcessor {
|
|
|
267
267
|
view: evidence.graph
|
|
268
268
|
}
|
|
269
269
|
};
|
|
270
|
-
const verificationTargets = this.historyManager.
|
|
271
|
-
const confidenceSignals = this._thoughtEvaluator.
|
|
270
|
+
const verificationTargets = this.historyManager.getVerificationTargets(sessionId);
|
|
271
|
+
const { confidenceSignals, reasoningStats, patternSignals } = this._thoughtEvaluator.computeAdmissionSignals(history, branches, {
|
|
272
272
|
currentThought: input,
|
|
273
273
|
sessionId,
|
|
274
274
|
verificationTargets,
|
|
275
275
|
...graphScope
|
|
276
276
|
});
|
|
277
|
-
const reasoningStats = this._thoughtEvaluator.computeReasoningStats(history, branches, {
|
|
278
|
-
verificationTargets
|
|
279
|
-
});
|
|
280
|
-
const patternSignals = this._thoughtEvaluator.computePatternSignals(history, branches, {
|
|
281
|
-
verificationTargets,
|
|
282
|
-
...graphScope
|
|
283
|
-
});
|
|
284
277
|
const reasoningHints = this._generateHints(patternSignals, input.thought_number, sessionId);
|
|
285
278
|
return {
|
|
286
279
|
evidence,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core/ThoughtProcessor.js","sources":["../../src/core/ThoughtProcessor.ts"],"sourcesContent":["/**\n * Core thought processing logic and validation.\n *\n * This module provides the `ThoughtProcessor` class which handles the main\n * sequential thinking request processing pipeline, including input validation,\n * history management, and response formatting.\n *\n * @module processor\n */\n\nimport * as v from 'valibot';\n\nimport { NullLogger } from '../logger/NullLogger.js';\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport {\n\tasBranchId,\n\tasSessionId,\n\ttype BranchId,\n\ttype SessionId,\n\ttype ThoughtId,\n} from '../contracts/ids.js';\nimport type { IEdgeStore, IOutcomeRecorder } from '../contracts/interfaces.js';\nimport type { ICalibrator } from '../contracts/calibrator.js';\nimport type { ISuspensionStore, SuspensionRecord } from '../contracts/suspension.js';\nimport type {\n\tActiveEvidenceProjection,\n\tIReasoningStrategy,\n\tStrategyDecision,\n} from '../contracts/strategy.js';\nimport { DEFAULT_FLAGS, type FeatureFlags } from '../contracts/features.js';\nimport type { ISessionLock, IToolRegistry } from '../contracts/interfaces.js';\nimport {\n\tInvalidBacktrackError,\n\tInvalidToolCallError,\n\tSequentialThinkingError,\n\tUnknownToolError,\n\tValidationError,\n} from '../errors.js';\nimport { getErrorMessage, WARNING_CODES } from '../errors.js';\nimport { enforceJsonShape, JsonShapeError } from '../sanitize.js';\nimport { SequentialThinkingSchema } from '../schema.js';\nimport { GraphView } from './graph/GraphView.js';\nimport { buildActiveEvidenceProjection } from './reasoning/ActiveEvidenceProjection.js';\nimport { buildGraphContext, type GraphContext } from './reasoning/GraphContext.js';\nimport { assertNever } from '../utils.js';\nimport type {\n\tHistorySessionSnapshot,\n\tIHistoryManager,\n\tThoughtAdmissionContext,\n} from './IHistoryManager.js';\nimport { normalizeInput } from './InputNormalizer.js';\nimport type {\n\tThoughtData,\n\tToolCallThought,\n\tToolObservationThought,\n\tValidatedThought,\n} from './thought.js';\nimport type { ThoughtEvaluator } from './ThoughtEvaluator.js';\nimport type { ThoughtFormatter } from './ThoughtFormatter.js';\nimport type { PatternName } from '../contracts/reasoning-types.js';\nimport type { PatternSignal } from './reasoning.js';\nimport { SequentialStrategy } from './reasoning/strategies/SequentialStrategy.js';\nimport type { CompressionService } from './compression/CompressionService.js';\nimport { validateThoughtCrossReferences } from './CrossReferenceValidator.js';\nimport { SessionLifecycleCoordinator } from './SessionLifecycleCoordinator.js';\nimport { prepareVerificationOutcome } from './VerificationOutcomeAdmission.js';\n\ntype ConfidenceSignalsResult = ReturnType<ThoughtEvaluator['computeConfidenceSignals']>;\ntype ReasoningStatsResult = ReturnType<ThoughtEvaluator['computeReasoningStats']>;\n\ntype ReasoningSignalBundle = {\n\treadonly evidence: ActiveEvidenceProjection | undefined;\n\treadonly confidenceSignals: ConfidenceSignalsResult;\n\treadonly reasoningStats: ReasoningStatsResult;\n\treadonly reasoningHints: readonly string[];\n};\n\ntype ProcessedThoughtResponseState = {\n\treadonly thought: ThoughtData;\n\treadonly reasoning: {\n\t\treadonly confidenceSignals: ConfidenceSignalsResult;\n\t\treadonly reasoningStats: ReasoningStatsResult;\n\t\treadonly graphContext: GraphContext | undefined;\n\t\treadonly reasoningHints: readonly string[];\n\t};\n\treadonly decision: StrategyDecision | undefined;\n\treadonly warnings: readonly string[];\n};\n\ntype ThoughtProcessInput = ThoughtData & { readonly register_branch_id?: string };\n\ntype PreparedThought = {\n\treadonly thought: ThoughtData;\n\treadonly resetState: boolean;\n\treadonly registerBranchId: BranchId | undefined;\n\treadonly validationWarnings: readonly string[];\n};\n\n/**\n * The return type expected by MCP tool invocations.\n *\n * This structure matches the MCP protocol for tool results,\n * supporting both success and error responses.\n *\n * @example\n * ```typescript\n * const successResult: CallToolResult = {\n * content: [{ type: 'text', text: '{\"status\":\"success\"}' }]\n * };\n *\n * const errorResult: CallToolResult = {\n * content: [{ type: 'text', text: '{\"error\":\"Something went wrong\"}' }],\n * isError: true\n * };\n * ```\n */\nexport interface CallToolResult extends Record<string, unknown> {\n\t/** Array of content blocks (typically text) to return to the client. */\n\tcontent: Array<{\n\t\ttype: 'text';\n\t\ttext: string;\n\t}>;\n\n\t/** Whether this result represents an error condition. */\n\tisError?: boolean;\n}\n\n/**\n * Core processor for sequential thinking requests.\n *\n * Pipeline: validate → normalize → add to history → format → evaluate signals\n * → run reasoning strategy → return structured response.\n *\n * Auto-adjusts `total_thoughts` if `thought_number` exceeds it. All errors are\n * caught and returned as formatted error responses with `isError: true`.\n *\n * @example\n * ```typescript\n * const processor = new ThoughtProcessor(historyManager, formatter, new ThoughtEvaluator());\n * const result = await processor.process({\n * thought: '...',\n * thought_number: 1,\n * total_thoughts: 5,\n * next_thought_needed: true,\n * session_id: asSessionId('analysis')\n * });\n * ```\n */\nexport class ThoughtProcessor {\n\t/** Logger for debugging and monitoring. */\n\tprivate _logger: Logger;\n\n\t/** Evaluator for quality signal computation. */\n\tprivate readonly _thoughtEvaluator: ThoughtEvaluator;\n\n\t/**\n\t * Per-session cooldown tracker: session_id → pattern → last_fired_thought_number.\n\t * Prevents re-firing the same pattern hint within 3 thoughts.\n\t */\n\tprivate _hintCooldowns = new Map<SessionId, Map<PatternName, number>>();\n\n\t/**\n\t * Creates a new ThoughtProcessor instance.\n\t *\n\t * @param historyManager - History manager for storing thoughts\n\t * @param thoughtFormatter - Formatter for output formatting\n\t * @param thoughtEvaluator - Evaluator for quality signal computation\n\t * @param logger - Optional logger for diagnostics (defaults to NullLogger)\n\t * @param strategy - Reasoning strategy controlling next-action decisions (defaults to SequentialStrategy)\n\t * @param compressionService - Optional compression service for auto-compression on terminate\n\t * @param suspensionStore - Optional suspension store enabling tool interleave\n\t * @param toolRegistry - Optional tool registry for tool_name allowlist validation (required when toolInterleave is enabled)\n\t * @param features - Optional feature flags (defaults to DEFAULT_FLAGS — all opt-in flags off)\n\t * @param sessionLock - Optional per-session async lock; when provided, `process()` runs under it\n\t * @param outcomeRecorder - Optional per-session calibration outcome store\n\t */\n\tconstructor(\n\t\tprivate historyManager: IHistoryManager,\n\t\tprivate thoughtFormatter: ThoughtFormatter,\n\t\tthoughtEvaluator: ThoughtEvaluator,\n\t\tlogger?: Logger,\n\t\tprivate readonly strategy: IReasoningStrategy = new SequentialStrategy(),\n\t\tprivate readonly _compressionService?: CompressionService,\n\t\tprivate readonly _suspensionStore?: ISuspensionStore,\n\t\tprivate readonly _toolRegistry?: IToolRegistry,\n\t\tprivate readonly _features: FeatureFlags = DEFAULT_FLAGS,\n\t\tprivate readonly _sessionLock?: ISessionLock,\n\t\tprivate readonly _outcomeRecorder?: IOutcomeRecorder,\n\t\tprivate readonly _lifecycle: SessionLifecycleCoordinator = new SessionLifecycleCoordinator(),\n\t\tprivate readonly _calibrator?: ICalibrator\n\t) {\n\t\tthis._thoughtEvaluator = thoughtEvaluator;\n\t\tthis._logger = logger ?? new NullLogger();\n\t}\n\n\t/**\n\t * Internal logging method.\n\t * @param message - The message to log\n\t * @param meta - Optional metadata\n\t * @private\n\t */\n\tprivate log(message: string, meta?: Record<string, unknown>): void {\n\t\tthis._logger.info(message, meta);\n\t}\n\n\t/**\n\t * Priority ordering for warning patterns (lower = higher priority).\n\t * Ensures the most actionable patterns fill the hint cap first.\n\t */\n\tprivate static readonly _HINT_PRIORITY: Readonly<Partial<Record<PatternName, number>>> = {\n\t\trefuted_hypothesis_dependency: 1, // Invalid foundation — revise dependents first\n\t\tconfidence_drift: 2, // Degrading confidence\n\t\tunverified_hypothesis: 3, // Missing hypothesis evidence\n\t\tunaddressed_critique: 4, // Unresolved challenge\n\t\tno_alternatives_explored: 5, // Breadth gap\n\t\tconsecutive_without_verification: 6, // Routine pattern; monotonic_type stays unranked\n\t};\n\n\t/**\n\t * Generate actionable hints from pattern signals.\n\t * Rules: max 3 hints, warning-severity only, cooldown of 3 thoughts per pattern per session.\n\t *\n\t * Warning patterns are sorted by priority before selection (see _HINT_PRIORITY).\n\t * Higher-priority patterns (lower number) fill the hint cap first.\n\t *\n\t * @param patterns - Detected pattern signals\n\t * @param currentThoughtNumber - The current thought number being processed\n\t * @param sessionId - Session identifier for cooldown scoping\n\t * @returns Array of hint strings (max 3), empty if no warnings\n\t */\n\tprivate _generateHints(\n\t\tpatterns: PatternSignal[],\n\t\tcurrentThoughtNumber: number,\n\t\tsessionId: SessionId\n\t): string[] {\n\t\tconst warnings = patterns.filter((p) => p.severity === 'warning');\n\t\tif (warnings.length === 0) return [];\n\n\t\t// Sort by priority (lower number = higher priority)\n\t\twarnings.sort((a, b) => {\n\t\t\tconst pa = ThoughtProcessor._HINT_PRIORITY[a.pattern] ?? 99;\n\t\t\tconst pb = ThoughtProcessor._HINT_PRIORITY[b.pattern] ?? 99;\n\t\t\treturn pa - pb;\n\t\t});\n\n\t\tlet cooldowns = this._hintCooldowns.get(sessionId);\n\t\tif (cooldowns === undefined) {\n\t\t\tcooldowns = new Map();\n\t\t\tthis._hintCooldowns.set(sessionId, cooldowns);\n\t\t}\n\n\t\tconst hints: string[] = [];\n\t\tfor (const warning of warnings) {\n\t\t\tif (hints.length >= 3) break;\n\n\t\t\tconst lastFired = cooldowns.get(warning.pattern);\n\t\t\tif (lastFired !== undefined && currentThoughtNumber - lastFired < 3) {\n\t\t\t\tcontinue; // Still in cooldown\n\t\t\t}\n\n\t\t\thints.push(warning.message);\n\t\t\tcooldowns.set(warning.pattern, currentThoughtNumber);\n\t\t}\n\n\t\treturn hints;\n\t}\n\n\t/**\n\t * Processes a thought through the sequential thinking pipeline.\n\t *\n\t * This method validates the input, adds it to history, formats the output,\n\t * computes quality signals via the ThoughtEvaluator, and returns\n\t * a structured response with metadata about the current state.\n\t *\n\t * @param input - The thought data to process\n\t * @returns A Promise resolving to the formatted tool result containing:\n\t * - `thought_number` — Current thought index\n\t * - `total_thoughts` — Estimated total thoughts\n\t * - `next_thought_needed` — Whether to continue\n\t * - `branches` — Active branch IDs\n\t * - `thought_history_length` — Number of thoughts in history\n\t * - `available_mcp_tools` — MCP tools available for recommendation\n\t * - `available_skills` — Skills available for recommendation\n\t * - `current_step` — Current step recommendation\n\t * - `previous_steps` — Previously recommended steps\n\t * - `remaining_steps` — Upcoming step descriptions\n\t * - `thought_type` — Classification of thought purpose (optional)\n\t * - `quality_score` — Self-assessed quality score 0-1 (optional)\n\t * - `confidence` — Self-assessed confidence 0-1 (optional)\n\t * - `hypothesis_id` — Hypothesis link for verification chains (optional)\n\t * - `confidence_signals` — Computed reasoning quality signals (includes structural_quality and quality_components)\n\t * - `reasoning_stats` — Aggregated reasoning analytics\n\t * - `reasoning_hints` — (Conditional) Actionable hints from pattern analysis, max 3, warning-severity only (optional)\n\t *\n\t * @example\n\t * ```typescript\n\t * const result = await processor.process({\n\t * thought: 'I should read the README file',\n\t * thought_number: 1,\n\t * total_thoughts: 3,\n\t * next_thought_needed: true,\n\t * session_id: asSessionId('analysis')\n\t * });\n\t *\n\t * console.log(result.content[0].text);\n\t * // Output includes: thought_number, total_thoughts, next_thought_needed,\n\t * // branches, thought_history_length, and any recommendations\n\t * ```\n\t */\n\tpublic async process(input: ThoughtProcessInput): Promise<CallToolResult> {\n\t\ttry {\n\t\t\tconst prepared = this._prepareInput(input);\n\t\t\tconst sessionId = prepared.thought.session_id;\n\t\t\tconst operation = async (): Promise<CallToolResult> => {\n\t\t\t\tif (this._sessionLock !== undefined) {\n\t\t\t\t\treturn await this._sessionLock.withLock(sessionId, () => this._processInner(prepared));\n\t\t\t\t}\n\t\t\t\treturn await this._processInner(prepared);\n\t\t\t};\n\t\t\tif (prepared.resetState) {\n\t\t\t\tthis.historyManager.assertSessionResetAuthorized(sessionId);\n\t\t\t\treturn await this._lifecycle.withSessionReset(sessionId, operation);\n\t\t\t}\n\t\t\tthis.historyManager.inspectSession(sessionId);\n\t\t\treturn await this._lifecycle.runOperation(sessionId, operation);\n\t\t} catch (error) {\n\t\t\treturn this._buildErrorResponse(error);\n\t\t}\n\t}\n\n\t/** Resets one canonical session and its processor-owned auxiliary state. */\n\tpublic async resetSession(sessionId: string): Promise<void> {\n\t\tconst canonicalSessionId = asSessionId(sessionId);\n\t\tthis.historyManager.assertSessionResetAuthorized(canonicalSessionId);\n\t\tconst operation = async (): Promise<void> => {\n\t\t\tawait this.historyManager.resetSessionWithinExclusive(canonicalSessionId, () =>\n\t\t\t\tthis.clearSessionAuxiliaryState(canonicalSessionId)\n\t\t\t);\n\t\t};\n\t\tawait this._lifecycle.withSessionReset(canonicalSessionId, async () => {\n\t\t\tif (this._sessionLock !== undefined) {\n\t\t\t\tawait this._sessionLock.withLock(canonicalSessionId, operation);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait operation();\n\t\t});\n\t}\n\n\t/** Resets all history and processor-owned auxiliary state from a trusted context. */\n\tpublic async resetAll(): Promise<void> {\n\t\tawait this._lifecycle.withGlobalReset(\n\t\t\tasync () =>\n\t\t\t\tawait this.historyManager.resetAllWithinExclusive(() => this.clearAllAuxiliaryState())\n\t\t);\n\t}\n\n\tprivate _prepareInput(input: ThoughtProcessInput): PreparedThought {\n\t\tconst normalized = normalizeInput(input);\n\t\tif (typeof normalized === 'object' && normalized !== null) {\n\t\t\tthis._validateToolArgumentsShape(normalized.tool_arguments);\n\t\t}\n\t\tconst parsed = v.safeParse(SequentialThinkingSchema, normalized);\n\t\tif (!parsed.success) {\n\t\t\tconst firstIssue = parsed.issues[0];\n\t\t\tconst field = firstIssue?.path?.map((item) => String(item.key)).join('.') || 'input';\n\t\t\tthrow new ValidationError(field, firstIssue?.message ?? 'Invalid input');\n\t\t}\n\n\t\tconst internal = normalizeInput(parsed.output) as ThoughtData & {\n\t\t\tregister_branch_id?: string;\n\t\t};\n\t\tconst registerBranchId =\n\t\t\tinternal.register_branch_id === undefined\n\t\t\t\t? undefined\n\t\t\t\t: asBranchId(internal.register_branch_id);\n\t\tconst thought = { ...internal };\n\t\tdelete thought.register_branch_id;\n\t\tconst { result, warnings } = this.validateInput(thought);\n\t\tthis._validateStatelessNewTypes(result);\n\t\treturn {\n\t\t\tthought: result,\n\t\t\tresetState: result.reset_state === true,\n\t\t\tregisterBranchId,\n\t\t\tvalidationWarnings: warnings,\n\t\t};\n\t}\n\n\tprivate _buildErrorResponse(error: unknown): CallToolResult {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text',\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...(error instanceof SequentialThinkingError && { code: error.code }),\n\t\t\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t\t\t\tmessage: getErrorMessage(error),\n\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t};\n\t}\n\n\tprivate static _emptySessionSnapshot(): HistorySessionSnapshot {\n\t\treturn {\n\t\t\thistory: [],\n\t\t\tbranches: {},\n\t\t\tverificationTargets: new Map(),\n\t\t\tbranchIds: [],\n\t\t\tavailableMcpTools: undefined,\n\t\t\tavailableSkills: undefined,\n\t\t};\n\t}\n\n\t/** Clears all processor-owned state for one removed session. */\n\tpublic clearSessionAuxiliaryState(sessionId: SessionId): void {\n\t\tthis._hintCooldowns.delete(sessionId);\n\t\tthis._suspensionStore?.clearSession(sessionId);\n\t\tthis._outcomeRecorder?.clearOutcomes(sessionId);\n\t\tthis._calibrator?.clearSession(sessionId);\n\t}\n\n\t/** Clears all processor-owned state after global reset or successful shutdown. */\n\tpublic clearAllAuxiliaryState(): void {\n\t\tthis._suspensionStore?.clearAll();\n\t\tthis._outcomeRecorder?.clearAllOutcomes();\n\t\tthis._calibrator?.clearAll();\n\t\tthis._hintCooldowns.clear();\n\t}\n\n\tprivate _validateToolArgumentsShape(toolArguments: unknown): void {\n\t\ttry {\n\t\t\tenforceJsonShape(toolArguments ?? {});\n\t\t} catch (error) {\n\t\t\tif (error instanceof JsonShapeError) {\n\t\t\t\tthrow new ValidationError('tool_arguments', error.reason);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate async _processInner(prepared: PreparedThought): Promise<CallToolResult> {\n\t\tconst { thought, resetState, registerBranchId } = prepared;\n\t\tconst sessionId = thought.session_id;\n\t\tif (resetState) this.historyManager.assertSessionResetAuthorized(sessionId);\n\t\tconst validationSnapshot = resetState\n\t\t\t? ThoughtProcessor._emptySessionSnapshot()\n\t\t\t: this.historyManager.inspectSession(sessionId);\n\t\tif (!resetState) {\n\t\t\tif (!thought.available_mcp_tools && validationSnapshot.availableMcpTools) {\n\t\t\t\tthought.available_mcp_tools = [...validationSnapshot.availableMcpTools];\n\t\t\t}\n\t\t\tif (!thought.available_skills && validationSnapshot.availableSkills) {\n\t\t\t\tthought.available_skills = [...validationSnapshot.availableSkills];\n\t\t\t}\n\t\t}\n\t\tconst resolveThoughtReference = resetState\n\t\t\t? () => ({ kind: 'missing' as const })\n\t\t\t: (thoughtNumber: number) =>\n\t\t\t\t\tthis.historyManager.resolveThoughtReference(sessionId, thoughtNumber);\n\t\tconst {\n\t\t\tresult: checkedInput,\n\t\t\twarnings: refWarnings,\n\t\t\tresolvedReferences,\n\t\t} = validateThoughtCrossReferences(thought, {\n\t\t\tsnapshot: validationSnapshot,\n\t\t\tresolveThoughtReference,\n\t\t\tstrictBranchReferences: resetState || registerBranchId !== undefined,\n\t\t\tlogger: this._logger,\n\t\t});\n\t\tconst verificationOutcome = prepareVerificationOutcome({\n\t\t\tinput: checkedInput,\n\t\t\tsnapshot: validationSnapshot,\n\t\t\tresolvedReferences,\n\t\t\tsessionId,\n\t\t\trecorder: this._outcomeRecorder,\n\t\t});\n\t\tconst allWarnings = [...prepared.validationWarnings, ...refWarnings];\n\t\tconst validated = this._validateNewTypes(checkedInput);\n\t\tconst admissionContext: ThoughtAdmissionContext = { resolvedReferences };\n\t\tif (resetState && validated.thought_type === 'tool_observation') {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t'tool_observation cannot resume a suspension in reset replacement state'\n\t\t\t);\n\t\t}\n\n\t\tif (resetState) {\n\t\t\tawait this.historyManager.resetSessionWithinExclusive(sessionId, () =>\n\t\t\t\tthis.clearSessionAuxiliaryState(sessionId)\n\t\t\t);\n\t\t\tthis.log('State reset for session', { sessionId });\n\t\t}\n\t\tthis.historyManager.assertThoughtIdentityAvailable(checkedInput);\n\t\tif (registerBranchId !== undefined) {\n\t\t\tthis.historyManager.registerBranch(sessionId, registerBranchId);\n\t\t}\n\n\t\t// Tool-interleave suspend path: persist the tool_call thought, then return\n\t\t// a `suspended` envelope without running strategy/evaluator.\n\t\tif (validated.thought_type === 'tool_call' && this._suspensionStore) {\n\t\t\treturn this._handleToolCall(validated, admissionContext);\n\t\t}\n\n\t\t// Tool-interleave resume path: consume the suspension and continue the\n\t\t// normal pipeline (addThought → format → evaluate → strategy).\n\t\tif (validated.thought_type === 'tool_observation' && this._suspensionStore) {\n\t\t\tawait this._handleToolObservation(validated, admissionContext);\n\t\t} else {\n\t\t\tthis.historyManager.addThought(checkedInput, admissionContext);\n\t\t}\n\t\tthis._recordVerificationOutcome(verificationOutcome, sessionId);\n\n\t\tconst formattedThought = this.thoughtFormatter.formatThought(checkedInput);\n\t\tthis.log(formattedThought, { sessionId });\n\n\t\tconst signals = this._collectReasoningSignals(checkedInput);\n\n\t\t// Strategy decision — pluggable reasoning policy hook.\n\t\t// Built after history/stats so strategies see the latest state.\n\t\tconst decision = this._runStrategy(checkedInput, signals.evidence, signals.reasoningStats);\n\n\t\treturn this._buildSuccessResponse({\n\t\t\tthought: checkedInput,\n\t\t\treasoning: {\n\t\t\t\tconfidenceSignals: signals.confidenceSignals,\n\t\t\t\treasoningStats: signals.reasoningStats,\n\t\t\t\tgraphContext:\n\t\t\t\t\tsignals.evidence === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: buildGraphContext(sessionId, checkedInput, signals.evidence),\n\t\t\t\treasoningHints: signals.reasoningHints,\n\t\t\t},\n\t\t\tdecision,\n\t\t\twarnings: allWarnings,\n\t\t});\n\t}\n\n\tprivate _recordVerificationOutcome(\n\t\toutcome: ReturnType<typeof prepareVerificationOutcome>,\n\t\tsessionId: SessionId\n\t): void {\n\t\tif (outcome === undefined) return;\n\t\tif (this._outcomeRecorder?.enabled === true) {\n\t\t\tthis._outcomeRecorder.recordVerification(outcome);\n\t\t}\n\t\tif (this._calibrator?.enabled === true) this._calibrator.refit(sessionId);\n\t}\n\n\tprivate _collectReasoningSignals(input: ThoughtData): ReasoningSignalBundle {\n\t\tconst sessionId = input.session_id;\n\t\tconst history = this.historyManager.getHistory(sessionId);\n\t\tconst branches = this.historyManager.getBranches(sessionId);\n\t\tconst evidence = this._buildActiveEvidence(sessionId, history, branches);\n\t\tconst graphScope =\n\t\t\tevidence?.graph === undefined ? {} : { activeGraph: { sessionId, view: evidence.graph } };\n\t\tconst verificationTargets = this.historyManager.inspectSession(sessionId).verificationTargets;\n\t\tconst confidenceSignals = this._thoughtEvaluator.computeConfidenceSignals(history, branches, {\n\t\t\tcurrentThought: input,\n\t\t\tsessionId,\n\t\t\tverificationTargets,\n\t\t\t...graphScope,\n\t\t});\n\t\tconst reasoningStats = this._thoughtEvaluator.computeReasoningStats(history, branches, {\n\t\t\tverificationTargets,\n\t\t});\n\t\tconst patternSignals = this._thoughtEvaluator.computePatternSignals(history, branches, {\n\t\t\tverificationTargets,\n\t\t\t...graphScope,\n\t\t});\n\t\tconst reasoningHints = this._generateHints(patternSignals, input.thought_number, sessionId);\n\n\t\treturn {\n\t\t\tevidence,\n\t\t\tconfidenceSignals,\n\t\t\treasoningStats,\n\t\t\treasoningHints,\n\t\t};\n\t}\n\n\tprivate _buildActiveEvidence(\n\t\tsessionId: SessionId,\n\t\thistory: readonly ThoughtData[],\n\t\tbranches: Record<BranchId, ThoughtData[]>\n\t): ActiveEvidenceProjection | undefined {\n\t\ttry {\n\t\t\treturn buildActiveEvidenceProjection({\n\t\t\t\tsessionId,\n\t\t\t\thistory,\n\t\t\t\tbranches,\n\t\t\t\tedgeStore: this._getEdgeStore(),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis._logger.warn('Active evidence projection failed — omitting graph and strategy hints', {\n\t\t\t\tsessionId,\n\t\t\t\terror: getErrorMessage(error),\n\t\t\t});\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate _buildSuccessResponse(state: ProcessedThoughtResponseState): CallToolResult {\n\t\tconst sessionId = state.thought.session_id;\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text' as const,\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthought_number: state.thought.thought_number,\n\t\t\t\t\t\t\ttotal_thoughts: state.thought.total_thoughts,\n\t\t\t\t\t\t\tnext_thought_needed: state.thought.next_thought_needed ?? true,\n\t\t\t\t\t\t\tbranches: this.historyManager.getBranchIds(sessionId),\n\t\t\t\t\t\t\tthought_history_length: this.historyManager.getHistoryLength(sessionId),\n\t\t\t\t\t\t\tavailable_mcp_tools: state.thought.available_mcp_tools,\n\t\t\t\t\t\t\tavailable_skills: state.thought.available_skills,\n\t\t\t\t\t\t\tcurrent_step: state.thought.current_step,\n\t\t\t\t\t\t\tprevious_steps: state.thought.previous_steps,\n\t\t\t\t\t\t\tremaining_steps: state.thought.remaining_steps,\n\t\t\t\t\t\t\tthought_type: state.thought.thought_type,\n\t\t\t\t\t\t\tquality_score: state.thought.quality_score,\n\t\t\t\t\t\t\tconfidence: state.thought.confidence,\n\t\t\t\t\t\t\thypothesis_id: state.thought.hypothesis_id,\n\t\t\t\t\t\t\tconfidence_signals: state.reasoning.confidenceSignals,\n\t\t\t\t\t\t\treasoning_stats: state.reasoning.reasoningStats,\n\t\t\t\t\t\t\t...(state.reasoning.graphContext !== undefined && {\n\t\t\t\t\t\t\t\tgraph_context: state.reasoning.graphContext,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...(state.reasoning.reasoningHints.length > 0 && {\n\t\t\t\t\t\t\t\treasoning_hints: state.reasoning.reasoningHints,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...(state.decision !== undefined && { strategy_hint: state.decision }),\n\t\t\t\t\t\t\t...(state.warnings.length > 0 && { warnings: state.warnings.slice(0, 3) }),\n\t\t\t\t\t\t\tsession_id: sessionId,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Run the configured reasoning strategy and return its decision.\n\t * Strategy errors omit the decision from the public response.\n\t * @private\n\t */\n\tprivate _runStrategy(\n\t\tcurrentThought: ThoughtData,\n\t\tevidence: ActiveEvidenceProjection | undefined,\n\t\tstats: ReturnType<ThoughtEvaluator['computeReasoningStats']>\n\t): StrategyDecision | undefined {\n\t\tconst sessionId = currentThought.session_id;\n\t\tlet decision: StrategyDecision | undefined;\n\t\ttry {\n\t\t\tif (evidence !== undefined) {\n\t\t\t\tdecision = this.strategy.decide({ sessionId, evidence, stats, currentThought });\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis._logger.warn('Reasoning strategy threw — omitting strategy hint', {\n\t\t\t\tstrategy: this.strategy.name,\n\t\t\t\terror: getErrorMessage(error),\n\t\t\t});\n\t\t}\n\n\t\t// Auto-compression trigger: when strategy terminates a branch and\n\t\t// compression is enabled, summarize the branch subtree. Compression\n\t\t// failures must NEVER break the thought pipeline.\n\t\tif (decision?.action === 'terminate' && this._compressionService && currentThought.branch_id) {\n\t\t\ttry {\n\t\t\t\tconst branchRoot = this._findBranchRoot(sessionId, currentThought.branch_id);\n\t\t\t\tif (branchRoot) {\n\t\t\t\t\tthis._compressionService.compressBranch(\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tcurrentThought.branch_id,\n\t\t\t\t\t\tbranchRoot as ThoughtId\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tthis._logger.debug('Compression auto-trigger failed', {\n\t\t\t\t\terror: getErrorMessage(err),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn decision;\n\t}\n\n\t/**\n\t * Locate the root thought id for a branch.\n\t * Prefers GraphView.branchThoughts() when an EdgeStore is available;\n\t * falls back to historyManager.getBranches(sessionId)[branchId][0].id.\n\t * @private\n\t */\n\tprivate _findBranchRoot(sessionId: SessionId, branchId: BranchId): string | undefined {\n\t\tconst edgeStore = this._getEdgeStore();\n\t\tconst branches = this.historyManager.getBranches(sessionId);\n\t\tconst branchList = branches[branchId];\n\t\tconst firstId = branchList?.[0]?.id;\n\t\tif (edgeStore && firstId) {\n\t\t\tconst graph = new GraphView(edgeStore);\n\t\t\tconst ids = graph.branchThoughts(sessionId, firstId);\n\t\t\tif (ids.length > 0) return ids[0];\n\t\t}\n\t\treturn firstId;\n\t}\n\n\t/** Access the EdgeStore via IHistoryManager. @private */\n\tprivate _getEdgeStore(): IEdgeStore | undefined {\n\t\treturn this.historyManager.getEdgeStore();\n\t}\n\n\t/**\n\t * Validates and normalizes thought input.\n\t *\n\t * Ensures that thought numbers are consistent and within valid ranges.\n\t * If `thought_number` exceeds `total_thoughts`, `total_thoughts` is\n\t * automatically adjusted to match and a warning is emitted.\n\t *\n\t * @param input - The input to validate\n\t * @returns Object with validated input and any warnings generated\n\t * @private\n\t *\n\t * @example\n\t * ```typescript\n\t * // Auto-adjusts total_thoughts when thought_number exceeds it\n\t * const { result, warnings } = this.validateInput(input);\n\t * // result.total_thoughts === 10 (auto-adjusted from 5)\n\t * // warnings === ['Auto-adjusted total_thoughts from 5 to 10 to match thought_number']\n\t * ```\n\t */\n\tprivate validateInput(input: ThoughtData): {\n\t\tresult: ThoughtData;\n\t\twarnings: string[];\n\t} {\n\t\tconst warnings: string[] = [];\n\t\tif (input.thought_number > input.total_thoughts) {\n\t\t\tconst originalTotal = input.total_thoughts;\n\t\t\twarnings.push(\n\t\t\t\t`[${WARNING_CODES.TOTAL_THOUGHTS_ADJUSTED}] Auto-adjusted total_thoughts from ${originalTotal} to ${input.thought_number} to match thought_number`\n\t\t\t);\n\t\t\tthis._logger.warn('Auto-adjusted total_thoughts to match thought_number', {\n\t\t\t\tthought_number: input.thought_number,\n\t\t\t\toriginal_total_thoughts: originalTotal,\n\t\t\t\tadjusted_total_thoughts: input.thought_number,\n\t\t\t});\n\t\t\tinput.total_thoughts = input.thought_number;\n\t\t}\n\t\treturn { result: input, warnings };\n\t}\n\n\t/**\n\t * Validate new thought-type invariants behind feature flags.\n\t * @private\n\t */\n\tprivate _validateStatelessNewTypes(input: ThoughtData): void {\n\t\tconst t = input.thought_type;\n\t\tif ((t === 'tool_call' || t === 'tool_observation') && !this._features.toolInterleave) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t`Type '${t}' requires the toolInterleave feature flag. Set TRACELATTICE_FEATURES_TOOL_INTERLEAVE=true to enable it.`\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\t(t === 'assumption' || t === 'decomposition' || t === 'backtrack') &&\n\t\t\t!this._features.newThoughtTypes\n\t\t) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t`Type '${t}' requires the newThoughtTypes feature flag. Set TRACELATTICE_FEATURES_NEW_THOUGHT_TYPES=true to enable it, or use '${ThoughtProcessor._getWorkaroundType(t)}' type as a workaround.`\n\t\t\t);\n\t\t}\n\t\tif (t === 'tool_call') {\n\t\t\tif (!input.tool_name) {\n\t\t\t\tthrow new InvalidToolCallError(\n\t\t\t\t\t'tool_call thought ' + input.thought_number + ' missing required tool_name'\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis._validateToolName(input.tool_name);\n\t\t}\n\t\tif (t === 'tool_observation' && !input.continuation_token) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'continuation_token',\n\t\t\t\t'tool_observation thought ' + input.thought_number + ' missing continuation_token'\n\t\t\t);\n\t\t}\n\t\tif (t === 'backtrack') {\n\t\t\tif (input.backtrack_target === undefined) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t'backtrack_target',\n\t\t\t\t\t'backtrack thought ' + input.thought_number + ' requires backtrack_target'\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (input.backtrack_target > input.thought_number) {\n\t\t\t\tthrow new InvalidBacktrackError(\n\t\t\t\t\t'backtrack_target ' +\n\t\t\t\t\t\tinput.backtrack_target +\n\t\t\t\t\t\t' must be <= thought_number ' +\n\t\t\t\t\t\tinput.thought_number\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (t === 'tool_call') {\n\t\t\tthis._validateToolArgumentsShape(input.tool_arguments);\n\t\t}\n\t}\n\n\tprivate _validateNewTypes(input: ThoughtData): ValidatedThought {\n\t\treturn input as ValidatedThought;\n\t}\n\n\t/**\n\t * Validate a tool_call's tool_name against the configured allowlist.\n\t *\n\t * Fails closed: if no tool registry was wired, all tool_call invocations are\n\t * rejected. This prevents arbitrary tool name injection through the protocol.\n\t *\n\t * @param toolName - The tool name from the tool_call thought\n\t * @throws {UnknownToolError} When no registry is wired or the tool is not registered\n\t * @private\n\t */\n\tprivate _validateToolName(toolName: string): void {\n\t\tif (!this._toolRegistry) {\n\t\t\tthrow new UnknownToolError(\n\t\t\t\ttoolName,\n\t\t\t\t`Tool '${toolName}' rejected: no tool registry configured. Tool interleave requires a registered allowlist.`\n\t\t\t);\n\t\t}\n\t\tif (!this._toolRegistry.has(toolName)) {\n\t\t\tthrow new UnknownToolError(toolName);\n\t\t}\n\t}\n\n\t/**\n\t * Returns a workaround thought type for a feature-flagged type.\n\t * @private\n\t */\n\tprivate static _getWorkaroundType(t: 'assumption' | 'decomposition' | 'backtrack'): string {\n\t\tswitch (t) {\n\t\t\tcase 'assumption':\n\t\t\t\treturn 'regular';\n\t\t\tcase 'decomposition':\n\t\t\t\treturn 'hypothesis';\n\t\t\tcase 'backtrack':\n\t\t\t\treturn 'regular';\n\t\t\tdefault:\n\t\t\t\tassertNever(t);\n\t\t}\n\t}\n\n\t/**\n\t * Persist a tool_call thought and return a `suspended` envelope.\n\t * Strategy/evaluator are intentionally skipped.\n\t * @private\n\t */\n\tprivate _handleToolCall(\n\t\tinput: ToolCallThought,\n\t\tadmissionContext: ThoughtAdmissionContext\n\t): CallToolResult {\n\t\tif (input.id === undefined) {\n\t\t\tthrow new ValidationError('id', 'tool_call requires an admitted thought id');\n\t\t}\n\t\tthis.historyManager.addThought(input, admissionContext);\n\t\tif (!this._suspensionStore) {\n\t\t\tthrow new ValidationError('thought_type', 'tool_call requires suspensionStore');\n\t\t}\n\t\tconst record: SuspensionRecord = this._suspensionStore.suspend({\n\t\t\tsessionId: input.session_id,\n\t\t\ttoolCallThoughtNumber: input.thought_number,\n\t\t\ttoolCallThoughtId: input.id,\n\t\t\ttoolName: input.tool_name,\n\t\t\ttoolArguments: input.tool_arguments ?? {},\n\t\t\texpiresAt: 0,\n\t\t});\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text' as const,\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstatus: 'suspended',\n\t\t\t\t\t\t\tcontinuation_token: record.token,\n\t\t\t\t\t\t\ttool_name: record.toolName,\n\t\t\t\t\t\t\ttool_arguments: record.toolArguments,\n\t\t\t\t\t\t\texpires_at: record.expiresAt,\n\t\t\t\t\t\t\tthought_number: input.thought_number,\n\t\t\t\t\t\t\ttotal_thoughts: input.total_thoughts,\n\t\t\t\t\t\t\tsession_id: input.session_id,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Resume from a tool_observation and atomically admit it before consuming the record.\n\t * @private\n\t */\n\tprivate async _handleToolObservation(\n\t\tinput: ToolObservationThought,\n\t\tadmissionContext: ThoughtAdmissionContext\n\t): Promise<void> {\n\t\tif (!this._suspensionStore) {\n\t\t\tthrow new ValidationError('thought_type', 'tool_observation requires suspensionStore');\n\t\t}\n\t\tawait this._suspensionStore.compareAndAdmit(\n\t\t\tinput.continuation_token,\n\t\t\tinput.session_id,\n\t\t\t(record) => {\n\t\t\t\tthis.historyManager.addThought(input, {\n\t\t\t\t\t...admissionContext,\n\t\t\t\t\ttoolInvocationSourceThoughtId: record.toolCallThoughtId,\n\t\t\t\t});\n\t\t\t}\n\t\t);\n\t}\n}\n"],"names":["ThoughtProcessor","Map","historyManager","thoughtFormatter","thoughtEvaluator","logger","strategy","SequentialStrategy","_compressionService","_suspensionStore","_toolRegistry","_features","DEFAULT_FLAGS","_sessionLock","_outcomeRecorder","_lifecycle","SessionLifecycleCoordinator","_calibrator","NullLogger","message","meta","patterns","currentThoughtNumber","sessionId","warnings","p","a","b","pa","pb","cooldowns","undefined","hints","warning","lastFired","input","prepared","operation","error","canonicalSessionId","asSessionId","normalized","normalizeInput","parsed","v","SequentialThinkingSchema","firstIssue","field","item","String","ValidationError","internal","registerBranchId","asBranchId","thought","result","JSON","SequentialThinkingError","getErrorMessage","toolArguments","enforceJsonShape","JsonShapeError","resetState","validationSnapshot","resolveThoughtReference","thoughtNumber","checkedInput","refWarnings","resolvedReferences","validateThoughtCrossReferences","verificationOutcome","prepareVerificationOutcome","allWarnings","validated","admissionContext","formattedThought","signals","decision","buildGraphContext","outcome","history","branches","evidence","graphScope","verificationTargets","confidenceSignals","reasoningStats","patternSignals","reasoningHints","buildActiveEvidenceProjection","state","currentThought","stats","branchRoot","err","branchId","edgeStore","branchList","firstId","graph","GraphView","ids","originalTotal","WARNING_CODES","t","InvalidToolCallError","InvalidBacktrackError","toolName","UnknownToolError","assertNever","record"],"mappings":";;;;;;;;;;;;;;;;AAoJO,MAAMA;;;;;;;;;;;;IAEJ,QAAgB;IAGP,kBAAoC;IAM7C,iBAAiB,IAAIC,MAA2C;IAiBxE,YACSC,cAA+B,EAC/BC,gBAAkC,EAC1CC,gBAAkC,EAClCC,MAAe,EACEC,WAA+B,IAAIC,oBAAoB,EACvDC,mBAAwC,EACxCC,gBAAmC,EACnCC,aAA6B,EAC7BC,YAA0BC,aAAa,EACvCC,YAA2B,EAC3BC,gBAAmC,EACnCC,aAA0C,IAAIC,6BAA6B,EAC3EC,WAAyB,CACzC;aAbOf,cAAc,GAAdA;aACAC,gBAAgB,GAAhBA;aAGSG,QAAQ,GAARA;aACAE,mBAAmB,GAAnBA;aACAC,gBAAgB,GAAhBA;aACAC,aAAa,GAAbA;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,IAAI,CAAC,OAAO,CAAC,IAAI,CAACD,SAASC;IAC5B;IAMA,OAAwB,iBAAiE;QACxF,+BAA+B;QAC/B,kBAAkB;QAClB,uBAAuB;QACvB,sBAAsB;QACtB,0BAA0B;QAC1B,kCAAkC;IACnC,EAAE;IAcM,eACPC,QAAyB,EACzBC,oBAA4B,EAC5BC,SAAoB,EACT;QACX,MAAMC,WAAWH,SAAS,MAAM,CAAC,CAACI,IAAMA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js","sources":["../../src/core/ThoughtProcessor.ts"],"sourcesContent":["/**\n * Core thought processing logic and validation.\n *\n * This module provides the `ThoughtProcessor` class which handles the main\n * sequential thinking request processing pipeline, including input validation,\n * history management, and response formatting.\n *\n * @module processor\n */\n\nimport * as v from 'valibot';\n\nimport { NullLogger } from '../logger/NullLogger.js';\nimport type { Logger } from '../logger/StructuredLogger.js';\nimport {\n\tasBranchId,\n\tasSessionId,\n\ttype BranchId,\n\ttype SessionId,\n\ttype ThoughtId,\n} from '../contracts/ids.js';\nimport type { IEdgeStore, IOutcomeRecorder } from '../contracts/interfaces.js';\nimport type { ICalibrator } from '../contracts/calibrator.js';\nimport type { ISuspensionStore, SuspensionRecord } from '../contracts/suspension.js';\nimport type {\n\tActiveEvidenceProjection,\n\tIReasoningStrategy,\n\tStrategyDecision,\n} from '../contracts/strategy.js';\nimport { DEFAULT_FLAGS, type FeatureFlags } from '../contracts/features.js';\nimport type { ISessionLock, IToolRegistry } from '../contracts/interfaces.js';\nimport {\n\tInvalidBacktrackError,\n\tInvalidToolCallError,\n\tSequentialThinkingError,\n\tUnknownToolError,\n\tValidationError,\n} from '../errors.js';\nimport { getErrorMessage, WARNING_CODES } from '../errors.js';\nimport { enforceJsonShape, JsonShapeError } from '../sanitize.js';\nimport { SequentialThinkingSchema } from '../schema.js';\nimport { GraphView } from './graph/GraphView.js';\nimport { buildActiveEvidenceProjection } from './reasoning/ActiveEvidenceProjection.js';\nimport { buildGraphContext, type GraphContext } from './reasoning/GraphContext.js';\nimport { assertNever } from '../utils.js';\nimport type {\n\tHistorySessionSnapshot,\n\tIHistoryManager,\n\tThoughtAdmissionContext,\n} from './IHistoryManager.js';\nimport { normalizeInput } from './InputNormalizer.js';\nimport type {\n\tThoughtData,\n\tToolCallThought,\n\tToolObservationThought,\n\tValidatedThought,\n} from './thought.js';\nimport type { ThoughtEvaluator } from './ThoughtEvaluator.js';\nimport type { ThoughtFormatter } from './ThoughtFormatter.js';\nimport type { PatternName } from '../contracts/reasoning-types.js';\nimport type { PatternSignal } from './reasoning.js';\nimport { SequentialStrategy } from './reasoning/strategies/SequentialStrategy.js';\nimport type { CompressionService } from './compression/CompressionService.js';\nimport { validateThoughtCrossReferences } from './CrossReferenceValidator.js';\nimport { SessionLifecycleCoordinator } from './SessionLifecycleCoordinator.js';\nimport { prepareVerificationOutcome } from './VerificationOutcomeAdmission.js';\n\ntype ConfidenceSignalsResult = ReturnType<ThoughtEvaluator['computeConfidenceSignals']>;\ntype ReasoningStatsResult = ReturnType<ThoughtEvaluator['computeReasoningStats']>;\n\ntype ReasoningSignalBundle = {\n\treadonly evidence: ActiveEvidenceProjection | undefined;\n\treadonly confidenceSignals: ConfidenceSignalsResult;\n\treadonly reasoningStats: ReasoningStatsResult;\n\treadonly reasoningHints: readonly string[];\n};\n\ntype ProcessedThoughtResponseState = {\n\treadonly thought: ThoughtData;\n\treadonly reasoning: {\n\t\treadonly confidenceSignals: ConfidenceSignalsResult;\n\t\treadonly reasoningStats: ReasoningStatsResult;\n\t\treadonly graphContext: GraphContext | undefined;\n\t\treadonly reasoningHints: readonly string[];\n\t};\n\treadonly decision: StrategyDecision | undefined;\n\treadonly warnings: readonly string[];\n};\n\ntype ThoughtProcessInput = ThoughtData & { readonly register_branch_id?: string };\n\ntype PreparedThought = {\n\treadonly thought: ThoughtData;\n\treadonly resetState: boolean;\n\treadonly registerBranchId: BranchId | undefined;\n\treadonly validationWarnings: readonly string[];\n};\n\n/**\n * The return type expected by MCP tool invocations.\n *\n * This structure matches the MCP protocol for tool results,\n * supporting both success and error responses.\n *\n * @example\n * ```typescript\n * const successResult: CallToolResult = {\n * content: [{ type: 'text', text: '{\"status\":\"success\"}' }]\n * };\n *\n * const errorResult: CallToolResult = {\n * content: [{ type: 'text', text: '{\"error\":\"Something went wrong\"}' }],\n * isError: true\n * };\n * ```\n */\nexport interface CallToolResult extends Record<string, unknown> {\n\t/** Array of content blocks (typically text) to return to the client. */\n\tcontent: Array<{\n\t\ttype: 'text';\n\t\ttext: string;\n\t}>;\n\n\t/** Whether this result represents an error condition. */\n\tisError?: boolean;\n}\n\n/**\n * Core processor for sequential thinking requests.\n *\n * Pipeline: validate → normalize → add to history → format → evaluate signals\n * → run reasoning strategy → return structured response.\n *\n * Auto-adjusts `total_thoughts` if `thought_number` exceeds it. All errors are\n * caught and returned as formatted error responses with `isError: true`.\n *\n * @example\n * ```typescript\n * const processor = new ThoughtProcessor(historyManager, formatter, new ThoughtEvaluator());\n * const result = await processor.process({\n * thought: '...',\n * thought_number: 1,\n * total_thoughts: 5,\n * next_thought_needed: true,\n * session_id: asSessionId('analysis')\n * });\n * ```\n */\nexport class ThoughtProcessor {\n\t/** Logger for debugging and monitoring. */\n\tprivate _logger: Logger;\n\n\t/** Evaluator for quality signal computation. */\n\tprivate readonly _thoughtEvaluator: ThoughtEvaluator;\n\n\t/**\n\t * Per-session cooldown tracker: session_id → pattern → last_fired_thought_number.\n\t * Prevents re-firing the same pattern hint within 3 thoughts.\n\t */\n\tprivate _hintCooldowns = new Map<SessionId, Map<PatternName, number>>();\n\n\t/**\n\t * Creates a new ThoughtProcessor instance.\n\t *\n\t * @param historyManager - History manager for storing thoughts\n\t * @param thoughtFormatter - Formatter for output formatting\n\t * @param thoughtEvaluator - Evaluator for quality signal computation\n\t * @param logger - Optional logger for diagnostics (defaults to NullLogger)\n\t * @param strategy - Reasoning strategy controlling next-action decisions (defaults to SequentialStrategy)\n\t * @param compressionService - Optional compression service for auto-compression on terminate\n\t * @param suspensionStore - Optional suspension store enabling tool interleave\n\t * @param toolRegistry - Optional tool registry for tool_name allowlist validation (required when toolInterleave is enabled)\n\t * @param features - Optional feature flags (defaults to DEFAULT_FLAGS — all opt-in flags off)\n\t * @param sessionLock - Optional per-session async lock; when provided, `process()` runs under it\n\t * @param outcomeRecorder - Optional per-session calibration outcome store\n\t */\n\tconstructor(\n\t\tprivate historyManager: IHistoryManager,\n\t\tprivate thoughtFormatter: ThoughtFormatter,\n\t\tthoughtEvaluator: ThoughtEvaluator,\n\t\tlogger?: Logger,\n\t\tprivate readonly strategy: IReasoningStrategy = new SequentialStrategy(),\n\t\tprivate readonly _compressionService?: CompressionService,\n\t\tprivate readonly _suspensionStore?: ISuspensionStore,\n\t\tprivate readonly _toolRegistry?: IToolRegistry,\n\t\tprivate readonly _features: FeatureFlags = DEFAULT_FLAGS,\n\t\tprivate readonly _sessionLock?: ISessionLock,\n\t\tprivate readonly _outcomeRecorder?: IOutcomeRecorder,\n\t\tprivate readonly _lifecycle: SessionLifecycleCoordinator = new SessionLifecycleCoordinator(),\n\t\tprivate readonly _calibrator?: ICalibrator\n\t) {\n\t\tthis._thoughtEvaluator = thoughtEvaluator;\n\t\tthis._logger = logger ?? new NullLogger();\n\t}\n\n\t/**\n\t * Internal logging method.\n\t * @param message - The message to log\n\t * @param meta - Optional metadata\n\t * @private\n\t */\n\tprivate log(message: string, meta?: Record<string, unknown>): void {\n\t\tthis._logger.info(message, meta);\n\t}\n\n\t/**\n\t * Priority ordering for warning patterns (lower = higher priority).\n\t * Ensures the most actionable patterns fill the hint cap first.\n\t */\n\tprivate static readonly _HINT_PRIORITY: Readonly<Partial<Record<PatternName, number>>> = {\n\t\trefuted_hypothesis_dependency: 1, // Invalid foundation — revise dependents first\n\t\tconfidence_drift: 2, // Degrading confidence\n\t\tunverified_hypothesis: 3, // Missing hypothesis evidence\n\t\tunaddressed_critique: 4, // Unresolved challenge\n\t\tno_alternatives_explored: 5, // Breadth gap\n\t\tconsecutive_without_verification: 6, // Routine pattern; monotonic_type stays unranked\n\t};\n\n\t/**\n\t * Generate actionable hints from pattern signals.\n\t * Rules: max 3 hints, warning-severity only, cooldown of 3 thoughts per pattern per session.\n\t *\n\t * Warning patterns are sorted by priority before selection (see _HINT_PRIORITY).\n\t * Higher-priority patterns (lower number) fill the hint cap first.\n\t *\n\t * @param patterns - Detected pattern signals\n\t * @param currentThoughtNumber - The current thought number being processed\n\t * @param sessionId - Session identifier for cooldown scoping\n\t * @returns Array of hint strings (max 3), empty if no warnings\n\t */\n\tprivate _generateHints(\n\t\tpatterns: PatternSignal[],\n\t\tcurrentThoughtNumber: number,\n\t\tsessionId: SessionId\n\t): string[] {\n\t\tconst warnings = patterns.filter((p) => p.severity === 'warning');\n\t\tif (warnings.length === 0) return [];\n\n\t\t// Sort by priority (lower number = higher priority)\n\t\twarnings.sort((a, b) => {\n\t\t\tconst pa = ThoughtProcessor._HINT_PRIORITY[a.pattern] ?? 99;\n\t\t\tconst pb = ThoughtProcessor._HINT_PRIORITY[b.pattern] ?? 99;\n\t\t\treturn pa - pb;\n\t\t});\n\n\t\tlet cooldowns = this._hintCooldowns.get(sessionId);\n\t\tif (cooldowns === undefined) {\n\t\t\tcooldowns = new Map();\n\t\t\tthis._hintCooldowns.set(sessionId, cooldowns);\n\t\t}\n\n\t\tconst hints: string[] = [];\n\t\tfor (const warning of warnings) {\n\t\t\tif (hints.length >= 3) break;\n\n\t\t\tconst lastFired = cooldowns.get(warning.pattern);\n\t\t\tif (lastFired !== undefined && currentThoughtNumber - lastFired < 3) {\n\t\t\t\tcontinue; // Still in cooldown\n\t\t\t}\n\n\t\t\thints.push(warning.message);\n\t\t\tcooldowns.set(warning.pattern, currentThoughtNumber);\n\t\t}\n\n\t\treturn hints;\n\t}\n\n\t/**\n\t * Processes a thought through the sequential thinking pipeline.\n\t *\n\t * This method validates the input, adds it to history, formats the output,\n\t * computes quality signals via the ThoughtEvaluator, and returns\n\t * a structured response with metadata about the current state.\n\t *\n\t * @param input - The thought data to process\n\t * @returns A Promise resolving to the formatted tool result containing:\n\t * - `thought_number` — Current thought index\n\t * - `total_thoughts` — Estimated total thoughts\n\t * - `next_thought_needed` — Whether to continue\n\t * - `branches` — Active branch IDs\n\t * - `thought_history_length` — Number of thoughts in history\n\t * - `available_mcp_tools` — MCP tools available for recommendation\n\t * - `available_skills` — Skills available for recommendation\n\t * - `current_step` — Current step recommendation\n\t * - `previous_steps` — Previously recommended steps\n\t * - `remaining_steps` — Upcoming step descriptions\n\t * - `thought_type` — Classification of thought purpose (optional)\n\t * - `quality_score` — Self-assessed quality score 0-1 (optional)\n\t * - `confidence` — Self-assessed confidence 0-1 (optional)\n\t * - `hypothesis_id` — Hypothesis link for verification chains (optional)\n\t * - `confidence_signals` — Computed reasoning quality signals (includes structural_quality and quality_components)\n\t * - `reasoning_stats` — Aggregated reasoning analytics\n\t * - `reasoning_hints` — (Conditional) Actionable hints from pattern analysis, max 3, warning-severity only (optional)\n\t *\n\t * @example\n\t * ```typescript\n\t * const result = await processor.process({\n\t * thought: 'I should read the README file',\n\t * thought_number: 1,\n\t * total_thoughts: 3,\n\t * next_thought_needed: true,\n\t * session_id: asSessionId('analysis')\n\t * });\n\t *\n\t * console.log(result.content[0].text);\n\t * // Output includes: thought_number, total_thoughts, next_thought_needed,\n\t * // branches, thought_history_length, and any recommendations\n\t * ```\n\t */\n\tpublic async process(input: ThoughtProcessInput): Promise<CallToolResult> {\n\t\ttry {\n\t\t\tconst prepared = this._prepareInput(input);\n\t\t\tconst sessionId = prepared.thought.session_id;\n\t\t\tconst operation = async (): Promise<CallToolResult> => {\n\t\t\t\tif (this._sessionLock !== undefined) {\n\t\t\t\t\treturn await this._sessionLock.withLock(sessionId, () => this._processInner(prepared));\n\t\t\t\t}\n\t\t\t\treturn await this._processInner(prepared);\n\t\t\t};\n\t\t\tif (prepared.resetState) {\n\t\t\t\tthis.historyManager.assertSessionResetAuthorized(sessionId);\n\t\t\t\treturn await this._lifecycle.withSessionReset(sessionId, operation);\n\t\t\t}\n\t\t\tthis.historyManager.assertSessionAccessible(sessionId);\n\t\t\treturn await this._lifecycle.runOperation(sessionId, operation);\n\t\t} catch (error) {\n\t\t\treturn this._buildErrorResponse(error);\n\t\t}\n\t}\n\n\t/** Resets one canonical session and its processor-owned auxiliary state. */\n\tpublic async resetSession(sessionId: string): Promise<void> {\n\t\tconst canonicalSessionId = asSessionId(sessionId);\n\t\tthis.historyManager.assertSessionResetAuthorized(canonicalSessionId);\n\t\tconst operation = async (): Promise<void> => {\n\t\t\tawait this.historyManager.resetSessionWithinExclusive(canonicalSessionId, () =>\n\t\t\t\tthis.clearSessionAuxiliaryState(canonicalSessionId)\n\t\t\t);\n\t\t};\n\t\tawait this._lifecycle.withSessionReset(canonicalSessionId, async () => {\n\t\t\tif (this._sessionLock !== undefined) {\n\t\t\t\tawait this._sessionLock.withLock(canonicalSessionId, operation);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait operation();\n\t\t});\n\t}\n\n\t/** Resets all history and processor-owned auxiliary state from a trusted context. */\n\tpublic async resetAll(): Promise<void> {\n\t\tawait this._lifecycle.withGlobalReset(\n\t\t\tasync () =>\n\t\t\t\tawait this.historyManager.resetAllWithinExclusive(() => this.clearAllAuxiliaryState())\n\t\t);\n\t}\n\n\tprivate _prepareInput(input: ThoughtProcessInput): PreparedThought {\n\t\tconst normalized = normalizeInput(input);\n\t\tif (typeof normalized === 'object' && normalized !== null) {\n\t\t\tthis._validateToolArgumentsShape(normalized.tool_arguments);\n\t\t}\n\t\tconst parsed = v.safeParse(SequentialThinkingSchema, normalized);\n\t\tif (!parsed.success) {\n\t\t\tconst firstIssue = parsed.issues[0];\n\t\t\tconst field = firstIssue?.path?.map((item) => String(item.key)).join('.') || 'input';\n\t\t\tthrow new ValidationError(field, firstIssue?.message ?? 'Invalid input');\n\t\t}\n\n\t\tconst internal = normalizeInput(parsed.output) as ThoughtData & {\n\t\t\tregister_branch_id?: string;\n\t\t};\n\t\tconst registerBranchId =\n\t\t\tinternal.register_branch_id === undefined\n\t\t\t\t? undefined\n\t\t\t\t: asBranchId(internal.register_branch_id);\n\t\tconst thought = { ...internal };\n\t\tdelete thought.register_branch_id;\n\t\tconst { result, warnings } = this.validateInput(thought);\n\t\tthis._validateStatelessNewTypes(result);\n\t\treturn {\n\t\t\tthought: result,\n\t\t\tresetState: result.reset_state === true,\n\t\t\tregisterBranchId,\n\t\t\tvalidationWarnings: warnings,\n\t\t};\n\t}\n\n\tprivate _buildErrorResponse(error: unknown): CallToolResult {\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text',\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\t...(error instanceof SequentialThinkingError && { code: error.code }),\n\t\t\t\t\t\t\terror: getErrorMessage(error),\n\t\t\t\t\t\t\tmessage: getErrorMessage(error),\n\t\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t\tisError: true,\n\t\t};\n\t}\n\n\tprivate static _emptySessionSnapshot(): HistorySessionSnapshot {\n\t\treturn {\n\t\t\thistory: [],\n\t\t\tbranches: {},\n\t\t\tverificationTargets: new Map(),\n\t\t\tbranchIds: [],\n\t\t\tavailableMcpTools: undefined,\n\t\t\tavailableSkills: undefined,\n\t\t};\n\t}\n\n\t/** Clears all processor-owned state for one removed session. */\n\tpublic clearSessionAuxiliaryState(sessionId: SessionId): void {\n\t\tthis._hintCooldowns.delete(sessionId);\n\t\tthis._suspensionStore?.clearSession(sessionId);\n\t\tthis._outcomeRecorder?.clearOutcomes(sessionId);\n\t\tthis._calibrator?.clearSession(sessionId);\n\t}\n\n\t/** Clears all processor-owned state after global reset or successful shutdown. */\n\tpublic clearAllAuxiliaryState(): void {\n\t\tthis._suspensionStore?.clearAll();\n\t\tthis._outcomeRecorder?.clearAllOutcomes();\n\t\tthis._calibrator?.clearAll();\n\t\tthis._hintCooldowns.clear();\n\t}\n\n\tprivate _validateToolArgumentsShape(toolArguments: unknown): void {\n\t\ttry {\n\t\t\tenforceJsonShape(toolArguments ?? {});\n\t\t} catch (error) {\n\t\t\tif (error instanceof JsonShapeError) {\n\t\t\t\tthrow new ValidationError('tool_arguments', error.reason);\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\tprivate async _processInner(prepared: PreparedThought): Promise<CallToolResult> {\n\t\tconst { thought, resetState, registerBranchId } = prepared;\n\t\tconst sessionId = thought.session_id;\n\t\tif (resetState) this.historyManager.assertSessionResetAuthorized(sessionId);\n\t\tconst validationSnapshot = resetState\n\t\t\t? ThoughtProcessor._emptySessionSnapshot()\n\t\t\t: this.historyManager.inspectSession(sessionId);\n\t\tif (!resetState) {\n\t\t\tif (!thought.available_mcp_tools && validationSnapshot.availableMcpTools) {\n\t\t\t\tthought.available_mcp_tools = [...validationSnapshot.availableMcpTools];\n\t\t\t}\n\t\t\tif (!thought.available_skills && validationSnapshot.availableSkills) {\n\t\t\t\tthought.available_skills = [...validationSnapshot.availableSkills];\n\t\t\t}\n\t\t}\n\t\tconst resolveThoughtReference = resetState\n\t\t\t? () => ({ kind: 'missing' as const })\n\t\t\t: (thoughtNumber: number) =>\n\t\t\t\t\tthis.historyManager.resolveThoughtReference(sessionId, thoughtNumber);\n\t\tconst {\n\t\t\tresult: checkedInput,\n\t\t\twarnings: refWarnings,\n\t\t\tresolvedReferences,\n\t\t} = validateThoughtCrossReferences(thought, {\n\t\t\tsnapshot: validationSnapshot,\n\t\t\tresolveThoughtReference,\n\t\t\tstrictBranchReferences: resetState || registerBranchId !== undefined,\n\t\t\tlogger: this._logger,\n\t\t});\n\t\tconst verificationOutcome = prepareVerificationOutcome({\n\t\t\tinput: checkedInput,\n\t\t\tsnapshot: validationSnapshot,\n\t\t\tresolvedReferences,\n\t\t\tsessionId,\n\t\t\trecorder: this._outcomeRecorder,\n\t\t});\n\t\tconst allWarnings = [...prepared.validationWarnings, ...refWarnings];\n\t\tconst validated = this._validateNewTypes(checkedInput);\n\t\tconst admissionContext: ThoughtAdmissionContext = { resolvedReferences };\n\t\tif (resetState && validated.thought_type === 'tool_observation') {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t'tool_observation cannot resume a suspension in reset replacement state'\n\t\t\t);\n\t\t}\n\n\t\tif (resetState) {\n\t\t\tawait this.historyManager.resetSessionWithinExclusive(sessionId, () =>\n\t\t\t\tthis.clearSessionAuxiliaryState(sessionId)\n\t\t\t);\n\t\t\tthis.log('State reset for session', { sessionId });\n\t\t}\n\t\tthis.historyManager.assertThoughtIdentityAvailable(checkedInput);\n\t\tif (registerBranchId !== undefined) {\n\t\t\tthis.historyManager.registerBranch(sessionId, registerBranchId);\n\t\t}\n\n\t\t// Tool-interleave suspend path: persist the tool_call thought, then return\n\t\t// a `suspended` envelope without running strategy/evaluator.\n\t\tif (validated.thought_type === 'tool_call' && this._suspensionStore) {\n\t\t\treturn this._handleToolCall(validated, admissionContext);\n\t\t}\n\n\t\t// Tool-interleave resume path: consume the suspension and continue the\n\t\t// normal pipeline (addThought → format → evaluate → strategy).\n\t\tif (validated.thought_type === 'tool_observation' && this._suspensionStore) {\n\t\t\tawait this._handleToolObservation(validated, admissionContext);\n\t\t} else {\n\t\t\tthis.historyManager.addThought(checkedInput, admissionContext);\n\t\t}\n\t\tthis._recordVerificationOutcome(verificationOutcome, sessionId);\n\n\t\tconst formattedThought = this.thoughtFormatter.formatThought(checkedInput);\n\t\tthis.log(formattedThought, { sessionId });\n\n\t\tconst signals = this._collectReasoningSignals(checkedInput);\n\n\t\t// Strategy decision — pluggable reasoning policy hook.\n\t\t// Built after history/stats so strategies see the latest state.\n\t\tconst decision = this._runStrategy(checkedInput, signals.evidence, signals.reasoningStats);\n\n\t\treturn this._buildSuccessResponse({\n\t\t\tthought: checkedInput,\n\t\t\treasoning: {\n\t\t\t\tconfidenceSignals: signals.confidenceSignals,\n\t\t\t\treasoningStats: signals.reasoningStats,\n\t\t\t\tgraphContext:\n\t\t\t\t\tsignals.evidence === undefined\n\t\t\t\t\t\t? undefined\n\t\t\t\t\t\t: buildGraphContext(sessionId, checkedInput, signals.evidence),\n\t\t\t\treasoningHints: signals.reasoningHints,\n\t\t\t},\n\t\t\tdecision,\n\t\t\twarnings: allWarnings,\n\t\t});\n\t}\n\n\tprivate _recordVerificationOutcome(\n\t\toutcome: ReturnType<typeof prepareVerificationOutcome>,\n\t\tsessionId: SessionId\n\t): void {\n\t\tif (outcome === undefined) return;\n\t\tif (this._outcomeRecorder?.enabled === true) {\n\t\t\tthis._outcomeRecorder.recordVerification(outcome);\n\t\t}\n\t\tif (this._calibrator?.enabled === true) this._calibrator.refit(sessionId);\n\t}\n\n\tprivate _collectReasoningSignals(input: ThoughtData): ReasoningSignalBundle {\n\t\tconst sessionId = input.session_id;\n\t\tconst history = this.historyManager.getHistory(sessionId);\n\t\tconst branches = this.historyManager.getBranches(sessionId);\n\t\tconst evidence = this._buildActiveEvidence(sessionId, history, branches);\n\t\tconst graphScope =\n\t\t\tevidence?.graph === undefined ? {} : { activeGraph: { sessionId, view: evidence.graph } };\n\t\tconst verificationTargets = this.historyManager.getVerificationTargets(sessionId);\n\t\tconst { confidenceSignals, reasoningStats, patternSignals } =\n\t\t\tthis._thoughtEvaluator.computeAdmissionSignals(history, branches, {\n\t\t\t\tcurrentThought: input,\n\t\t\t\tsessionId,\n\t\t\t\tverificationTargets,\n\t\t\t\t...graphScope,\n\t\t\t});\n\t\tconst reasoningHints = this._generateHints(patternSignals, input.thought_number, sessionId);\n\n\t\treturn {\n\t\t\tevidence,\n\t\t\tconfidenceSignals,\n\t\t\treasoningStats,\n\t\t\treasoningHints,\n\t\t};\n\t}\n\n\tprivate _buildActiveEvidence(\n\t\tsessionId: SessionId,\n\t\thistory: readonly ThoughtData[],\n\t\tbranches: Record<BranchId, ThoughtData[]>\n\t): ActiveEvidenceProjection | undefined {\n\t\ttry {\n\t\t\treturn buildActiveEvidenceProjection({\n\t\t\t\tsessionId,\n\t\t\t\thistory,\n\t\t\t\tbranches,\n\t\t\t\tedgeStore: this._getEdgeStore(),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthis._logger.warn('Active evidence projection failed — omitting graph and strategy hints', {\n\t\t\t\tsessionId,\n\t\t\t\terror: getErrorMessage(error),\n\t\t\t});\n\t\t\treturn undefined;\n\t\t}\n\t}\n\n\tprivate _buildSuccessResponse(state: ProcessedThoughtResponseState): CallToolResult {\n\t\tconst sessionId = state.thought.session_id;\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text' as const,\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tthought_number: state.thought.thought_number,\n\t\t\t\t\t\t\ttotal_thoughts: state.thought.total_thoughts,\n\t\t\t\t\t\t\tnext_thought_needed: state.thought.next_thought_needed ?? true,\n\t\t\t\t\t\t\tbranches: this.historyManager.getBranchIds(sessionId),\n\t\t\t\t\t\t\tthought_history_length: this.historyManager.getHistoryLength(sessionId),\n\t\t\t\t\t\t\tavailable_mcp_tools: state.thought.available_mcp_tools,\n\t\t\t\t\t\t\tavailable_skills: state.thought.available_skills,\n\t\t\t\t\t\t\tcurrent_step: state.thought.current_step,\n\t\t\t\t\t\t\tprevious_steps: state.thought.previous_steps,\n\t\t\t\t\t\t\tremaining_steps: state.thought.remaining_steps,\n\t\t\t\t\t\t\tthought_type: state.thought.thought_type,\n\t\t\t\t\t\t\tquality_score: state.thought.quality_score,\n\t\t\t\t\t\t\tconfidence: state.thought.confidence,\n\t\t\t\t\t\t\thypothesis_id: state.thought.hypothesis_id,\n\t\t\t\t\t\t\tconfidence_signals: state.reasoning.confidenceSignals,\n\t\t\t\t\t\t\treasoning_stats: state.reasoning.reasoningStats,\n\t\t\t\t\t\t\t...(state.reasoning.graphContext !== undefined && {\n\t\t\t\t\t\t\t\tgraph_context: state.reasoning.graphContext,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...(state.reasoning.reasoningHints.length > 0 && {\n\t\t\t\t\t\t\t\treasoning_hints: state.reasoning.reasoningHints,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...(state.decision !== undefined && { strategy_hint: state.decision }),\n\t\t\t\t\t\t\t...(state.warnings.length > 0 && { warnings: state.warnings.slice(0, 3) }),\n\t\t\t\t\t\t\tsession_id: sessionId,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Run the configured reasoning strategy and return its decision.\n\t * Strategy errors omit the decision from the public response.\n\t * @private\n\t */\n\tprivate _runStrategy(\n\t\tcurrentThought: ThoughtData,\n\t\tevidence: ActiveEvidenceProjection | undefined,\n\t\tstats: ReturnType<ThoughtEvaluator['computeReasoningStats']>\n\t): StrategyDecision | undefined {\n\t\tconst sessionId = currentThought.session_id;\n\t\tlet decision: StrategyDecision | undefined;\n\t\ttry {\n\t\t\tif (evidence !== undefined) {\n\t\t\t\tdecision = this.strategy.decide({ sessionId, evidence, stats, currentThought });\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tthis._logger.warn('Reasoning strategy threw — omitting strategy hint', {\n\t\t\t\tstrategy: this.strategy.name,\n\t\t\t\terror: getErrorMessage(error),\n\t\t\t});\n\t\t}\n\n\t\t// Auto-compression trigger: when strategy terminates a branch and\n\t\t// compression is enabled, summarize the branch subtree. Compression\n\t\t// failures must NEVER break the thought pipeline.\n\t\tif (decision?.action === 'terminate' && this._compressionService && currentThought.branch_id) {\n\t\t\ttry {\n\t\t\t\tconst branchRoot = this._findBranchRoot(sessionId, currentThought.branch_id);\n\t\t\t\tif (branchRoot) {\n\t\t\t\t\tthis._compressionService.compressBranch(\n\t\t\t\t\t\tsessionId,\n\t\t\t\t\t\tcurrentThought.branch_id,\n\t\t\t\t\t\tbranchRoot as ThoughtId\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (err) {\n\t\t\t\tthis._logger.debug('Compression auto-trigger failed', {\n\t\t\t\t\terror: getErrorMessage(err),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\treturn decision;\n\t}\n\n\t/**\n\t * Locate the root thought id for a branch.\n\t * Prefers GraphView.branchThoughts() when an EdgeStore is available;\n\t * falls back to historyManager.getBranches(sessionId)[branchId][0].id.\n\t * @private\n\t */\n\tprivate _findBranchRoot(sessionId: SessionId, branchId: BranchId): string | undefined {\n\t\tconst edgeStore = this._getEdgeStore();\n\t\tconst branches = this.historyManager.getBranches(sessionId);\n\t\tconst branchList = branches[branchId];\n\t\tconst firstId = branchList?.[0]?.id;\n\t\tif (edgeStore && firstId) {\n\t\t\tconst graph = new GraphView(edgeStore);\n\t\t\tconst ids = graph.branchThoughts(sessionId, firstId);\n\t\t\tif (ids.length > 0) return ids[0];\n\t\t}\n\t\treturn firstId;\n\t}\n\n\t/** Access the EdgeStore via IHistoryManager. @private */\n\tprivate _getEdgeStore(): IEdgeStore | undefined {\n\t\treturn this.historyManager.getEdgeStore();\n\t}\n\n\t/**\n\t * Validates and normalizes thought input.\n\t *\n\t * Ensures that thought numbers are consistent and within valid ranges.\n\t * If `thought_number` exceeds `total_thoughts`, `total_thoughts` is\n\t * automatically adjusted to match and a warning is emitted.\n\t *\n\t * @param input - The input to validate\n\t * @returns Object with validated input and any warnings generated\n\t * @private\n\t *\n\t * @example\n\t * ```typescript\n\t * // Auto-adjusts total_thoughts when thought_number exceeds it\n\t * const { result, warnings } = this.validateInput(input);\n\t * // result.total_thoughts === 10 (auto-adjusted from 5)\n\t * // warnings === ['Auto-adjusted total_thoughts from 5 to 10 to match thought_number']\n\t * ```\n\t */\n\tprivate validateInput(input: ThoughtData): {\n\t\tresult: ThoughtData;\n\t\twarnings: string[];\n\t} {\n\t\tconst warnings: string[] = [];\n\t\tif (input.thought_number > input.total_thoughts) {\n\t\t\tconst originalTotal = input.total_thoughts;\n\t\t\twarnings.push(\n\t\t\t\t`[${WARNING_CODES.TOTAL_THOUGHTS_ADJUSTED}] Auto-adjusted total_thoughts from ${originalTotal} to ${input.thought_number} to match thought_number`\n\t\t\t);\n\t\t\tthis._logger.warn('Auto-adjusted total_thoughts to match thought_number', {\n\t\t\t\tthought_number: input.thought_number,\n\t\t\t\toriginal_total_thoughts: originalTotal,\n\t\t\t\tadjusted_total_thoughts: input.thought_number,\n\t\t\t});\n\t\t\tinput.total_thoughts = input.thought_number;\n\t\t}\n\t\treturn { result: input, warnings };\n\t}\n\n\t/**\n\t * Validate new thought-type invariants behind feature flags.\n\t * @private\n\t */\n\tprivate _validateStatelessNewTypes(input: ThoughtData): void {\n\t\tconst t = input.thought_type;\n\t\tif ((t === 'tool_call' || t === 'tool_observation') && !this._features.toolInterleave) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t`Type '${t}' requires the toolInterleave feature flag. Set TRACELATTICE_FEATURES_TOOL_INTERLEAVE=true to enable it.`\n\t\t\t);\n\t\t}\n\t\tif (\n\t\t\t(t === 'assumption' || t === 'decomposition' || t === 'backtrack') &&\n\t\t\t!this._features.newThoughtTypes\n\t\t) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'thought_type',\n\t\t\t\t`Type '${t}' requires the newThoughtTypes feature flag. Set TRACELATTICE_FEATURES_NEW_THOUGHT_TYPES=true to enable it, or use '${ThoughtProcessor._getWorkaroundType(t)}' type as a workaround.`\n\t\t\t);\n\t\t}\n\t\tif (t === 'tool_call') {\n\t\t\tif (!input.tool_name) {\n\t\t\t\tthrow new InvalidToolCallError(\n\t\t\t\t\t'tool_call thought ' + input.thought_number + ' missing required tool_name'\n\t\t\t\t);\n\t\t\t}\n\t\t\tthis._validateToolName(input.tool_name);\n\t\t}\n\t\tif (t === 'tool_observation' && !input.continuation_token) {\n\t\t\tthrow new ValidationError(\n\t\t\t\t'continuation_token',\n\t\t\t\t'tool_observation thought ' + input.thought_number + ' missing continuation_token'\n\t\t\t);\n\t\t}\n\t\tif (t === 'backtrack') {\n\t\t\tif (input.backtrack_target === undefined) {\n\t\t\t\tthrow new ValidationError(\n\t\t\t\t\t'backtrack_target',\n\t\t\t\t\t'backtrack thought ' + input.thought_number + ' requires backtrack_target'\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (input.backtrack_target > input.thought_number) {\n\t\t\t\tthrow new InvalidBacktrackError(\n\t\t\t\t\t'backtrack_target ' +\n\t\t\t\t\t\tinput.backtrack_target +\n\t\t\t\t\t\t' must be <= thought_number ' +\n\t\t\t\t\t\tinput.thought_number\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (t === 'tool_call') {\n\t\t\tthis._validateToolArgumentsShape(input.tool_arguments);\n\t\t}\n\t}\n\n\tprivate _validateNewTypes(input: ThoughtData): ValidatedThought {\n\t\treturn input as ValidatedThought;\n\t}\n\n\t/**\n\t * Validate a tool_call's tool_name against the configured allowlist.\n\t *\n\t * Fails closed: if no tool registry was wired, all tool_call invocations are\n\t * rejected. This prevents arbitrary tool name injection through the protocol.\n\t *\n\t * @param toolName - The tool name from the tool_call thought\n\t * @throws {UnknownToolError} When no registry is wired or the tool is not registered\n\t * @private\n\t */\n\tprivate _validateToolName(toolName: string): void {\n\t\tif (!this._toolRegistry) {\n\t\t\tthrow new UnknownToolError(\n\t\t\t\ttoolName,\n\t\t\t\t`Tool '${toolName}' rejected: no tool registry configured. Tool interleave requires a registered allowlist.`\n\t\t\t);\n\t\t}\n\t\tif (!this._toolRegistry.has(toolName)) {\n\t\t\tthrow new UnknownToolError(toolName);\n\t\t}\n\t}\n\n\t/**\n\t * Returns a workaround thought type for a feature-flagged type.\n\t * @private\n\t */\n\tprivate static _getWorkaroundType(t: 'assumption' | 'decomposition' | 'backtrack'): string {\n\t\tswitch (t) {\n\t\t\tcase 'assumption':\n\t\t\t\treturn 'regular';\n\t\t\tcase 'decomposition':\n\t\t\t\treturn 'hypothesis';\n\t\t\tcase 'backtrack':\n\t\t\t\treturn 'regular';\n\t\t\tdefault:\n\t\t\t\tassertNever(t);\n\t\t}\n\t}\n\n\t/**\n\t * Persist a tool_call thought and return a `suspended` envelope.\n\t * Strategy/evaluator are intentionally skipped.\n\t * @private\n\t */\n\tprivate _handleToolCall(\n\t\tinput: ToolCallThought,\n\t\tadmissionContext: ThoughtAdmissionContext\n\t): CallToolResult {\n\t\tif (input.id === undefined) {\n\t\t\tthrow new ValidationError('id', 'tool_call requires an admitted thought id');\n\t\t}\n\t\tthis.historyManager.addThought(input, admissionContext);\n\t\tif (!this._suspensionStore) {\n\t\t\tthrow new ValidationError('thought_type', 'tool_call requires suspensionStore');\n\t\t}\n\t\tconst record: SuspensionRecord = this._suspensionStore.suspend({\n\t\t\tsessionId: input.session_id,\n\t\t\ttoolCallThoughtNumber: input.thought_number,\n\t\t\ttoolCallThoughtId: input.id,\n\t\t\ttoolName: input.tool_name,\n\t\t\ttoolArguments: input.tool_arguments ?? {},\n\t\t\texpiresAt: 0,\n\t\t});\n\t\treturn {\n\t\t\tcontent: [\n\t\t\t\t{\n\t\t\t\t\ttype: 'text' as const,\n\t\t\t\t\ttext: JSON.stringify(\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstatus: 'suspended',\n\t\t\t\t\t\t\tcontinuation_token: record.token,\n\t\t\t\t\t\t\ttool_name: record.toolName,\n\t\t\t\t\t\t\ttool_arguments: record.toolArguments,\n\t\t\t\t\t\t\texpires_at: record.expiresAt,\n\t\t\t\t\t\t\tthought_number: input.thought_number,\n\t\t\t\t\t\t\ttotal_thoughts: input.total_thoughts,\n\t\t\t\t\t\t\tsession_id: input.session_id,\n\t\t\t\t\t\t},\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\t2\n\t\t\t\t\t),\n\t\t\t\t},\n\t\t\t],\n\t\t};\n\t}\n\n\t/**\n\t * Resume from a tool_observation and atomically admit it before consuming the record.\n\t * @private\n\t */\n\tprivate async _handleToolObservation(\n\t\tinput: ToolObservationThought,\n\t\tadmissionContext: ThoughtAdmissionContext\n\t): Promise<void> {\n\t\tif (!this._suspensionStore) {\n\t\t\tthrow new ValidationError('thought_type', 'tool_observation requires suspensionStore');\n\t\t}\n\t\tawait this._suspensionStore.compareAndAdmit(\n\t\t\tinput.continuation_token,\n\t\t\tinput.session_id,\n\t\t\t(record) => {\n\t\t\t\tthis.historyManager.addThought(input, {\n\t\t\t\t\t...admissionContext,\n\t\t\t\t\ttoolInvocationSourceThoughtId: record.toolCallThoughtId,\n\t\t\t\t});\n\t\t\t}\n\t\t);\n\t}\n}\n"],"names":["ThoughtProcessor","Map","historyManager","thoughtFormatter","thoughtEvaluator","logger","strategy","SequentialStrategy","_compressionService","_suspensionStore","_toolRegistry","_features","DEFAULT_FLAGS","_sessionLock","_outcomeRecorder","_lifecycle","SessionLifecycleCoordinator","_calibrator","NullLogger","message","meta","patterns","currentThoughtNumber","sessionId","warnings","p","a","b","pa","pb","cooldowns","undefined","hints","warning","lastFired","input","prepared","operation","error","canonicalSessionId","asSessionId","normalized","normalizeInput","parsed","v","SequentialThinkingSchema","firstIssue","field","item","String","ValidationError","internal","registerBranchId","asBranchId","thought","result","JSON","SequentialThinkingError","getErrorMessage","toolArguments","enforceJsonShape","JsonShapeError","resetState","validationSnapshot","resolveThoughtReference","thoughtNumber","checkedInput","refWarnings","resolvedReferences","validateThoughtCrossReferences","verificationOutcome","prepareVerificationOutcome","allWarnings","validated","admissionContext","formattedThought","signals","decision","buildGraphContext","outcome","history","branches","evidence","graphScope","verificationTargets","confidenceSignals","reasoningStats","patternSignals","reasoningHints","buildActiveEvidenceProjection","state","currentThought","stats","branchRoot","err","branchId","edgeStore","branchList","firstId","graph","GraphView","ids","originalTotal","WARNING_CODES","t","InvalidToolCallError","InvalidBacktrackError","toolName","UnknownToolError","assertNever","record"],"mappings":";;;;;;;;;;;;;;;;AAoJO,MAAMA;;;;;;;;;;;;IAEJ,QAAgB;IAGP,kBAAoC;IAM7C,iBAAiB,IAAIC,MAA2C;IAiBxE,YACSC,cAA+B,EAC/BC,gBAAkC,EAC1CC,gBAAkC,EAClCC,MAAe,EACEC,WAA+B,IAAIC,oBAAoB,EACvDC,mBAAwC,EACxCC,gBAAmC,EACnCC,aAA6B,EAC7BC,YAA0BC,aAAa,EACvCC,YAA2B,EAC3BC,gBAAmC,EACnCC,aAA0C,IAAIC,6BAA6B,EAC3EC,WAAyB,CACzC;aAbOf,cAAc,GAAdA;aACAC,gBAAgB,G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AAM,UAAU;oBAC7B,GACA,MACA;gBAEF;aACA;QACF;IACD;IAMA,MAAc,uBACbA,KAA6B,EAC7BuC,gBAAyC,EACzB;QAChB,IAAI,CAAC,IAAI,CAAC,gBAAgB,EACzB,MAAM,IAAIxB,gBAAgB,gBAAgB;QAE3C,MAAM,IAAI,CAAC,gBAAgB,CAAC,eAAe,CAC1Cf,MAAM,kBAAkB,EACxBA,MAAM,UAAU,EAChB,CAAC2E;YACA,IAAI,CAAC,cAAc,CAAC,UAAU,CAAC3E,OAAO;gBACrC,GAAGuC,gBAAgB;gBACnB,+BAA+BoC,OAAO,iBAAiB;YACxD;QACD;IAEF;AACD"}
|
|
@@ -16,4 +16,9 @@ export declare function resolvedVerificationTarget(thought: ThoughtData, referen
|
|
|
16
16
|
export declare function resolveVerificationLinks(history: readonly ThoughtData[], branches: ActiveThoughtBranches, admissionTargets?: ReadonlyMap<ThoughtId, ThoughtId>): VerificationLinks;
|
|
17
17
|
export declare function collectActiveMainThoughts(history: readonly ThoughtData[], branches: ActiveThoughtBranches): ThoughtData[];
|
|
18
18
|
export declare function collectActiveThoughts(history: readonly ThoughtData[], branches: ActiveThoughtBranches): ThoughtData[];
|
|
19
|
+
/** Visit each retained record once; later retractions delete earlier copies without reordering. */
|
|
20
|
+
export declare function collectActiveEvidence(history: readonly ThoughtData[], branches: ActiveThoughtBranches): {
|
|
21
|
+
readonly thoughts: ThoughtData[];
|
|
22
|
+
readonly mainCount: number;
|
|
23
|
+
};
|
|
19
24
|
//# sourceMappingURL=VerificationLinks.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"VerificationLinks.d.ts","sourceRoot":"","sources":["../../../src/core/evaluator/VerificationLinks.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACxD,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,KAAK,EAAE,WAAW,EAAE,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